Cotton code
6398 lines · 301.2 KB · RustRaw
//! The client half, held for the app: the replica, the ingest queue, and what//! the sync loop is doing.//!//! Design M6 puts all of this in `cotton-client` and says Swift never touches//! sync. This controller is the thin thing that OWNS one of each per data//! directory and answers the five FFI methods over it — the same shape as//! [`super::controller::ServerController`], and for the same reason: a method//! is a question, and something has to be holding the answer between two of//! them.//!//! **Attaching is lazy and it is a STATE.** A Mac that nobody has connected yet//! has no workspace, no replica, and nothing to sync; that is the ordinary//! condition of a fresh install, not an error, so every method answers//! `connected: false` and says why rather than refusing. The connection record//! is re-read on every attach, because the person may have joined a server//! since the last question.use std::sync::{Arc, Mutex};use cotton_client::connection::held::HeldNotes;use cotton_client::connection::{read_connection, read_record, StoredConnection};use cotton_client::layout::Layout;use cotton_client::replica::{    open_replica_with, MigrationEvent, OpenReplicaInput, ReadPool, ReadReplica, Replica, ReplicaError,};use cotton_client::seams::op_ids;use cotton_client::seams::{Clock, Random, SystemClock, SystemRandom};use cotton_client::sync::cycle::{current_held, current_pending};use cotton_store::driver::Driver;use serde_json::{json, Value};use crate::authoring::WriteInput;use crate::events::{EventBus, EventKind};use crate::shell::file::ReadFile;use crate::shell::feed_index::{self, FeedIndex};use crate::shell::held::{OpenFiles, OPEN_HANDLES};thread_local! {    /// The database the call on THIS thread named (`database`, beside the    /// method's own arguments); `None` is the device's own.    ///    /// A call is answered on the thread that made it, start to finish, so the    /// name rides the thread rather than every signature between the dispatch    /// and the two places a file is taken ([`ClientController::attached_replica`],    /// [`ClientController::attached_readers`]). The dispatch sets it for every    /// call — absent included — so a subscriber that re-enters the core from    /// inside a write's event is answered from the database IT named.    static NAMED: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };}/// One call's named database, in force until dropped; the name before it/// comes back then. Made by [`ClientController::name_database`].pub struct NamedDatabase {    before: Option<String>,}impl Drop for NamedDatabase {    fn drop(&mut self) {        NAMED.with(|named| *named.borrow_mut() = self.before.take());    }}/// The database this call names, `None` for the personal one.pub(crate) fn named_database() -> Option<String> {    NAMED.with(|named| named.borrow().clone())}thread_local! {    /// Whether the read on THIS thread takes the read pool's SHORT lane    /// (`ReadPool::take_short`) — set by [`on_short_lane`] for the reads a    /// screen cannot be drawn without, so every connection they take on the    /// way (the sync status, the file, a named database) is a short one.    static SHORT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// The reads the pool's SHORT lane is reserved for, BY NAME, and nothing/// else (architect, 16 Oct 2026 21:58 IST): Home's card set (`read.home`),/// the catalogue its board is drawn from (`definitions.catalogue`) and Today/// (`read.day`). A closed set, so no other read can be put on the lane — the/// reservation is what keeps long reads out; the lane's deadline only catches/// a bug. On 16 Oct 2026 these queued behind four long reads on one lane and/// Home was refused at 30 s (readpool).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum ShortRead {    Home,    Catalogue,    Day,}impl ShortRead {    pub(crate) const ALL: [ShortRead; 3] = [ShortRead::Home, ShortRead::Catalogue, ShortRead::Day];    /// The method the app calls.    pub(crate) fn method(self) -> &'static str {        match self {            ShortRead::Home => "read.home",            ShortRead::Catalogue => "definitions.catalogue",            ShortRead::Day => "read.day",        }    }    /// The short read `method` is, if it is one.    pub(crate) fn named(method: &str) -> Option<ShortRead> {        Self::ALL.into_iter().find(|read| read.method() == method)    }}/// Run `work` — the short read `read` — with every read connection it takes/// on the pool's SHORT lane, which no list or walk of the file ever holds. A/// run over [`cotton_client::replica::SHORT_READ_SLOW`] is logged as a/// finding with its duration, never refused.pub(crate) fn on_short_lane<T>(read: ShortRead, work: impl FnOnce() -> T) -> T {    struct Restore(bool);    impl Drop for Restore {        fn drop(&mut self) {            SHORT.with(|short| short.set(self.0));        }    }    let began = std::time::Instant::now();    let steps = cotton_store::driver::Driver::thread_steps();    let answer = {        let _restore = Restore(SHORT.with(|short| short.replace(true)));        work()    };    let took = began.elapsed();    if took >= cotton_client::replica::SHORT_READ_SLOW {        crate::shell::diagnostics::read_took(            &format!("short lane over {} ms: {}", cotton_client::replica::SHORT_READ_SLOW.as_millis(), read.method()),            took,            cotton_store::driver::Driver::thread_steps().saturating_sub(steps),            &Value::Null,        );    }    answer}impl ClientController {    /// This device's admission, from the connection record that exists before    /// the first replica row arrives. Replica read connections intentionally    /// carry no writer binding, so callers must not infer this from their    /// `Driver`.    pub fn device_scope(&self) -> Result<cotton_core::device::scope::DeviceScope, String> {        let connection = read_connection(&self.layout.connection_json()).map_err(|error| error.to_string())?;        cotton_core::device::scope::DeviceScope::parse(connection.as_ref().and_then(|record| record.device_scope.as_deref()))            .map_err(str::to_string)    }    /// A SHORT read of a held database nothing in this process has opened yet    /// reads its file directly (`ReadReplica::open_short`), never through the    /// database's open — its turn, ladder and rebuild, which a catch-up holds    /// across its folds. `None` for every other read, a database already open    /// (its pool's short lane serves it), or one not here yet.    fn short_direct(&self, database: &str) -> Option<Result<ReadReplica, String>> {        if !SHORT.with(std::cell::Cell::get) {            return None;        }        if self.placing.load(std::sync::atomic::Ordering::SeqCst) || self.removed_from(database).is_some() {            return None;        }        let own_open = self            .state            .lock()            .ok()            .is_some_and(|state| state.as_ref().is_some_and(|attached| attached.workspace_id == database));        if own_open || self.others.lock().ok()?.get(database).is_some() || self.arriving(database).is_some() {            return None;        }        let path = self.layout.replica(database);        if !path.is_file() {            return None;        }        Some(ReadReplica::open_short(&path, &self.self_device_id().unwrap_or_default()).map_err(read_not_open))    }}/// A connection of `readers` on the lane this thread's read takes.#[track_caller]fn take_reader(readers: &ReadPool) -> cotton_store::Result<cotton_client::replica::ReadLease<'_>> {    if SHORT.with(std::cell::Cell::get) {        readers.take_short()    } else {        readers.take()    }}/// The least time between two passes the schedule starts over the joined/// databases. The personal loop reports several statuses a pass.pub const JOINED_PASS_FLOOR_MS: i64 = 20_000;/// What a cycle's failure says to a person.fn cycle_failure_sentence(failure: &cotton_client::sync::cycle::CycleFailure) -> String {    use cotton_client::sync::cycle::CycleFailure;    match failure {        CycleFailure::TerminalDevice { sentence, .. } => sentence.clone(),        CycleFailure::MacBehind { .. } => cotton_client::sync::cycle::MAC_BEHIND_SENTENCE.to_string(),        CycleFailure::Transient { message, .. }        | CycleFailure::Refused { message, .. }        | CycleFailure::PhoneBehind { message }        | CycleFailure::Unlisted { message } => message.clone(),    }}/// The connection record under `layout` with only the places this app's/// scope admits (`super::scope`): what every held, synced or opened set reads.fn scoped_record(layout: &Layout) -> Result<Option<cotton_client::connection::ConnectionRecord>, String> {    let scope = super::scope::kept(layout);    Ok(read_record(&layout.connection_json())        .map_err(|error| error.to_string())?        .map(|record| super::scope::admitted(record, &scope)))}/// Every database the connection record under `layout` says this device/// holds: its own first, then each other one the server last listed for it.fn held_ids(layout: &Layout) -> Result<Vec<String>, String> {    let record = scoped_record(layout)?        .ok_or_else(not_connected_sentence)?;    let mut held: Vec<String> = record.mine.workspace_id.clone().into_iter().collect();    for place in record.places {        // A database this device was removed from is in its Bin and held for        // nothing else: no open, read or write reaches it (ruling, 16 Oct 2026).        if place.available && place.removed_at.is_none() && !held.contains(&place.id) {            held.push(place.id);        }    }    Ok(held)}/// Every database served to this device by the Mac that serves `database` —/// the databases at its origin (`origin_groups`: the household's address, or/// one other person's Mac), itself included. Just itself when the record/// names no such group.fn mac_peers(layout: &Layout, database: &str) -> Vec<String> {    scoped_record(layout)        .ok()        .flatten()        .and_then(|record| {            cotton_client::connection::joined::origin_groups(&record)                .into_iter()                .find(|group| group.databases.iter().any(|id| id == database))        })        .map(|group| group.databases)        .unwrap_or_else(|| vec![database.to_string()])}/// The databases the device's own loop syncs: its own, then each other one/// held at the household's address. A database joined at another person's Mac/// is not among them — it syncs at its own origin.fn household_ids(layout: &Layout) -> Vec<String> {    scoped_record(layout)        .ok()        .flatten()        .and_then(|record| {            cotton_client::connection::joined::origin_groups(&record)                .into_iter()                .find(|group| !group.is_joined())        })        .map(|group| group.databases)        .unwrap_or_default()}/// Every database this device syncs, at ANY origin: its own, the others at/// the household's address, then each joined at another person's Mac. What a/// pass over this device's BYTES covers — the uploads, the thumbnails, the/// keep sweep and the budget — because each of those is about this device's/// disk and each database's own Mac (`RoutedMedia`), not about one origin./// One this device was removed from is in none: its copy is read-only.fn syncing_ids(layout: &Layout) -> Vec<String> {    scoped_record(layout)        .ok()        .flatten()        .map(|record| {            cotton_client::connection::joined::origin_groups(&record)                .into_iter()                .flat_map(|group| group.databases)                .collect()        })        .unwrap_or_default()}/// THE TURNS TO OPEN the held databases other than the device's own: one per/// database, so two questions naming the same closed database open it once,/// while a question about a database that is already open never waits on/// another's open — a heal, a log replay or a ladder on one file of twelve/// held the whole set's lock before (12 Oct 2026, the owner's phone after an/// update, when every held copy climbs a ladder on its first open).#[derive(Default)]pub(crate) struct OtherOpens {    turns: Mutex<std::collections::BTreeMap<String, Arc<Mutex<()>>>>,    /// Bumped, under the set's lock, by every act that lets a held file go    /// for good — a detach, a leave, a deleted copy: an open in flight across    /// one does not put the handle it opened back into the set.    let_go: std::sync::atomic::AtomicU64,    /// Run inside every open, after the turn is taken — where a test holds    /// an open in flight.    #[cfg(test)]    pub(crate) during_open: Mutex<Option<Arc<dyn Fn(&str) + Send + Sync>>>,}impl OtherOpens {    fn turn(&self, database: &str) -> Arc<Mutex<()>> {        let mut turns = self.turns.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        Arc::clone(turns.entry(database.to_string()).or_default())    }    fn let_go_count(&self) -> u64 {        self.let_go.load(std::sync::atomic::Ordering::SeqCst)    }    /// Called with the set's lock held, before the set lets the file go.    fn letting_go(&self) {        self.let_go.fetch_add(1, std::sync::atomic::Ordering::SeqCst);    }}/// The open handles on a held database OTHER than the device's own, opened on/// first use and kept in `others`.////// A free function because two callers reach it: a method naming a database/// ([`ClientController::open_database`]) and the sync loop's pass, which runs/// on its own thread and holds no controller.fn open_other(    layout: &Layout,    clock: &dyn Clock,    random: &dyn Random,    judge: cotton_client::ReplicaJudge,    receipt_signer: cotton_store::signed::SignerSlot,    others: &Mutex<OpenFiles<OpenFile>>,    opens: &OtherOpens,    feeds: &Mutex<FeedIndex>,    events: Arc<EventBus>,    database: &str,) -> Result<OpenFile, String> {    loop {        if let Some(open) = others.lock().map_err(|_| locked())?.get(database) {            return Ok(open);        }        // THE DATABASE'S OWN TURN is held across the open, so two questions        // naming the same closed database open it once — two writers on one        // file is the thing the writer mutex exists to prevent. The set's        // lock is not: it is taken for an instant to look and to put in.        let turn = opens.turn(database);        let _turn = turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        if let Some(open) = others.lock().map_err(|_| locked())?.get(database) {            return Ok(open);        }        let let_go = opens.let_go_count();        #[cfg(test)]        if let Some(hook) = opens.during_open.lock().ok().and_then(|slot| slot.clone()) {            hook(database);        }        let open = open_other_file(layout, clock, random, judge.clone(), receipt_signer.clone(), database)?;        let mut set = others.lock().map_err(|_| locked())?;        // LET GO WHILE IT OPENED — left, deleted or detached: the handle is        // dropped, and the next look finds the database no longer held.        if opens.let_go_count() != let_go {            continue;        }        let closed = set.insert(database, open.clone(), OpenFile::idle);        drop(set);        close_handles(layout, feeds, closed);        start_opened_index(database, layout.replica(database), events);        return Ok(open);    }}/// A database that first arrives after attach missed `start_moves`: schedule/// its device-local computed index when its first handle opens.  This is not a/// record write, so a Reader may and must do it for its own copy.fn start_opened_index(database: &str, path: std::path::PathBuf, events: Arc<EventBus>) {    rebuild_index_beside(database, path, events);}/// Bring `database`'s computed index current on a thread of its own — one at/// a time per database — and say which tables it moved. A device's folds/// leave a stale index to this (`cotton_store::Driver::index_beside`), so a/// pass that folded rows calls it; when the index is current it opens the/// file, reads one row and is done.fn rebuild_index_beside(database: &str, path: std::path::PathBuf, events: Arc<EventBus>) {    static RUNNING: Mutex<std::collections::BTreeSet<String>> = Mutex::new(std::collections::BTreeSet::new());    if !RUNNING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(database.to_string()) {        return;    }    let database = database.to_string();    // The rebuild opens its own WAL connection. Retaining the cached writer    // here would make an otherwise idle database depend on thread scheduling    // before it could close (you_tests and client_holds_several_databases).    let spawned = std::thread::Builder::new()        .name("cotton-late-index".to_string())        .spawn({            let database = database.clone();            move || {                match cotton_tools::derive::ensure_file_current(&path, &database, |_| {}) {                    Ok(Some(moved)) => events.emit(EventKind::Data, json!({ "workspaceId": database, "tables": moved, "origin": MOVES_DONE_ORIGIN })),                    Ok(None) => {},                    Err(error) => tracing::warn!(workspace_id = %database, %error, "computed index not rebuilt"),                }                RUNNING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&database);            }        });    if spawned.is_err() {        RUNNING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&database);    }}/// One open of a held database other than the device's own, under its turn.fn open_other_file(    layout: &Layout,    clock: &dyn Clock,    random: &dyn Random,    judge: cotton_client::ReplicaJudge,    receipt_signer: cotton_store::signed::SignerSlot,    database: &str,) -> Result<OpenFile, String> {    if !held_ids(layout)?.iter().any(|held| held == database) {        return Err(not_held(database));    }    // A held database other than the device's own is served wherever the    // device's own is (it borrows its connection): a served one's copy    // another build wrote is refused, never moved (29 Oct 2026). One held    // alone moves its first step here, the tables it has left after the    // open, on the move thread (passivemove rule 1).    let heal = if mine_is_served(layout) {        refuse_another_builds_copy(layout, database)?;        None    } else {        let heal = cotton_client::dev_heal::heal_stale_replica_leaving_tables(layout, database, cotton_core::flavor::current());        if let Some(refusal) = cotton_client::dev_heal::Heal::stopped(&heal) {            return Err(refusal.to_string());        }        heal    };    let replica = open_replica_with(OpenReplicaInput {        layout,        workspace_id: database,        clock,        random,        judge: Some(judge),        // As in `attach`: nothing downloads inside this call. A held        // database whose file has not arrived yet says so.        bootstrap: &mut |_path| Err(NOT_ARRIVED.to_string()),        on_migration: None,        on_bootstrapped: None,        receipt_signer,    })    .map_err(|error| match error {        // Only a file that is not there has not arrived; a file that is        // there and refused is kept and named (architect, 12 Oct 2026).        ReplicaError::Bootstrap(_) => NOT_ARRIVED.to_string(),        other => cotton_client::dev_heal::Heal::explain(heal, other.to_string()),    })?;    super::diagnostics::opened(database, &replica.opened);    let readers = replica        .open_read_pool()        .map_err(|error| format!("this device's read connection did not open: {error}"))?;    Ok(OpenFile {        workspace_id: database.to_string(),        replica: Arc::new(Mutex::new(replica)),        readers: Arc::new(readers),    })}/// Close the handles a set took out, carrying the feeds' index across each/// close: closing checkpoints the file's log, which moves its stamp with no/// row changed (`feed_index`).fn close_handles(layout: &Layout, feeds: &Mutex<FeedIndex>, closed: Vec<(String, OpenFile)>) {    for (database, open) in closed {        let path = layout.replica(&database);        let before = feed_index::stamp(&path);        drop(open);        let after = feed_index::stamp(&path);        feeds            .lock()            .unwrap_or_else(|error| error.into_inner())            .carry(&database, before.as_ref(), after);    }}/// A serving business uses the selected-file slot without becoming Personal.fn primary_database(db: &cotton_store::Driver, genesis: cotton_core::genesis::Genesis) -> Result<(bool, String), String> {    if genesis == cotton_core::genesis::Genesis::Personal {        return Ok((true, PERSONAL_NAME.to_string()));    }    let row = db.get("SELECT kind, name FROM cotton_workspaces LIMIT 1", &[]).map_err(|error| error.to_string())?;    let personal = row.as_ref().is_some_and(|row| row.text("kind") == Some("personal"));    let name = if personal { PERSONAL_NAME.to_string() } else {        row.as_ref().and_then(|row| row.text("name")).unwrap_or_default().to_string()    };    Ok((personal, name))}/// The kinds that live in the personal database ALONE — the owner's list:/// mail, one reader's own marks on a chat (the chats themselves are read, and/// pinned, muted, archived and cleared, in the database named: one filed in a/// shared database is read and marked there), calls, the/// contacts import, moods, and (for now) code sessions. Named as `places_classes` names them, and held to/// that table by `every_personal_kind_is_a_class_the_table_names`.////// NOT the whole `PersonalOnly` class: that table also says Alarms, which the/// phone keeps as its own. Albums, news and the journal left the class/// (owner, 11 Oct 2026): each database keeps its own, and a call naming a/// project database runs there.pub const PERSONAL_KINDS: &[&str] = &[    "Mail",    "A reader's own mark on a chat (unread, kept, deleted)",    "Calls",    "The contacts import",    "Moods",    "Code sessions",];/// Does this tool's data live in the personal database whatever database the/// call names?pub fn lives_in_personal(tool: &str) -> bool {    matches!(        cotton_tools::mcp::places_classes::class_of(tool),        Some(cotton_tools::mcp::places_classes::PlacesClass::PersonalOnly { what, .. })            if PERSONAL_KINDS.contains(what)    )}/// The personal database's name: one per person, made at first run.pub const PERSONAL_NAME: &str = "Personal";/// One database this device holds, as `read.databases` lists it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct HeldDatabase {    pub id: String,    pub name: String,    /// The device's own database — nobody else can enter it.    pub personal: bool,    /// Made on this device and not yet taken by the server: held, readable and    /// writable here, in no exchange until the next pass hands its id over.    pub pending: bool,    /// JOINED AT ANOTHER PERSON'S MAC: it syncs at its own origin, and this    /// device holds no name for the Mac that serves it — so its page says    /// "their Mac not reachable" and never a name (`PlaceEntry::origin`).    pub theirs: bool,}/// The copy of a database this device was REMOVED from, as its Bin lists it/// ([`ClientController::removed_copies`]): typed fields only — the Bin's/// definition says the words.#[derive(Debug, Clone, PartialEq, Eq)]pub struct RemovedCopy {    pub database_id: String,    /// The name the invite gave it.    pub name: String,    /// Who removed this device, when known.    pub removed_by: Option<String>,    pub removed_at: String,    /// When it is purged with its media    /// ([`cotton_client::connection::joined::REMOVED_COPY_DAYS`] on).    pub purge_at: Option<String>,}/// **The named state of a device that holds its own database and no server.**////// What a phone is in between *Start* and the day a Mac joins/// (`cotton_client::start::start_local`). The sync loop is not running, and/// that is deliberate: there is no address, so every pass would be a refusal/// and the ladder would climb against nobody on a battery. Swift draws it as/// **"No Mac yet"**.////// A WORD rather than an absence, because the absence already had a meaning:/// `connected: false` is "this device has joined nothing and there is no file",/// which sends the app to Join. A phone that started its own database is/// connected to its own file and must not be sent anywhere.pub const NO_SERVER_YET: &str = "noServerYet";/// The named state of a device that has a server on the other end.////// Whether a pass is in flight right now is `cotton_client::sync::SyncState`'s/// to say on the event stream; this field answers the question before it — is/// there anything to sync WITH.pub const SYNCING_STATE: &str = "joined";/// The `phase` the sync loop's own status wears on the `client` stream.////// **The loop's status and the media drain's are two phase-less frames that/// both carry `state` and `pending`**, and their state words overlap (`idle`,/// `stopped`). A reader keyed on the fields alone cannot tell "a pass is/// waiting out its backoff" from "an upload finished", so the loop's frame is/// TAGGED here, the way the join, the download and the migration tag theirs/// (`phone/commands.rs`). The drain's frame stays as it was: nothing on the/// phone reads it by shape, and the ledger it counts rides `read.syncStatus`.pub const SYNC_PHASE: &str = "sync";/// The loop's status, as the `client` stream carries it: the serialised/// `SyncStatus` plus the tag above./// The Sync section's search-index line (mailsearch, v122): how far THIS/// file's mail index is filled — `{ "filled", "total" }` while it fills in/// the background, `null` once it is whole (or on a file that cannot say).fn search_index_fill(driver: &cotton_store::Driver) -> Value {    match cotton_store::fts_fill::filling(driver, crate::phone::mail_index::INDEX) {        Ok(Some(progress)) => json!({ "filled": progress.filled, "total": progress.total }),        _ => Value::Null,    }}/// The `origin` of the `data` event a finished background move says — the/// computed index rebuilt after the open, mail's wide search index filled:/// the tables it names are in step again, and a read that answered/// `could_not_read` `moving` over them is read again on it, never on a timer/// or a pull (passivemove rule 3). The per-table shape move joins it later.pub const MOVES_DONE_ORIGIN: &str = "moved";/// How a capture's bytes go UP: the port the drain puts through and who/// hears its counts after every tick.#[derive(Clone)]pub struct MediaUpload {    pub deps: Arc<dyn cotton_client::media::MediaDrainDeps>,    pub on_status: Option<cotton_client::media::drain::DrainStatusListener>,    /// Run after each tick's uploads: the release of Photos copies the object    /// now holds (`ClientController::release_photos_copies`).    pub after_uploads: Option<cotton_client::media::drain::AfterUploads>,}/// Bring `replica`'s computed index current, and when it rebuilt, say so on/// `events`: the `data` event, origin [`MOVES_DONE_ORIGIN`], naming every/// table the rebuild moved. True when it rebuilt.pub(crate) fn bring_moves_done(workspace_id: &str, replica: &Arc<Mutex<Replica>>, events: &EventBus) -> Result<bool, String> {    bring_moves_done_with_progress(workspace_id, replica, events, |_| {})}fn bring_moves_done_with_progress(    workspace_id: &str,    replica: &Arc<Mutex<Replica>>,    events: &EventBus,    report: impl Fn(cotton_tools::derive::IndexProgress),) -> Result<bool, String> {    let path = replica.lock().map_err(|_| "the replica's lock is poisoned".to_string())?.path.clone();    let Some(moved) = cotton_tools::derive::ensure_file_current(&path, workspace_id, report).map_err(|error| error.to_string())? else {        return Ok(false);    };    events.emit(EventKind::Data, json!({ "workspaceId": workspace_id, "tables": moved, "origin": MOVES_DONE_ORIGIN }));    Ok(true)}/// Run every step `replica`'s schema move has left, one table per/// transaction, each taking the copy's lock for its own table only — a read/// of any other table goes on meanwhile. A step that fails stops the move/// where it is: the copy stays mid-move, written down as not moved, and its/// next open tries the steps left again.pub(crate) fn bring_move_on(layout: &cotton_client::layout::Layout, workspace_id: &str, replica: &Arc<Mutex<Replica>>, events: &EventBus) {    if cotton_client::moves::left(workspace_id).is_none() {        return;    }    // A stop is written down and logged by the steps; the copy stays served.    let _stopped = run_move_steps(layout, workspace_id, events, &mut || replica.lock().ok().map(|replica| replica.move_step()));}/// Whether `workspace_id`'s stopped move is said for the first time in this/// launch: a copy held alone opens at every launch and tries its move again/// at every attach, and a stop that stands is one log line a launch, not one/// an attach (coordinator, 3 Nov 2026).fn first_stop_this_launch(workspace_id: &str) -> bool {    static SAID: Mutex<std::collections::BTreeSet<String>> = Mutex::new(std::collections::BTreeSet::new());    SAID.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(workspace_id.to_string())}/// Take `workspace_id`'s schema move through every step it has left, one/// table per `step` (`None`: the copy can no longer be taken, and the move/// waits for its next open), and say each as it is done: the `data` event,/// origin [`MOVES_DONE_ORIGIN`], naming the tables it moved, and at the last/// step every table the move moved, with the stamp now this build's/// (passivemove rule 1). `Err` is the reason of a step that failed, written/// down as not moved first and logged once a launch; the copy stays/// mid-move, served at its stored schema, and its next open tries again.fn run_move_steps(    layout: &cotton_client::layout::Layout,    workspace_id: &str,    events: &EventBus,    step: &mut dyn FnMut() -> Option<Result<Option<cotton_store::shape_move::Stepped>, cotton_client::replica::ReplicaError>>,) -> Result<(), String> {    let started = std::time::Instant::now();    let mut moved: Vec<String> = Vec::new();    loop {        let Some(stepped) = step() else { return Ok(()) };        match stepped {            Ok(Some(stepped)) => {                moved.extend(stepped.tables.iter().cloned());                let tables = if stepped.finished { moved.clone() } else { stepped.tables.clone() };                events.emit(EventKind::Data, json!({ "workspaceId": workspace_id, "tables": tables, "origin": MOVES_DONE_ORIGIN }));                if stepped.finished {                    // Moved: an earlier reason it could not be is not true now,                    // and the writes it parked for a newer shape fold.                    cotton_client::bootstrap::not_moved::clear(layout, workspace_id);                    tracing::info!(database = %workspace_id, steps = stepped.total, ms = started.elapsed().as_millis() as u64, "schema move finished");                    return Ok(());                }            }            Ok(None) => return Ok(()),            Err(error) => {                let stamped = cotton_client::moves::left(workspace_id).map_or(0, |left| left.from);                cotton_client::bootstrap::not_moved::mark(layout, workspace_id, stamped, &error.to_string());                if first_stop_this_launch(workspace_id) {                    tracing::warn!(database = %workspace_id, %error, "schema move stopped; the copy is served at its stored schema and its next open tries again");                }                return Err(error.to_string());            }        }    }}fn sync_status_event(status: &cotton_client::sync::SyncStatus) -> Value {    let mut payload = serde_json::to_value(status).unwrap_or(Value::Null);    if let Value::Object(fields) = &mut payload {        fields.insert("phase".to_string(), Value::from(SYNC_PHASE));    }    payload}/// Whether a write's `data` payload names a table or a row that moved. A write that minted nothing (a merge or a/// filing with nothing to do) says nothing: every phone screen reads again on a `data` event, and one that reads/// through a write looped on its own empty event (Words, the launch walk of 22 Nov 2026: sixty lists a second). The/// `client` event still carries the write's answer.pub(crate) fn moved_something(payload: &Value) -> bool {    let named = |key: &str| payload.get(key).and_then(Value::as_array).is_some_and(|moved| !moved.is_empty());    // `rows` is null past `authoring::MOST_ROWS_NAMED`, when the tables alone are named.    named("tables") || named("rows")}/// The sentence a method answers with while this device holds no database/// yet — a phone before its first open has made or joined one, a Mac nobody/// has connected. It names the machine the core runs on through the/// `machines` set's `host.title.*` lines and says that machine's own next/// step (`boot.not_connected.*`): a phone build (no `host` feature) never/// says "This Mac" or the menu bar. Rigby build 3 showed the Mac's sentence/// in a phone's Debug list (architect's row C2, 22 Oct 2026).pub fn not_connected_sentence() -> String {    not_connected_on(false)}/// [`not_connected_sentence`] as the Mac (`mac`) or the phone says it.fn not_connected_on(mac: bool) -> String {    use cotton_core::rules::shell_lines::resolve;    if mac {        let host = resolve("machines", "host.title.mac", &[], &[]).unwrap_or_default();        resolve("boot", "not_connected.mac", &[], &[("host", &host)]).unwrap_or_default()    } else {        let host = resolve("machines", "host.title.phone", &[], &[]).unwrap_or_default();        resolve("boot", "not_connected.phone", &[], &[("host", &host)]).unwrap_or_default()    }}/// What [`ClientController::attach`] answers for a copy of a served database/// another build wrote: it is never opened or moved here, and/// `personal.connect` makes it again from the object.pub const ANOTHER_BUILDS_COPY: &str =    "This phone's copy was written by an earlier version of the app; it is made again from your database when this phone connects.";/// Refuse `database`'s copy when another build stamped it and the database/// is served: it is made again from the object, never opened or moved here./// The numbers go to the log; the refusal a page can reach names none/// (passivemove rule 4).fn refuse_another_builds_copy(layout: &Layout, database: &str) -> Result<(), String> {    match cotton_client::unsent::stamped_by_another_build(&layout.replica(database)) {        Some(stamped) => {            eprintln!("cotton-client: {database}: the copy is stamped schema {stamped}, this build reads {}; not opened", cotton_store::migrate::SCHEMA_VERSION);            Err(ANOTHER_BUILDS_COPY.to_string())        }        None => Ok(()),    }}/// Whether the device's own database has a server: every other database it/// holds is then served too, at the same address.fn mine_is_served(layout: &Layout) -> bool {    scoped_record(layout).ok().flatten().is_some_and(|record| record.mine.mode.has_server())}/// What is still owed before a decision or an import can reach a server from/// here.////// `cotton-client` declares the transport seam (`ServerFetch`) and there is no/// HTTP implementation of it in the tree yet — the join flow that would build/// one lands with the connection half. Saying so is the point: a `sync.now`/// that quietly answered "0 pushed" would read as a healthy sync.pub const NO_TRANSPORT: &str =    "This build can read and import into this Mac's own copy, but cannot talk to the server yet: \     the client's HTTP transport is not wired up. Imports are kept locally and go up when it is.";/// How a caller gets a transport, when there is one to get.pub type TransportSource = Arc<    dyn Fn() -> Result<Box<dyn cotton_client::transport::SyncingTransport>, String> + Send + Sync,>;/// The ONE signed request seam, held for whatever needs to ask the server a/// question the sync loop's two calls cannot ask.////// It is [`cotton_client::transport::ServerFetch`] and nothing else: the device/// signature and the base address both live BELOW it, in the connection seam/// that owns "which server this device talks to". A/// caller holding this holds no URL and no key, which is the whole point —/// there is one signing path in this tree, not one per question.pub type FetchSource = Arc<dyn cotton_client::transport::ServerFetch>;/// Where the migration ladder reports while it runs INSIDE an attach.////// The ladder is not the bootstrap's alone. A launch that already has a file/// runs it from [`ClientController::attach`] — a schema bump means every/// returning phone does, on a file that can be hundreds of megabytes — and/// with nowhere to report, that whole run was a screen holding at the boot/// gate saying nothing. This is the seam the phone fills so the SAME/// `migrate.status` read and the SAME `MigrationEvent`s the bootstrap already/// emits carry an ordinary launch too.////// `Fn` + `Send` + `Sync` rather than `FnMut`: it is called from whichever/// thread asked the question first, and the state behind it is the phone's own/// progress mutex.pub type MigrationReporter = Arc<dyn Fn(MigrationEvent) + Send + Sync>;struct Attached {    connection: StoredConnection,    workspace_id: String,    /// THE WRITER: the one connection that writes — the outbox, the sync fold,    /// the migrations, the ledger stamps. One mutex, because there is one    /// writer.    replica: Arc<Mutex<Replica>>,    /// THE READERS: read-only connections to the same file, opened after the    /// replica's ladder ran and dropped with it. Every screen's read runs on    /// one ([`ClientController::with_file`]), so a read never waits on the    /// writer's mutex — a sync fold holding it for a thousand rows is not a    /// list the person is watching spin — nor on another read: a board's    /// tiles each take a free connection ([`ReadPool`]).    readers: Arc<ReadPool>,}/// One held database's open handles: its writer and its readers.////// What [`ClientController::open_database`] answers for the device's own/// database and for every other one alike, so a caller that names a database/// never learns which of the two it was.#[derive(Clone)]pub struct OpenFile {    pub workspace_id: String,    pub replica: Arc<Mutex<Replica>>,    pub readers: Arc<ReadPool>,}impl OpenFile {    /// Is the set the only holder — no read, write or fold still running?    fn idle(&self) -> bool {        Arc::strong_count(&self.replica) == 1 && Arc::strong_count(&self.readers) == 1    }}/// What the ingest sources need to know about the machine they read.////// A HOST's, and absent on a phone: `ClientController::new` takes an `Option`/// rather than two placeholders a phone never fills, and the ingest sources are/// registered only when it is there. The struct itself compiles on every build/// because `OpenMode::Host` names it on every build.pub struct MachineSources {    /// The ingesting machine's label — rides every imported row as    /// `meta.source.device`.    pub device: String,    /// The person's home folder, under which every source lives.    pub home: std::path::PathBuf,}/// What runs after a pull, handed the tables that moved.////// A named type rather than the closure spelled out at each of its two sites:/// the field, the setter and the call would otherwise repeat it, and one of/// them drifting is a hook that silently never installs.pub type AfterPull = Arc<dyn Fn(&[String]) + Send + Sync>;/// What makes this device's copy of the personal object again, given why/// its passes are stuck (`personal.connect`).pub type SyncHeal = Arc<dyn Fn(&str) + Send + Sync>;/// What makes this device's copy of the personal object again after the server was put back to an earlier time/// (RESTORE 2), given what the passes learned of it (`personal.connect`).pub type RestoreHeal = Arc<dyn Fn(cotton_client::transport::object::ServerRestored) + Send + Sync>;/// The heals a failed pass may start, and whether each is under way.#[derive(Clone)]struct Heals {    stuck: Arc<Mutex<Option<SyncHeal>>>,    /// Whether this launch has made its copy again for a stuck pass.    healed: Arc<std::sync::atomic::AtomicBool>,    restore: Arc<Mutex<Option<RestoreHeal>>>,    /// Whether a copy is being made again after a restore now: one at a time, and another restore seen after it ends    /// makes the copy again too.    restoring: Arc<std::sync::atomic::AtomicBool>,}/// A COPY STUCK ON ONE PAGE IS MADE AGAIN (owner's phone, 2 Nov 2026: one/// page asked every 30 s for a day, while a fresh copy on the same build caught/// up in ten minutes — the fault was the copy's own state). When the passes/// to the personal object say the copy is stuck (`SyncProgress::stuck`: three/// running failed on one page for one reason while the object answered) and/// a heal is installed, it runs on its own thread — never the loop's, which/// it stops — at most once a launch.////// A SERVER PUT BACK TO AN EARLIER TIME (RESTORE 2) comes first: a pass that met a new generation, or a post refused/// `generation_moved`, makes the copy again from the server (what it holds unsent kept aside and listed, never sent),/// on its own thread, one at a time, as often as a restore is seen.fn heal_if_stuck(progress: &Mutex<Option<Arc<cotton_client::transport::object::SyncProgress>>>, heals: &Heals) {    let progress = progress.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone();    if let Some(restored) = progress.as_ref().and_then(|progress| progress.restore_seen()) {        let Some(heal) = heals.restore.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone() else { return };        if heals.restoring.swap(true, std::sync::atomic::Ordering::SeqCst) {            return;        }        let restoring = Arc::clone(&heals.restoring);        let spawned = std::thread::Builder::new().name("cotton-copy-restore".into()).spawn(move || {            heal(restored);            restoring.store(false, std::sync::atomic::Ordering::SeqCst);        });        if let Err(error) = spawned {            heals.restoring.store(false, std::sync::atomic::Ordering::SeqCst);            eprintln!("[object] the server was put back and this phone's copy could not be made again: no thread ({error})");        }        return;    }    let Some(why) = progress.as_ref().and_then(|progress| progress.stuck()) else { return };    let Some(heal) = heals.stuck.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone() else { return };    if heals.healed.swap(true, std::sync::atomic::Ordering::SeqCst) {        return;    }    if let Err(error) = std::thread::Builder::new().name("cotton-copy-heal".into()).spawn(move || heal(&why)) {        eprintln!("[object] this phone's copy is stuck and could not be made again: no thread ({error})");    }}pub struct ClientController {    pub(crate) voice_context: Mutex<Option<Value>>,    layout: Layout,    events: Arc<EventBus>,    /// THE DEVICE'S OWN IANA ZONE, handed down at open (`OpenConfig.timeZone`).    ///    /// The reader's half of the rule the writer already keeps: a mood, a    /// journal day and every "today" the app draws are the DEVICE's calendar    /// day, so the phone hands its zone down once at open and every banding    /// read takes it from here. `None` is a NAMED state, never UTC — a read    /// that needs a day and has no zone refuses, exactly as `record_mood`'s    /// `writer_zone` refuses, because a strip silently drawn in UTC is a    /// fortnight of the wrong days.    time_zone: Option<String>,    clock: Arc<dyn Clock>,    /// TEST ONLY: the moment `clock` answers once a test pins it, so a golden    /// holding "3 days ago" is read against one fixed day, not the wall clock.    #[cfg(test)]    pinned_clock: Arc<Mutex<Option<chrono::DateTime<chrono::Utc>>>>,    random: Arc<dyn Random>,    /// JUDGE TIME (slice 1): the process's one judge clock, which every answer    /// from the serving Mac is a reading for and every replica this    /// controller opens is written by. A phone's own; on a Mac, the server's    /// (`judged_by`), which the relay line also feeds.    judge: Arc<cotton_client::judge::JudgeClock>,    /// THE VAULT MASTER KEY, while this device is unlocked (spec §6.2).    ///    /// It lives on the controller rather than on the handle because it belongs    /// to the FILE this process is holding, which is what the controller owns —    /// and because a `read.*` entry is handed a controller and not a handle,    /// and the Passwords list has to draw "unlocked until …". A session on the    /// handle would be a status the read could not ask about.    ///    /// An `Arc` so `read.secrets` and `vault.reveal` hold the SAME session: two    /// would be two answers to whether this phone is unlocked.    vault: Arc<crate::phone::vault::VaultSession>,    /// THIS MACHINE'S OWN VAULT PRIVATE KEY — the Mac's, and only the Mac's.    ///    /// The phone's equivalent is guarded by presence and crosses per call as    /// `vault.unlock`'s parameter, so nothing holds it between two reveals.    /// The Mac's is held for the process's life on purpose (spec §7.1): the    /// placement applier writes a credential into a build nobody is watching,    /// and an import seals a few hundred logins with no person present. The    /// login session is the guard, and the reveal screen's Touch ID prompt is a    /// courtesy the screen performs rather than an access control the key    /// carries.    ///    /// `None` on a phone build, always, and on a Mac with no Keychain item.    vault_key: Mutex<Option<[u8; 32]>>,    tool_signer: Mutex<Option<cotton_tools::mcp::dispatch::ToolSigner>>,    /// THE DEVICE KEY THAT SIGNS THIS DEVICE'S RECEIPTS (keys slice KS1): one    /// slot every replica this controller opens reads from, filled at open.    receipt_signer: cotton_store::signed::SignerSlot,    /// THIS DEVICE'S VAULT PUBLIC HALF, AND THE DATABASES THAT HOLD IT — the    /// latch behind `phone::vault::publish_owed`, ONE ENTRY PER DATABASE.    ///    /// The public half is not a secret; it is kept so a database admitted    /// after the launch's publish gets the key on its first pass without the    /// screen asking again (a phone's private half never leaves the Keychain,    /// so Rust cannot derive it there). The set names the databases whose file    /// already holds this key.    ///    /// Process-local and deliberately not a column: this device's public half    /// changes only when its Keychain item does, which needs a relaunch, so a    /// launch that has published into a database has published there for its    /// whole life. Until a database is in the set, every sync pass asks again    /// — which is the half that was missing on one Mac, 2026-09-19, where the    /// one publish this Mac attempted was refused at open and nothing ever    /// asked a second time. A different public half empties the set.    vault_published: Mutex<(Option<String>, std::collections::BTreeSet<String>)>,    /// What the loop runs after each of its own passes that ended idle. The    /// handle installs it, WEAK for [`Self::after_pull`]'s reason; it is how a    /// database that owes this device's vault key gets it whatever moved.    after_pass: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,    transport: Mutex<Option<TransportSource>>,    /// THE ID THE SERVER ADMITS THIS DEVICE BY — the public half of the Ed25519    /// key, 43 base64url characters.    ///    /// NOT `replica.device_id`, which is an AUTHOR id (`device:<ulid>`) and    /// names this device to a FILE. `replica::resolve_device_id` says the two    /// must never be conflated, and the vault is where conflating them cost    /// something: `vault.publishKey` filed this phone's key row under the    /// author id while the approve path files it under this one, so the row the    /// phone wrote named a device the server's registry had never heard of —    /// which `rotate::pending_rotation` reads as a REVOKED device. Every boot    /// then deleted the row and rotated the master key, and the phone read    /// "Waiting for your Mac to share the key" for ever.    ///    /// ONE SLOT, SHARED (`cotton_client::identity::DeviceKey`): the budget    /// pass holds a clone and reads it when it runs, so the id its holds name    /// this device by is this one — never the replica's author id, which no    /// reader of the media ledger can see.    self_device_id: cotton_client::identity::DeviceKey,    /// The signed-request seam, for the questions that are not the sync loop's.    ///    /// A SECOND slot rather than a wider `TransportSource`, because the two are    /// different things: `transport` hands out a fresh `HttpTransport` per sync    /// pass (the store's `SyncTransport` is `&mut` and remembers its last    /// refusal), while this is the ONE long-lived fetch every such transport is    /// built over. Absent is a state, never a failure to report later: see    /// [`NO_SIGNED_REQUESTS`].    fetch: Mutex<Option<FetchSource>>,    /// How bytes come DOWN, when something has given this device a way.    ///    /// A separate slot from `transport` because it is a separate question and    /// the sync transport structurally cannot answer it — see    /// [`crate::phone::media::MediaFetch`], which carries the whole reason.    media_fetch: Mutex<Option<Arc<dyn crate::phone::media::MediaFetch>>>,    /// How a capture's bytes go UP, from `personal.connect` on: the object's    /// media door and who hears the drain's counts. `None` on a device with    /// no object (Rigby, a test), which runs no drain.    media_upload: Mutex<Option<MediaUpload>>,    /// The drain carrying the `_media` queue to the object, while a copy is    /// attached and `media_upload` is set (`cotton_client::media::drain`).    media_drain: Mutex<Option<cotton_client::media::MediaDrain>>,    /// The uploads in the air on this device and how far each has gone    /// (MEDIA DRAIN 1): one for the client's life, so a drain started again    /// over a new way up reports into the same place `media.uploads` reads.    upload_watch: Arc<cotton_client::media::UploadWatch>,    /// The person's own object, asked directly (`phone::personal_object::ObjectDoor`).    object_door: Mutex<Option<Arc<crate::phone::personal_object::ObjectDoor>>>,    /// The one Cotton Calling call this device holds (`phone::calls`): memory only.    call: Mutex<cotton_core::calling::Call>,    /// The calls that ended here lately (room, when, why), kept for a VoIP push's lifetime (`phone::calls`): a late    /// push for one is reported and ended at once, never rung (CALLS FIX 2).    ended_calls: Mutex<Vec<(String, i64, cotton_core::calling::wire::EndReason)>>,    /// What Cotton messages remember between calls: this phone's number and the keys last seen (`phone::cotton_chat`). Never a private key.    chat: Mutex<crate::phone::cotton_chat::ChatMemory>,    /// The notes this phone takes on a call (`phone::call_notes`).    notes: Mutex<crate::phone::call_notes::Notes>,    /// Each database's data key for its sealed tables, as the shell handed    /// it over from the platform's key store (`phone::seal`). Never written    /// anywhere by the core.    data_keys: Arc<cotton_client::seal::HeldDataKeys>,    /// The database a back-up is adopting this phone's own signed-out    /// database into, and that local database's id: its data key (made with    /// no question, `seal.makeKey`) becomes the new object's when the object    /// has none (`phone::seal::ensure`). Ids only, never a key.    carried_key: Mutex<Option<(String, String)>>,    /// An unlock card's Allow held while this device's vault founds, with    /// the device key it was handed (wiped when dropped), or why completing    /// it failed (`phone::unlock`). Memory only, within the request's life.    unlock_held: Mutex<Option<crate::phone::unlock::HeldAllow>>,    /// The adopt of this launch, bringing a used local database into the    /// person's object (`phone::adopt`); `None` before one starts.    adopting: Mutex<Option<Arc<crate::phone::adopt::Adopting>>>,    /// The pictures sweep a phone on the personal object runs after every    /// pass (`phone::media_sweep`); `None` everywhere else.    pictures_sweep: Mutex<Option<Arc<crate::phone::media_sweep::PicturesSweep>>>,    /// What Days last heard of its Google calendars and Cotton people    /// (`phone::days_people::Heard`): the object's Google status and the    /// connected numbers, kept in memory only, so a sheet draws who goes    /// which way without asking the network.    pub(crate) days_heard: Mutex<crate::phone::days_people::Heard>,    /// The media keys the far end answered 404 for, each waiting before it is    /// asked again (`cotton_client::media::absent`, `phone::media::land`).    absent_media: cotton_client::media::absent::AbsentKeys,    /// Where the passes to the owner's personal object stand, once    /// `personal.connect` has made that object the far end: what this    /// device's own record says of its sync (`device.facts`) and whether Home    /// draws it.    sync_progress: Arc<Mutex<Option<Arc<cotton_client::transport::object::SyncProgress>>>>,    /// The object's definitions as the passes to the personal object last    /// held them (`personal.connect`): every served table's plural, placed in    /// the copy or not (`phone::unlock`'s labels).    served_definitions: Mutex<Option<Arc<cotton_client::transport::object::HeldDefinitions>>>,    /// What makes the copy of the personal object again when its passes are    /// stuck on one page (`SyncProgress::stuck`): installed by    /// `personal.connect`, run on its own thread after a failed pass, at most    /// once a launch ([`heal_if_stuck`]).    sync_heal: Arc<Mutex<Option<SyncHeal>>>,    /// Whether this launch has made its copy again for a stuck pass: a copy    /// that stalls again after it is left alone, and keeps saying why.    copy_healed: Arc<std::sync::atomic::AtomicBool>,    /// What makes the copy again after the server was put back (RESTORE 2), installed by `personal.connect`.    restore_heal: Arc<Mutex<Option<RestoreHeal>>>,    /// Whether that runs now.    copy_restoring: Arc<std::sync::atomic::AtomicBool>,    /// What this device's own storage is doing — a seam, never `std::fs` in a    /// read. See [`crate::phone::disk`].    disk: Mutex<Arc<dyn crate::phone::disk::Disk>>,    /// The persisted terminal refusal, when this build has one to read.    ///    /// RUST owns the note (`client/refusal.json`) because the transport has to    /// refuse before sending, on the first request of a cold launch and before    /// any screen exists. The boot gate reads it from here so that a device    /// refusal paints FIRST — ahead of signed-out — which is the gate's own    /// order and matters because a revoked phone has just been signed out by    /// the app's leave and the sentence has to outlive that.    refusals: Mutex<Option<Arc<cotton_client::transport::RefusalMemory>>>,    /// Where a ladder run inside [`Self::attach`] reports, when something has    /// given this device a screen to report to. `None` until one does.    on_migration: Mutex<Option<MigrationReporter>>,    /// What an open in flight is doing, while [`Self::attach`] runs — the step    /// the wait screen names instead of guessing (`migrate.status`'s    /// `opening`). `None` when no open is running.    opening: Mutex<Option<OpenStep>>,    /// A whole copy has ARRIVED and a bootstrap or re-hydrate thread is    /// checking, unpacking and claiming it — set by its first `place` event,    /// cleared when it attaches or ends. While set, `attach` answers at once    /// instead of opening the same file (see [`PLACING_A_COPY`]).    placing: std::sync::atomic::AtomicBool,    /// THE TURN TO OPEN the device's own database, held for the length of one    /// open by [`Self::attach`] — and never the `state` lock, which a detach    /// and every read of what is held take for an instant and must never    /// queue behind a ladder, a write-ahead log replay or a heal.    attaching: Mutex<()>,    /// THE SWAP OF THE DATABASE THIS PHONE STANDS ON (sign-out, a sign-in    /// over a copy that goes aside or comes back, a removal, a deleted    /// account forgotten): every open waits it out (`super::swap`).    swap: Arc<super::swap::SwapGate>,    /// Run inside every open, between taking the turn and installing the    /// handle — where a test holds an open in flight.    #[cfg(test)]    pub(crate) during_open: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,    /// Bumped by every [`Self::detach`]: an open that began before one does    /// not install a handle on the file that was let go.    detaches: std::sync::atomic::AtomicU64,    /// WHAT TO RUN AFTER A PULL MOVED SOMETHING. One installer and one caller.    ///    /// The placement applier is what wants it (`methods::vault`): a placement    /// this machine has to write arrives as an ordinary synced row, and a Mac    /// that only applied at start would sit on it until the next launch. It is    /// installed by the handle rather than here, because the hook has to reach    /// back through the controller and only the handle holds the `Arc` — WEAK    /// deliberately: the controller holds the hook, so a strong one would be a    /// cycle neither end ever frees.    after_pull: Mutex<Option<AfterPull>>,    after_tables: Mutex<Option<Arc<dyn Fn(&str, &[String]) + Send + Sync>>>,    /// When the last pass actually reached the server, ISO-8601 UTC.    ///    /// Held HERE rather than read off a `SyncLoop`, because on the phone there    /// is no running loop to ask: a cycle is a one-shot the scene phase, the    /// live channel or a pull-to-refresh drives. The sync banner needs "last    /// checked" whatever drove it, so the one thing that all of them go through    /// records it.    ///    /// An `Arc` rather than a bare field because the running loop's status    /// listener writes it too: once a schedule exists, "last checked" advances    /// on a pass nobody asked for, which is the whole reason a schedule is    /// worth having.    last_pull_at: Arc<Mutex<Option<String>>>,    /// The database the last pass that reached the server was for. Whether a copy knows its vault is asked of the    /// database attached now, never of the one before: signed out of one number and into another, a fresh copy    /// read the earlier number's pass as its own and founded a second vault (iPhone walk, 23 Nov 2026).    pulled_for: Arc<Mutex<Option<String>>>,    /// The database whose last pass ended with nothing still to pull (`SyncStatus::caught_up`): unlike `pulled_for`,    /// never set by a pass that reached the server only part way (SITES ROWS, 26 Nov 2026).    /// The database whose copy's last pass ended caught up, and the copy's generation (`detaches`) it was said of:    /// a word from a loop or pass of a copy since let go never counts (review of SITES ROWS 3, item 3).    caught_up_for: Arc<Mutex<Option<(String, u64)>>>,    /// The same, kept once said until the copy is let go: "caught up at least once since this copy opened".    caught_up_once_for: Arc<Mutex<Option<(String, u64)>>>,    /// The object's word when it stopped taking this phone's credential (a    /// 401 to a pass), until a connect is taken again: `shell.home` says it.    signed_out: Mutex<Option<String>>,    /// Why the last `personal.connect` did not take (`code`, the refusal's    /// own words), until a connect takes, an adopt starts, or the person    /// signs out: `shell.home` stands failed on it and says it.    connect_refused: Mutex<Option<(String, String)>>,    /// The database this phone was signed in to when a `personal.connect`    /// began over its copy, kept while that connect runs and after one that    /// did not take: the copy made again after an update, or an object out of    /// reach, leaves the phone signed in (owner's iPhone, Chat build 14, 21    /// Nov 2026). Gone when a connect takes or the person signs out.    kept_signed_in: Mutex<Option<String>>,    /// A `personal.connect` runs now.    connecting: std::sync::atomic::AtomicBool,    /// The last thing that went wrong between this phone and its object,    /// in words, and when (ISO 8601): a connect refused, a backup that    /// failed, the object signing this phone out. The Account card says it    /// until the person signs out or removes the copy.    last_trouble: Mutex<Option<(String, String)>>,    /// What the last top-up sent to the object (`phone::adopt::top_up`):    /// rows sent, rows refused, and when (ISO 8601); none before one ran    /// since the person signed in. The Account card says it.    topped_up: Mutex<Option<(u64, u64, String)>>,    /// A top-up is running: one at a time.    topping_up: std::sync::atomic::AtomicBool,    /// How long a pass may still run — closed by a background slice    /// ([`Self::begin_slice`]), open otherwise. ONE box for the loop's passes    /// and the joined databases' pass, because it is the process that is    /// about to be frozen, not one of them.    time_box: cotton_client::sync::TimeBox,    /// The runtime the scheduled loop is spawned into.    ///    /// Handed down rather than built here: there is exactly ONE runtime per    /// open handle (design M2), and a controller that made its own would be a    /// second thread pool nobody counted.    runtime: Mutex<Option<tokio::runtime::Handle>>,    /// Which databases this app shows and holds (`super::scope`): the    /// manifest's word, set once at open ([`Self::limit_to`]); unset is every.    scope: std::sync::OnceLock<super::scope::DatabaseScope>,    /// Whether this app syncs (the manifest's `sync`): set once at open by    /// [`Self::without_sync`]; unset is true, as in Cotton.    syncs: std::sync::OnceLock<bool>,    /// Which app identity opened this client (`cotton_core::flavor`): set    /// once at open by [`Self::declare_flavor`]; unset in a unit test.    flavor: std::sync::OnceLock<cotton_core::flavor::Flavor>,    /// Where each listed database's first fill stands: how far its download    /// is, or why the last one stopped. What [`Self::arriving`] says.    fills: Mutex<std::collections::BTreeMap<String, Fill>>,    /// Where each database's sync stands, in words (`cotton_client::sync::line`):    /// kept across passes because a catch-up's percent is measured against    /// what was owed when it began. Shared with the loop's report listener,    /// which is where most of them are heard.    home_lines: HomeLines,    /// What a copy that stopped says, until the next one moves or opens.    copy_note: Mutex<Option<String>>,    /// The PULL SCHEDULE, once there is a file and a transport to run it over.    ///    /// Without this the loop is a library nothing calls: `PULL_INTERVAL_MS`    /// never ticks, the backoff ladder never climbs, `Retry-After` is never    /// obeyed and the coalescing drain has no flights to coalesce — every one    /// of which is a rule this crate tests and, until now, nothing ran.    sync_loop: Mutex<Option<cotton_client::sync::task::SyncLoop>>,    /// The background move the open left (`cotton-index`), while it runs.    index_move: Mutex<Option<std::thread::JoinHandle<()>>>,    state: Mutex<Option<Attached>>,    /// The OTHER databases this device holds, open on demand.    ///    /// `state` is the device's own database, open while it is connected. Every    /// other held file opens here when something names it and closes when    /// nothing uses it ([`Self::open_database`]). No file is ever attached to    /// another's connection.    others: Arc<Mutex<OpenFiles<OpenFile>>>,    /// The turn each of those opens under, so the set's lock is never held    /// across one ([`OtherOpens`]).    pub(crate) other_opens: Arc<OtherOpens>,    /// What Today and "Asked of you" last answered in each other held file,    /// so a feed across every database opens no idle one (`feed_index`).    feeds: Arc<Mutex<FeedIndex>>,}impl std::fmt::Debug for ClientController {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("ClientController")            .field("data_dir", &self.layout.root())            .finish_non_exhaustive()    }}/// A background slice's hold on the time box ([`ClientController::begin_slice`]).////// Lifted when dropped, and only if the box is still this slice's: a later/// slice's limit is that slice's to lift, and a foreground open has lifted it/// already.#[must_use = "the slice ends, and its limit with it, when this is dropped"]pub struct Slice {    time_box: cotton_client::sync::TimeBox,    until: std::time::Instant,}impl Drop for Slice {    fn drop(&mut self) {        self.time_box.lift_if(self.until);    }}/// TEST ONLY: the wall clock until a test pins a moment, then that moment.#[cfg(test)]#[derive(Debug)]struct PinnableClock {    pinned: Arc<Mutex<Option<chrono::DateTime<chrono::Utc>>>>,}#[cfg(test)]impl Clock for PinnableClock {    fn now(&self) -> chrono::DateTime<chrono::Utc> {        self.pinned.lock().unwrap_or_else(|error| error.into_inner()).unwrap_or_else(|| SystemClock.now())    }}/// ERASES, once at start (DISCOVERY OFF 2, 27 Nov 2026): `chat-discover.json`, which builds with "Find people I know"/// left on the phone. It held the digest of every address-book number found not on Cotton, with when; a digest is/// reversed by trying every number, so it goes. Nothing else is touched, and a phone without it changes nothing.pub(crate) fn erase_old_finding(client_dir: &std::path::Path) {    let old = client_dir.join("chat-discover.json");    if old.exists() {        // not a copy: the old finding file, erased by decision.        if let Err(error) = std::fs::remove_file(&old) {            tracing::warn!("chat: the old finding file was not erased — {error}");        }    }}impl ClientController {    pub fn new(        layout: Layout,        events: Arc<EventBus>,        time_zone: Option<String>,        machine: Option<MachineSources>,    ) -> ClientController {        // The client build has no ingest sources to hand it to; the value is        // taken so the two builds share one signature.        let _ = machine;        // Before the judge clock is read: on iOS the boot session is kept        // in the data folder.        cotton_client::judge::keep_boot_session_in(layout.root());        let home_lines = HomeLines::kept_at(layout.home_lines_json());        erase_old_finding(&layout.client_dir());        #[cfg(test)]        let pinned_clock: Arc<Mutex<Option<chrono::DateTime<chrono::Utc>>>> = Arc::new(Mutex::new(None));        #[cfg(test)]        let clock: Arc<dyn Clock> = Arc::new(PinnableClock { pinned: Arc::clone(&pinned_clock) });        #[cfg(not(test))]        let clock: Arc<dyn Clock> = Arc::new(SystemClock);        ClientController {            voice_context: Mutex::new(None),            layout,            events,            time_zone: time_zone.filter(|zone| !zone.trim().is_empty()),            clock,            #[cfg(test)]            pinned_clock,            random: Arc::new(SystemRandom),            judge: Arc::new(cotton_client::judge::JudgeClock::system()),            vault: Arc::new(crate::phone::vault::VaultSession::default()),            vault_key: Mutex::new(None),            tool_signer: Mutex::new(None),            receipt_signer: cotton_store::signed::SignerSlot::default(),            vault_published: Mutex::new((None, std::collections::BTreeSet::new())),            after_pass: Mutex::new(None),            transport: Mutex::new(None),            self_device_id: cotton_client::identity::DeviceKey::default(),            fetch: Mutex::new(None),            media_fetch: Mutex::new(None),            media_upload: Mutex::new(None),            media_drain: Mutex::new(None),            upload_watch: Arc::new(cotton_client::media::UploadWatch::new()),            object_door: Mutex::new(None),            call: Mutex::new(cotton_core::calling::Call::idle()),            ended_calls: Mutex::new(Vec::new()),            chat: Mutex::new(crate::phone::cotton_chat::ChatMemory::default()),            notes: Mutex::new(crate::phone::call_notes::Notes::default()),            data_keys: cotton_client::seal::HeldDataKeys::new(),            carried_key: Mutex::new(None),            unlock_held: Mutex::new(None),            adopting: Mutex::new(None),            pictures_sweep: Mutex::new(None),            days_heard: Mutex::new(Default::default()),            absent_media: cotton_client::media::absent::AbsentKeys::default(),            sync_progress: Arc::new(Mutex::new(None)),            served_definitions: Mutex::new(None),            sync_heal: Arc::new(Mutex::new(None)),            copy_healed: Arc::new(std::sync::atomic::AtomicBool::new(false)),            restore_heal: Arc::new(Mutex::new(None)),            copy_restoring: Arc::new(std::sync::atomic::AtomicBool::new(false)),            disk: Mutex::new(Arc::new(crate::phone::disk::SystemDisk)),            refusals: Mutex::new(None),            on_migration: Mutex::new(None),            opening: Mutex::new(None),            placing: std::sync::atomic::AtomicBool::new(false),            attaching: Mutex::new(()),            swap: Arc::new(super::swap::SwapGate::default()),            #[cfg(test)]            during_open: Mutex::new(None),            detaches: std::sync::atomic::AtomicU64::new(0),            after_pull: Mutex::new(None),            after_tables: Mutex::new(None),            copy_note: Mutex::new(None),            last_pull_at: Arc::new(Mutex::new(None)),            pulled_for: Arc::new(Mutex::new(None)),            caught_up_for: Arc::new(Mutex::new(None)),            caught_up_once_for: Arc::new(Mutex::new(None)),            signed_out: Mutex::new(None),            connect_refused: Mutex::new(None),            kept_signed_in: Mutex::new(None),            connecting: std::sync::atomic::AtomicBool::new(false),            last_trouble: Mutex::new(None),            topped_up: Mutex::new(None),            topping_up: std::sync::atomic::AtomicBool::new(false),            time_box: cotton_client::sync::TimeBox::open(),            runtime: Mutex::new(None),            scope: std::sync::OnceLock::new(),            syncs: std::sync::OnceLock::new(),            flavor: std::sync::OnceLock::new(),            fills: Mutex::new(std::collections::BTreeMap::new()),            home_lines,            sync_loop: Mutex::new(None),            index_move: Mutex::new(None),            state: Mutex::new(None),            others: Arc::new(Mutex::new(OpenFiles::new(OPEN_HANDLES))),            other_opens: Arc::default(),            feeds: Arc::default(),        }    }    /// Give the controller the runtime its schedule runs on.    ///    /// Until something does, [`Self::attach`] builds no loop and every cycle is    /// the one-shot a caller asked for — which is what a test wants and what    /// the Mac, whose schedule is the server's, wants too.    pub fn set_runtime(&self, handle: Option<tokio::runtime::Handle>) {        *self.runtime.lock().expect("the runtime slot") = handle;    }    /// What an open in flight is doing, or `None` when none is running.    pub fn opening(&self) -> Option<OpenStep> {        *self            .opening            .lock()            .unwrap_or_else(|poisoned| poisoned.into_inner())    }    /// Stand the controller in the middle of an open, for a test of what    /// `migrate.status` answers then. The real mark is set and cleared by    /// [`Self::attach`] around the open.    #[cfg(test)]    pub(crate) fn set_opening_for_test(&self, step: Option<OpenStep>) {        *self            .opening            .lock()            .unwrap_or_else(|poisoned| poisoned.into_inner()) = step;    }    /// Give the controller somewhere to report a ladder run from.    ///    /// Installed once at open by the phone's handle, which owns the progress    /// the migration screen reads. Until something does, [`Self::attach`] runs    /// the ladder silently — which is what the Mac wants and what a test that    /// is not about the screen wants.    pub fn set_migration_reporter(&self, reporter: Option<MigrationReporter>) {        *self            .on_migration            .lock()            .expect("the migration reporter slot") = reporter;    }    /// Install the seams a test drives this with. Never called by the app.    /// Pin the clock every read and stamp on this device answers, so a test's    /// words ("3 days ago", "late") come out the same on any day it runs.    #[cfg(test)]    pub(crate) fn pin_clock(&self, at: chrono::DateTime<chrono::Utc>) {        *self.pinned_clock.lock().unwrap_or_else(|error| error.into_inner()) = Some(at);    }    #[cfg(test)]    pub fn with_seams(        mut self,        clock: Arc<dyn Clock>,        random: Arc<dyn Random>,    ) -> ClientController {        self.clock = clock;        self.random = random;        self    }    /// Judge by the process's one clock — on a Mac, the server's, which the    /// relay line feeds (slice 1).    /// The server's time as this copy last heard it, on its continuous clock; none when it has heard none this boot.    #[cfg_attr(test, allow(dead_code))]    pub(crate) fn judge_now(&self) -> Option<i64> {        self.judge.now()    }    pub fn judged_by(mut self, judge: Arc<cotton_client::judge::JudgeClock>) -> ClientController {        self.judge = judge;        self    }    /// A test's phone that has heard its serving Mac: one reading at its own    /// clock, so its writes are Checked and queue rather than hold (slice 1).    #[cfg(test)]    #[must_use]    pub(crate) fn heard_the_serving_mac(self) -> ClientController {        let now = self.clock.now();        self.judge            .offer_server_time(&now.to_rfc3339(), now.timestamp_millis())            .expect("a reading");        self    }    /// The judge every replica this controller opens is written by.    pub fn replica_judge(&self) -> cotton_client::ReplicaJudge {        cotton_client::ReplicaJudge {            judge: Arc::clone(&self.judge) as Arc<dyn cotton_store::judge::JudgeSource>,            random: Arc::clone(&self.random),        }    }    /// Tell the controller the id the SERVER admits this device by. Installed    /// once, at open, from the same identity read the transport signs with.    pub fn set_self_device_id(&self, device_id: Option<String>) {        self.self_device_id.set(device_id);    }    /// That id, or `None` on a device with no identity yet — which is a named    /// state (it has not paired) and never a guess.    pub fn self_device_id(&self) -> Option<String> {        self.self_device_id.get()    }    /// Whether this device's copy has somewhere to sync — the personal    /// object it signed in to — rather than standing on its own    /// (`ConnectionMode::Local`, `noServerYet`): off the connection record    /// alone, a record that cannot be read answering `false`.    pub fn signed_in(&self) -> bool {        read_record(&self.layout.connection_json()).ok().flatten().is_some_and(|record| record.mine.mode.has_server())    }    /// The SLOT that id lives in, for a pass built before it is filled and    /// reading it when it runs (the thumbnail sweep, as the eviction pass).    pub fn device_key(&self) -> cotton_client::identity::DeviceKey {        self.self_device_id.clone()    }    /// Give the controller a way to reach the server. Until something does,    /// every push answers [`NO_TRANSPORT`].    pub fn set_transport(&self, source: Option<TransportSource>) {        *self.transport.lock().expect("the transport slot") = source;    }    /// Run the loop over the transport installed NOW: a loop already running    /// over another one is stopped, and an attached file's loop started again.    /// What `personal.connect` calls after it installs the personal object as    /// the far end — a launch may have attached the copy before it.    pub fn restart_sync_loop(&self) {        if let Ok(mut held) = self.sync_loop.lock() {            if let Some(mut running) = held.take() {                running.stop();            }        }        self.stop_media_drain();        if let Some(attached) = self.state.lock().ok().and_then(|state| state.as_ref().map(|a| (a.workspace_id.clone(), Arc::clone(&a.replica)))) {            self.start_sync_loop(&attached.0, &attached.1);        }    }    /// Is this device a runner (scope `runner`, with or without the placement    /// grant)? A runner holds no copy, serves nothing and stands by for nobody.    pub fn holds_no_copy(&self) -> bool {        cotton_client::connection::holds_no_copy(&self.layout)    }    /// A placement-only connection remembers its address, never opens a copy.    pub fn placement_database(&self) -> Option<String> {        let stored = read_connection(&self.layout.connection_json()).ok().flatten()?;        cotton_core::device::scope::DeviceScope::from_pair(stored.device_scope.as_deref(), Some(i64::from(stored.takes_placements))).ok()?.placement_runner().then_some(stored.workspace_id).flatten()    }    /// Give the controller the ONE signed fetch this process talks through.    ///    /// Installed once, at open, by whoever assembles the device identity and    /// the remembered address; every caller that needs to ask the server a    /// question takes it from here rather than building a second one.    #[cfg(test)]    pub fn set_fetch(&self, fetch: Option<FetchSource>) {        *self.fetch.lock().expect("the fetch slot") = fetch;    }    /// The signed fetch, when this process has one.    ///    /// `None` is the honest answer of a build or a launch with no device key    /// and no address — the caller refuses with [`NO_SIGNED_REQUESTS`] rather    /// than inventing an answer.    pub fn fetch(&self) -> Option<FetchSource> {        self.fetch.lock().expect("the fetch slot").clone()    }    /// Give the controller the note the transport writes.    pub fn set_refusals(&self, refusals: Option<Arc<cotton_client::transport::RefusalMemory>>) {        *self.refusals.lock().expect("the refusal slot") = refusals;    }    /// Has this device joined a server, as the CACHE says?    ///    /// Never the network. "Who is here?" is answered before "is there a file?",    /// and a phone with no server has to reach Join in one frame — a boot read    /// that asked a socket would hold the splash for a round trip that was    /// always going to fail.    ///    /// **A file that cannot be read is an ERROR, never a `false`.** That is    /// [`read_connection`]'s own rule and this is the caller it was written    /// for: `false` here means "this person has never joined anything", and    /// answering it on the strength of a bad disk read sends a paired phone to    /// the Join screen and asks it to pair again as a new device. The boot read    /// hands the error up and the app paints a fallback with a Retry.    pub fn joined_workspace(&self) -> Result<bool, String> {        Ok(read_connection(&self.layout.connection_json())            .map_err(|error| error.to_string())?            .and_then(|stored| stored.workspace_id)            .is_some())    }    /// The cached `/v1/me` answer, as the gate reads it.    ///    /// `ownerId` is the gate's "who is here?" — `null` IS `signed-out` — and    /// `serverUrl` is what a refusal screen pre-fills the Join form with. Both    /// come off `connection.json`, which is where the join wrote them.    ///    /// Loud for the reason [`Self::joined_workspace`] is: an empty object and    /// an unreadable file are not the same answer.    pub fn cached_identity(&self) -> Result<Value, String> {        let Some(stored) = read_connection(&self.layout.connection_json())            .map_err(|error| error.to_string())?        else {            return Ok(json!({}));        };        Ok(json!({            "ownerId": stored.owner_id,            "workspaceId": stored.workspace_id,            "serverUrl": stored.base_url,            // The short name the address stands for, when it is a relay one.            // Asked of `cotton-core` rather than sliced here: the pattern is            // the relay lane's and there is no second copy.            "serverName": cotton_core::device::pairing::relay_name_of(&stored.base_url),        }))    }    /// Fold this device's write-ahead log back into the replica.    ///    /// Answers whether there was a file to do it to — `false` on a phone that    /// has not attached, which is not a failure: there is nothing to fold.    ///    /// **Never attaches.** `sync.background` is the caller, and opening a    /// replica on the way OUT to checkpoint it would be the recovery this is    /// meant to avoid, paid at the worst possible moment. `attached_replica`    /// asks what is already open and nothing more.    pub fn checkpoint(&self) -> bool {        let Ok((_workspace_id, replica)) = self.attached_replica() else {            return false;        };        let Ok(replica) = replica.lock() else {            return false;        };        replica.driver.checkpoint_truncate().is_ok()    }    /// The standing refusal only the server can reverse, if one stands.    ///    /// `{code, sentence, serverUrl, serverName, at, erase}` — everything    /// `ServerRefusalScreen` draws, including the address it pre-fills the Join    /// form with.    ///    /// **`erase` is what turns a question into an act.** A revocation is a    /// DECISION and the screen offers two verbs — *Keep my copy* and *Erase    /// Cotton from this iPhone*. When the owner already ticked the box on the    /// device they revoked this one from, the server's `403 device_revoked`    /// carries `erase: true`, and the app takes the second verb without asking    /// (the app's erase) rather than putting a question to somebody who has    /// answered it. `false` on anything else, and on a note an older build    /// wrote, because the safe reading is the one that asks.    ///    /// **The erase guard** (slice 12): `erase` is `true` only when this    /// device's own copy may go for the epoch the refusal named    /// ([`cotton_client::bootstrap::may_erase_at`]) — never from a Mac it has    /// not handed over to, nor from an older one come back.    pub fn standing_refusal(&self) -> Option<Value> {        let held = self.refusals.lock().ok()?.clone()?;        let note = held.standing_terminal()?;        let erase = note.erase && self.may_erase(note.serving_epoch);        Some(json!({            "code": note.code,            "sentence": cotton_client::connection::terminal_device_sentence(&note.code),            "serverUrl": note.server_url,            "serverName": note.server_name,            "answeringServer": note.refuser.tag(),            "callerDevice": note.device.or_else(|| self.self_device_id()),            "line": self.fetch().and_then(|fetch| fetch.answered_way()),            "at": note.at,            "erase": erase,        }))    }    /// May a refusal naming `serving_epoch` erase this device's own copy?    /// Asked of Mine's replica file; a device with no database holds no copy.    fn may_erase(&self, serving_epoch: Option<i64>) -> bool {        match read_connection(&self.layout.connection_json()) {            Ok(stored) => stored.and_then(|stored| stored.workspace_id).is_none_or(|mine| {                cotton_client::bootstrap::may_erase_at(&self.layout.replica(&mine), serving_epoch)            }),            Err(_) => false,        }    }    /// Why every authoring entry on this device refuses right now, or `None`.    ///    /// **ONE CHOKEPOINT, BELOW THE BOUNDARY.** A server that has refused    /// THIS DEVICE for good (`RefusalMemory::standing_terminal` — not    /// approved, revoked, a bad signature, no key) has stopped admitting its    /// ops, so a row filed now reaches no other device and may never. The    /// app opens read-only over the copy it holds and says so in a banner;    /// what makes "nothing new is saved" TRUE is this method, asked first by    /// [`Self::write`], [`Self::write_rows_with_vault`] (and so every    /// `capture.*`, `dictation.create`, `session.*`, `settings.*`,    /// `vault.*` write) and [`Self::import_rows`], and by    /// `vault.unlock` / `vault.reveal`, which open nothing on a device the    /// server no longer trusts. The Swift `WriteGate` is only the field's    /// early answer to the same fact.    ///    /// The sentence is the crate's own ([`terminal_device_sentence`]).    pub fn write_refusal(&self) -> Option<String> {        let held = self.refusals.lock().ok()?.clone()?;        let note = held.standing_terminal()?;        Some(            cotton_client::connection::terminal_device_sentence(&note.code)                .unwrap_or_else(|| format!("the server refused this device ({})", note.code)),        )    }    /// [`Self::write_refusal`] as the `Err` an authoring entry answers —    /// and, for a call that NAMES a database, that database's own answer.    ///    /// A database this device was removed from is read-only: its copy stays,    /// and a write filed into it would reach nobody. That refusal is the    /// named database's alone; the personal one is not asked about it.    ///    /// A named database that does take the write is noted as no longer idle    /// (`HeldNotes::note_write`), so the next cycle opens its file rather    /// than letting its note say there is nothing to hand over.    fn refuse_writes(&self) -> Result<(), String> {        if let Some(sentence) = self.write_refusal() {            return Err(sentence);        }        let Some(database) = named_database() else {            return Ok(());        };        if let Some(sentence) = self.removed_from(&database) {            return Err(sentence);        }        let notes =            cotton_client::connection::held::HeldNotes::beside(&self.layout.connection_json());        if let Err(error) = notes.note_write(&database) {            // The note is a saving: without it the next pass must open the            // file, so a note that could not be changed is dropped.            eprintln!("[cotton-sync] the held note was not updated: {error}");            let _ = notes.forget(&database);        }        Ok(())    }    /// The sentence for a database this device was removed from, or `None`.    pub fn removed_from(&self, database: &str) -> Option<String> {        read_record(&self.layout.connection_json())            .ok()            .flatten()?            .places            .iter()            .find(|place| place.id == database && place.removed_at.is_some())            .map(cotton_client::connection::joined::removed_sentence)    }    /// Close this device's handle on `database` for good: an open in flight    /// does not put it back ([`OtherOpens::letting_go`]).    fn let_go_of(&self, database: &str) -> Result<(), String> {        let mut others = self.others.lock().map_err(|_| locked())?;        self.other_opens.letting_go();        others.close(database);        Ok(())    }    fn connection_file(&self) -> Arc<cotton_client::connection::ConnectionFile> {        Arc::new(cotton_client::connection::ConnectionFile::at(            self.layout.connection_json(),        ))    }    /// The copies of databases this device was removed from — its Bin's    /// removed rows. Off the connection record alone.    pub fn removed_copies(&self) -> Vec<RemovedCopy> {        let Some(record) = read_record(&self.layout.connection_json()).ok().flatten() else {            return Vec::new();        };        cotton_client::connection::joined::removed_copies(&record)            .into_iter()            .filter_map(|place| {                let removed_at = place.removed_at.clone()?;                Some(RemovedCopy {                    database_id: place.id.clone(),                    name: place.name.clone().unwrap_or_default(),                    removed_by: place.removed_by.clone(),                    purge_at: cotton_client::connection::joined::purge_at(&removed_at),                    removed_at,                })            })            .collect()    }    /// The Debug group's explicit act: retire one observed failed copy,    /// retaining its whole directory. No queued write is left behind and no    /// SQLite handle survives the rename. New opens stop until it finishes.    pub(crate) fn archive_refused_copy(&self,database:&str,kept:&std::path::Path,validate:impl FnOnce()->Result<(),String>)->Result<(),String> {        if !self.databases()?.iter().any(|held|held.id==database) {            return Err("Only a held phone copy can be removed here.".into());        }        if self.placing.compare_exchange(false,true,std::sync::atomic::Ordering::SeqCst,std::sync::atomic::Ordering::SeqCst).is_err() {            return Err("A copy is being put in place; try this act once that finishes.".into());        }        let mut detached=false;        let result=(|| {            let turn=self.other_opens.turn(database);            let _turn=turn.lock().map_err(|_|locked())?;            validate()?;            let path=self.layout.replica(database);            let mut writers=Vec::new();            let mut readers=Vec::new();            if let Some(state)=self.state.lock().map_err(|_|locked())?.as_ref().filter(|state|state.workspace_id==database) {                writers.push(Arc::downgrade(&state.replica));readers.push(Arc::downgrade(&state.readers));            }            if let Some(open)=self.others.lock().map_err(|_|locked())?.get(database) {                writers.push(Arc::downgrade(&open.replica));readers.push(Arc::downgrade(&open.readers));            }            self.detach();            detached=true;            let until=std::time::Instant::now()+std::time::Duration::from_secs(1);            while writers.iter().any(|weak|weak.upgrade().is_some()) || readers.iter().any(|weak|weak.upgrade().is_some()) {                if std::time::Instant::now()>=until { return Err("A read or write still holds this copy; it has been kept unchanged.".into()); }                std::thread::sleep(std::time::Duration::from_millis(10));            }            // With our handles closed, a readable SQLite file must have no            // outstanding WAL. Immutable inspection cannot change sidecars.            if super::database_files::sqlite_header(&path) {                if path.with_extension("db-wal").metadata().is_ok_and(|meta|meta.len()>0) {                    return Err("This copy still has a SQLite log; it has been kept until it can be checked.".into());                }                let absolute=std::fs::canonicalize(&path).map_err(|error|error.to_string())?;                let encoded:String=absolute.as_os_str().as_encoded_bytes().iter().map(|byte|match *byte {                    b'/'|b':'|b'-'|b'_'|b'.'|b'0'..=b'9'|b'A'..=b'Z'|b'a'..=b'z'=>char::from(*byte).to_string(),                    byte=>format!("%{byte:02X}"),                }).collect();                if let Ok(connection)=rusqlite::Connection::open_with_flags(format!("file:{encoded}?immutable=1"),rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY|rusqlite::OpenFlags::SQLITE_OPEN_URI) {                    for sql in ["SELECT COUNT(*) FROM _outbox","SELECT COUNT(*) FROM _writes WHERE held=1","SELECT COUNT(*) FROM _tombstones WHERE held=1","SELECT COUNT(*) FROM _parked WHERE direction='push'"] {                        if connection.query_row(sql,[],|row|row.get::<_,i64>(0)).is_ok_and(|count|count>0) {                            return Err("This copy holds changes not yet taken by the Mac; they must be sent before it can be removed.".into());                        }                    }                }            }            std::fs::create_dir_all(kept.parent().ok_or("The retained-copy folder is missing.")?).map_err(|error|error.to_string())?;            // The copy moves whole, through the one place a copy moves (QUEUE BAD OP 4).            cotton_client::copy_keep::relocate_folder(path.parent().ok_or("The copy folder is missing.")?,&kept)?;            self.note_fill(database,None);            self.events.emit(EventKind::Data,json!({"workspaceId":database,"tables":["cotton_workspaces"],"origin":"local"}));            Ok(())        })();        self.set_placing(false);        if detached { let _=self.attach(); }        result    }    /// What a pass REPORTED for one database (`databaseSync_frame`), and the    /// home's line it leaves that database on. `refused` is a section    /// unanswered because the Mac and this build disagree about the schema.    #[cfg(test)]    fn say_reported(        &self,        database: &str,        reported: Option<cotton_client::sync::Reported>,        refused: Option<cotton_client::sync::SchemaStanding>,        moved: Option<cotton_client::sync::TableMoves<'_>>,    ) {        self.say_response(database, reported, refused, moved, false);    }    #[cfg(test)]    fn say_response(        &self,        database: &str,        reported: Option<cotton_client::sync::Reported>,        refused: Option<cotton_client::sync::SchemaStanding>,        moved: Option<cotton_client::sync::TableMoves<'_>>,        answered: bool,    ) {        let now_ms = self.clock.now().timestamp_millis();        let standing = self.home_lines.heard(database, reported, refused, moved, answered, now_ms);        self.events.emit(EventKind::Client, database_sync_frame(database, reported, &standing));    }    /// A copy of the whole of `database`'s file is under way with    /// `bytes_to_go` still to arrive, or (`None`) it is over. The whole-file    /// lane's to call as its download moves; what the cap and the page say of    /// it ("copying · 400 MB to go") is `cotton_client::sync::line`'s.    pub fn say_copying(&self, database: &str, bytes_to_go: Option<u64>) {        let now_ms = self.clock.now().timestamp_millis();        let standing = self.home_lines.copying(database, bytes_to_go, now_ms);        self.events.emit(EventKind::Client, database_sync_frame(database, None, &standing));    }    /// Open the replica now, and say whether it took.    ///    /// The lazy [`Self::attach`] is what every method calls; this is for the    /// one caller that has just PUT a file there — the bootstrap — and wants    /// the controller holding it before the next question arrives, rather than    /// on whichever method happens to ask first.    /// Open the copy `connection.json` names, as the gate asks it    /// (`shell.home`, on a thread of its own).    pub(crate) fn open_copy(&self) -> Result<(), String> {        self.attach()    }    /// The object's word when it stopped taking this phone's credential,    /// while that stands.    pub fn signed_out_code(&self) -> Option<String> {        self.signed_out.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// The object stopped taking this phone's credential (`code`), or a    /// connect was taken again (`None`).    pub fn note_signed_out(&self, code: Option<String>) {        *self.signed_out.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = code;    }    /// The last trouble with the object, `(words, when)`.    pub fn last_trouble(&self) -> Option<(String, String)> {        self.last_trouble.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Something went wrong with the object just now (`words`), or the    /// person signed out and nothing is left to say (`None`).    /// Words that name a sealing refusal by its code are the core's own: the    /// Account card says the kit's line for them, and the log keeps them.    pub fn note_trouble(&self, words: Option<String>) {        self.note_trouble_coded("", words);    }    /// [`Self::note_trouble`] for a refusal whose `code` is held: words    /// that say the object did not answer (a 5xx, nothing reached, too busy:    /// `cotton_client::transport::object::names_an_unanswered_object`) are    /// the core's own too, kept in the log, and the card says the kit's    /// line that Cotton could not be reached just now (incident, 21 Nov    /// 2026: Last error read "the business did not answer").    pub fn note_trouble_coded(&self, code: &str, words: Option<String>) {        let words = words.map(|words| {            let kit = if cotton_client::seal::names_a_seal_refusal(&words) {                "trouble.sealed"            } else if cotton_client::transport::object::names_an_unanswered_object(code, &words) {                "trouble.unreached"            } else {                return words;            };            eprintln!("[object] {words}");            cotton_core::rules::shell_lines::LineSet::shipped("backup").and_then(|lines| lines.say(kit, &[])).unwrap_or_default()        });        let noted = words.map(|words| (words, chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)));        *self.last_trouble.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = noted;    }    /// What the last top-up sent: `(sent, refused, when)`.    pub fn topped_up(&self) -> Option<(u64, u64, String)> {        self.topped_up.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// A top-up ended having sent `sent` rows and been refused `refused`    /// (`Some`), or the person signed out (`None`).    pub fn note_topped_up(&self, sent: Option<(u64, u64)>) {        let noted = sent.map(|(sent, refused)| (sent, refused, chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)));        *self.topped_up.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = noted;    }    /// Whether a top-up is running now.    pub fn topping_up(&self) -> bool {        self.topping_up.load(std::sync::atomic::Ordering::SeqCst)    }    /// A top-up begins (true: none was running) or ends.    pub fn set_topping_up(&self, running: bool) -> bool {        !self.topping_up.swap(running, std::sync::atomic::Ordering::SeqCst)    }    /// Why the last `personal.connect` did not take, while that stands.    pub fn connect_refused(&self) -> Option<(String, String)> {        self.connect_refused.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// A `personal.connect` was refused (`code`, its words), or one took, an    /// adopt began, or the person signed out (`None`).    pub fn note_connect_refused(&self, refused: Option<(String, String)>) {        *self.connect_refused.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = refused;    }    /// The database this phone stays signed in to while its connect runs or    /// after one that did not take ([`Self::kept_signed_in`]'s field).    pub fn kept_signed_in(&self) -> Option<String> {        self.kept_signed_in.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    pub fn keep_signed_in(&self, database: Option<String>) {        *self.kept_signed_in.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = database;    }    /// A `personal.connect` begins (true) or ends.    pub fn set_connecting(&self, running: bool) {        self.connecting.store(running, std::sync::atomic::Ordering::SeqCst);    }    /// Whether this phone's copy is being connected or put in place now: a    /// `personal.connect` runs, or an arrived copy is being placed.    pub fn moving(&self) -> bool {        self.connecting.load(std::sync::atomic::Ordering::SeqCst) || self.placing.load(std::sync::atomic::Ordering::SeqCst)    }    /// Take the turn to swap the database this phone stands on: held from    /// before the detach until the new one stands, while every read on    /// another thread waits (`super::swap`).    pub fn swapping(&self) -> super::swap::SwapTurn {        self.swap.enter()    }    /// Whether a swap is under way on any thread (tests).    #[cfg(test)]    pub fn swapping_now(&self) -> bool {        self.swap.swapping()    }    /// AT THE END OF A SWAP, nothing stays open but what the connection    /// names now. A read already under way when the swap began, which came    /// to open after its detach, opened the database the connection still    /// named (the one being set aside or deleted, or the same copy under its    /// old mode); the fresh database's own open then found one open and    /// opened nothing. That one is let go here, inside the turn, and the next    /// question opens what stands. An open in flight is waited for first    /// (the turn to open): it read the connection before the swap wrote it.    pub fn let_go_if_stale(&self) {        let _turn = self.attaching.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        let named = read_connection(&self.layout.connection_json()).ok().flatten();        let stale = self.state.lock().ok().is_some_and(|state| {            state.as_ref().is_some_and(|attached| {                named.as_ref().is_none_or(|named| {                    named.workspace_id.as_deref() != Some(attached.workspace_id.as_str()) || named.mode != attached.connection.mode                })            })        });        if stale {            self.detach();        }    }    /// The swap of the database this phone stands on, which every call from    /// the app waits out (`methods::dispatch_across_swaps`).    pub fn swap_gate(&self) -> &super::swap::SwapGate {        &self.swap    }    pub fn attach_now(&self) -> Result<(), String> {        // The thread that put the copy in place attaches it: its own placing        // is over.        self.set_placing(false);        self.attach()    }    /// A bootstrap or re-hydrate thread says its arrived copy is (or is no    /// longer) being put in place.    pub fn set_placing(&self, placing: bool) {        self.placing.store(placing, std::sync::atomic::Ordering::SeqCst);    }    /// Let go of the replica and everything built over it.    ///    /// Called when the person leaves a server: the file is about to be deleted,    /// and a controller still holding an open handle on it would keep the    /// deleted inode alive and answer questions about a database nobody has any    /// more.    pub fn detach(&self) {        // Caught up belongs to the copy: one let go (signed out, made again) is caught up no more.        if let Ok(mut held) = self.caught_up_for.lock() {            *held = None;        }        if let Ok(mut held) = self.caught_up_once_for.lock() {            *held = None;        }        // The SCHEDULE goes first. A loop left running over a replica that is        // about to be deleted would open the next pass on a file nobody has,        // and `Drop` alone would not be soon enough: the state lock below is        // what the pass is waiting on.        if let Ok(mut held) = self.sync_loop.lock() {            if let Some(mut running) = held.take() {                running.stop();            }        }        self.stop_media_drain();        // BEFORE the slot is emptied: an open in flight reads this when it        // comes to install its handle, and finds the file it opened let go.        self.detaches.fetch_add(1, std::sync::atomic::Ordering::SeqCst);        if let Ok(mut state) = self.state.lock() {            *state = None;        }        // EVERY OTHER HELD FILE TOO: leaving deletes them all, and a handle        // kept here would keep a deleted file alive.        if let Ok(mut others) = self.others.lock() {            self.other_opens.letting_go();            others.clear();        }        // And after the loop has stopped: its last word may have said caught up again.        if let Ok(mut held) = self.caught_up_for.lock() {            *held = None;        }        if let Ok(mut held) = self.caught_up_once_for.lock() {            *held = None;        }    }    /// Every database this device holds: its own first, then each other one    /// the server last listed for it.    ///    /// Read from the connection record every time, as [`Self::attach`] reads    /// it: a database admitted a moment ago is held from the next question on.    /// One that went missing from the listing keeps its file and is not named    /// here — nothing opens or syncs it until it is listed again.    pub fn held_databases(&self) -> Result<Vec<String>, String> {        held_ids(&self.layout)    }    /// The databases this device holds at the household's own address — what    /// one sync pass covers, and what a media pass over "every database" means.    /// One joined at another person's Mac is not among them.    pub fn household_databases(&self) -> Vec<String> {        household_ids(&self.layout)    }    /// Every database this device syncs, joined ones included — what a pass    /// over this device's bytes means by "every database".    pub fn syncing_databases(&self) -> Vec<String> {        syncing_ids(&self.layout)    }    /// The open handles on one NAMED database this device holds.    ///    /// The device's own is the attachment. Any other is opened here on first    /// use — its own connection, never attached to another file's — and kept    /// in a small set that closes the least recently used idle one. A database    /// this device does not hold is refused by name: there is no default file    /// a wrong id falls back onto.    pub fn open_database(&self, database: &str) -> Result<OpenFile, String> {        if self.placement_database().is_some() { return Err("a placement-only device keeps no database copy".into()); }        if self.placing.load(std::sync::atomic::Ordering::SeqCst) { return Err(NOT_ARRIVED.into()); }        let record=read_record(&self.layout.connection_json()).map_err(|error|error.to_string())?;        // REMOVED IS GONE FROM EVERY READER, a handle opened before the        // removal included: it is closed, and nothing is answered from it.        if record.as_ref().is_some_and(|record|record.places.iter().any(|place|place.id==database && place.removed_at.is_some())) {            let _ = self.let_go_of(database);            return Err(not_held(database));        }        let own=record.and_then(|record|record.mine.workspace_id);        if own.as_deref()==Some(database) { self.attach()?; }        {            let state = self.state.lock().map_err(|_| locked())?;            if let Some(attached)=state.as_ref().filter(|attached|attached.workspace_id==database) {                return Ok(OpenFile {                    workspace_id: attached.workspace_id.clone(),                    replica: Arc::clone(&attached.replica),                    readers: Arc::clone(&attached.readers),                });            }        }        open_other(            &self.layout,            self.clock.as_ref(),            self.random.as_ref(),            self.replica_judge(),            self.receipt_signer.clone(),            &self.others,            &self.other_opens,            &self.feeds,            Arc::clone(&self.events),            database,        )        // With how far the download is, or why the last one stopped.        .map_err(|reason| match self.arriving(database) {            Some(arriving) if reason == NOT_ARRIVED => arriving,            _ => reason,        })    }    /// WHERE A HELD DATABASE'S ARRIVAL STANDS, as the screen reads it —    /// `None` when it is here (or is the device's own, or was made here and    /// the server has not taken it yet): `{state: "waiting"}` before a byte,    /// `{state: "arriving", bytesWritten, totalBytes}` while its body comes,    /// `{state: "failed", reason}` when the last try stopped (another is made    /// by itself). A state the screen draws on the cap, never an error: the    /// owner's phone painted thirteen "could not be read"s for databases that    /// were simply on their way (11 Oct 2026).    ///    /// Off the connection record and one `exists`: no file is opened, so    /// `read.databases` can ask it for every row.    pub fn arrival(&self, database: &str) -> Option<Value> {        Some(match self.unarrived(database)? {            Some(Fill::Downloading { written, total }) => {                json!({ "state": "arriving", "bytesWritten": written, "totalBytes": total })            }            Some(Fill::Failed(reason)) => json!({ "state": "failed", "reason": reason }),            None => json!({ "state": "waiting" }),        })    }    /// A held database whose copy is not here, with where its fill stands —    /// `None` when there is nothing to arrive.    fn unarrived(&self, database: &str) -> Option<Option<Fill>> {        let record = read_record(&self.layout.connection_json()).ok().flatten()?;        // THE DEVICE'S OWN, MID-COPY: no file yet, or a copy being checked,        // unpacked and claimed — where its download stands, never a plain        // database with nothing in it. 12 Oct 2026, the owner's phone: an        // empty Personal page with "only you" under its cap, over a copy still        // coming in.        if record.mine.workspace_id.as_deref() == Some(database) {            let placing = self.placing.load(std::sync::atomic::Ordering::SeqCst);            if !placing && self.layout.replica(database).exists() {                return None;            }            return Some(self.fills.lock().unwrap_or_else(|error| error.into_inner()).get(database).cloned());        }        if self.layout.replica(database).exists() {            return None;        }        let place = record.places.iter().find(|place| place.id == database)?;        if place.pending || !place.available {            return None;        }        Some(self.fills.lock().unwrap_or_else(|error| error.into_inner()).get(database).cloned())    }    /// The sentence for a held database whose copy has not arrived on this    /// device, for a read of it that cannot be answered ([`Self::arrival`]).    pub fn arriving(&self, database: &str) -> Option<String> {        let fill = self.unarrived(database)?;        let megabytes = |bytes: u64| bytes.div_ceil(1024 * 1024);        Some(match fill {            Some(Fill::Downloading { written, total: Some(total) }) => format!(                "This database is arriving on this device — {} of {} MB so far.",                megabytes(written),                megabytes(total)            ),            Some(Fill::Downloading { written, total: None }) => format!(                "This database is arriving on this device — {} MB so far.",                megabytes(written)            ),            Some(Fill::Failed(reason)) => format!(                "This database has not arrived on this device yet. Its last download did not finish: {reason} Cotton tries again by itself."            ),            None => NOT_ARRIVED.to_string(),        })    }    /// Where a whole copy of the device's own database stands, from the    /// bootstrap or re-hydrate thread moving it: `bytes` written of `total`,    /// or why it stopped, or (`None`, `None`) that it is over. What the list    /// draws for the device's own while its file is not in place    /// ([`Self::arrival`]).    pub fn note_own_copy(&self, database: &str, bytes: Option<(u64, Option<u64>)>, failed: Option<String>) {        self.copy_moved(database, bytes, failed.as_deref());        let fill = match (bytes, failed) {            (_, Some(reason)) => Some(Fill::Failed(reason)),            (Some((written, total)), None) => Some(Fill::Downloading { written, total }),            (None, None) => None,        };        self.note_fill(database, fill);    }    fn note_fill(&self, database: &str, fill: Option<Fill>) {        let mut fills = self.fills.lock().unwrap_or_else(|error| error.into_inner());        match fill {            Some(fill) => fills.insert(database.to_string(), fill),            None => fills.remove(database),        };    }    /// Pin a database a window's screens are drawing, so no pass over the    /// others closes it. Counted: every `show` is undone by one    /// [`Self::hide_database`], so two windows showing one database keep it    /// open until both turn away. The device's own is always open and takes no    /// pin.    pub fn show_database(&self, database: &str) -> Result<(), String> {        if self.genesis() == cotton_core::genesis::Genesis::None            && self.databases()?.iter().any(|held| held.id == database && held.personal) {            return Err(cotton_core::genesis::NO_PERSONAL_MESSAGE.into());        }        let open = self.open_database(database)?;        if !self.is_own(&open.workspace_id)? {            self.others.lock().map_err(|_| locked())?.pin(database);        }        Ok(())    }    /// One window stopped drawing `database`. Never refuses: a window turning    /// away from a database this device no longer holds is still turning away.    pub fn hide_database(&self, database: &str) {        if let Ok(mut others) = self.others.lock() {            others.unpin(database);        }    }    /// The databases pinned by a window right now, in id order.    pub fn shown_databases(&self) -> Vec<String> {        self.others            .lock()            .map(|others| others.shown())            .unwrap_or_default()    }    fn is_own(&self, database: &str) -> Result<bool, String> {        let state = self.state.lock().map_err(|_| locked())?;        Ok(state            .as_ref()            .is_some_and(|attached| attached.workspace_id == database))    }    /// Every database this device holds, with the name to draw: the personal    /// one first, then each other in the order it was admitted.    ///    /// Off the connection record alone — no file is opened and nothing is    /// asked of a server, so a list of twelve idle databases costs one small    /// read.    pub fn databases(&self) -> Result<Vec<HeldDatabase>, String> {        let Some(record) =            read_record(&self.layout.connection_json()).map_err(|error| error.to_string())?        else {            return Ok(Vec::new());        };        let mut held = Vec::new();        if let Some(mine) = record.mine.workspace_id.clone() {            let (personal, name) = if self.genesis() == cotton_core::genesis::Genesis::None {                match cotton_store::Driver::open_reader(self.layout.replica(&mine)) {                    Ok(db) => primary_database(&db, self.genesis())?,                    Err(_) => (false, String::new()),                }            } else { (true, PERSONAL_NAME.to_string()) };            held.push(HeldDatabase {                id: mine,                name,                personal,                pending: false,                theirs: false,            });        }        for place in record.places {            // One this device was removed from is in its Bin and nowhere else            // (`removed_copies`): no cap, no Home, no Members, no Photos.            if place.available                && place.removed_at.is_none()                && !held.iter().any(|database| database.id == place.id)            {                held.push(HeldDatabase {                    pending: place.pending,                    theirs: place.origin.is_some(),                    name: place.name.unwrap_or_default(),                    id: place.id,                    personal: false,                });            }        }        Ok(held)    }    /// An explicit archive read: the serving Mac's alone.    pub fn archived_databases(&self) -> Result<Vec<Value>, String> {        Err("The serving Mac is unavailable".to_string())    }    /// [`Self::databases`] as this app shows them (`super::scope`): Personal    /// left out where the manifest names another database, and every database    /// but the named one left out. What the list of databases and the feeds    /// read; the person's own facts keep reading [`Self::databases`].    pub fn scoped_databases(&self) -> Result<Vec<HeldDatabase>, String> {        Ok(self            .databases()?            .into_iter()            .filter(|database| self.scope().shows(database.personal, &database.id)                && !(database.personal && self.genesis() == cotton_core::genesis::Genesis::None))            .collect())    }    /// This launch's typed Personal policy, shared with every creation path.    pub fn genesis(&self) -> cotton_core::genesis::Genesis {        cotton_core::genesis::Genesis::at(self.layout.root()).unwrap_or(cotton_core::genesis::Genesis::None)    }    /// Existing synthetic installs keep their own Personal working until reinstall.    pub fn require_personal(&self) -> Result<(), String> {        if self.genesis() == cotton_core::genesis::Genesis::None            && !self.databases()?.iter().any(|database| database.personal) {            return Err(cotton_core::genesis::NO_PERSONAL_MESSAGE.into());        }        Ok(())    }    /// This app's scope, as its manifest said it.    pub fn scope(&self) -> &super::scope::DatabaseScope {        static EVERY: super::scope::DatabaseScope = super::scope::DatabaseScope::Every;        self.scope.get().unwrap_or(&EVERY)    }    /// Set the app's scope — once, at open, before anything is held; a second    /// one is refused, so no call can widen what an app shows.    pub fn limit_to(&self, scope: super::scope::DatabaseScope) -> Result<(), String> {        super::scope::keep(&self.layout, &scope)?;        // ONE DATABASE, ONE COPY (70th amendment): on a device, every held        // copy this scope does not admit goes with its bytes, here at open,        // before anything is held or synced. A Mac holds what it serves.        if scope != super::scope::DatabaseScope::Every {            let removed = cotton_client::join::leave::remove_out_of_scope(&self.layout, &self.connection_file(), |database| scope.admits(database));            if !removed.is_empty() {                tracing::info!(removed = removed.len(), "copies outside this app's scope removed");            }        }        self.scope.set(scope).map_err(|_| "this app's databases are already set".to_string())    }    /// Whether this app syncs at all: false where its manifest says    /// `"sync": false` (Rigby — one device, no Mac).    pub fn syncs(&self) -> bool {        *self.syncs.get().unwrap_or(&true)    }    /// Which app identity opened this client; `None` where none was declared.    pub fn flavor(&self) -> Option<cotton_core::flavor::Flavor> {        self.flavor.get().copied()    }    /// Say which app identity opened this client — once, at open.    pub fn declare_flavor(&self, flavor: cotton_core::flavor::Flavor) -> Result<(), String> {        self.flavor.set(flavor).map_err(|_| "this app's flavor is already set".to_string())    }    /// Mark this app as one that never syncs — once, at open.    pub fn without_sync(&self) -> Result<(), String> {        self.syncs.set(false).map_err(|_| "this app's sync is already set".to_string())    }    /// Bin facts are read only when the Bin opens; removed members cannot restore.    pub fn binned_databases(&self) -> Result<Vec<Value>, String> {        let Some(record) =            read_record(&self.layout.connection_json()).map_err(|error| error.to_string())?        else {            return Ok(Vec::new());        };        let mut rows = Vec::new();        for place in record            .places            .into_iter()            .filter(|place| place.removed_at.is_some())        {            let deleted_at = place.removed_at.as_deref().unwrap();            let creator_name=cotton_store::Driver::open_reader(self.layout.replica(&place.id)).ok().and_then(|db|db.get("SELECT person_name FROM cotton_admissions WHERE rights='owner' ORDER BY _hlc,id LIMIT 1",&[]).ok().flatten().and_then(|row|row.text("person_name").map(str::to_string)));            // A member removed from it says who removed them in place of            // who made it (`removed_by`); only the creator's own copy restores.            let creator_name = if place.removed_by.is_some() { None } else { creator_name };            rows.push(json!({"databaseId":place.id,"name":place.name,"creator_name":creator_name,"removed_by":place.removed_by,"deletedAt":deleted_at,"can_restore":place.origin.is_none() && !cotton_store::database_bin::purge_due(deleted_at,self.clock.now())}));        }        Ok(rows)    }    /// Answer the rest of this call, on this thread, from `database`.    ///    /// `None` is the device's own, and is SET like any other name: see    /// [`NAMED`]. A database this device does not hold is refused here, by    /// name, before the method runs — there is no default file a wrong id    /// falls back onto.    pub fn name_database(&self, database: Option<&str>) -> Result<NamedDatabase, String> {        if let Some(database) = database {            self.open_database(database)?;        }        let before = NAMED.with(|named| named.replace(database.map(str::to_string)));        Ok(NamedDatabase { before })    }    /// [`Self::name_database`] for a SHORT read (`ShortRead`): the database is    /// held and here, but it is NOT opened — the short read reads its file    /// directly when nothing has opened it (`short_direct`), so naming it never    /// waits on its turn, ladder and rebuild (readpool, 16 Oct 2026). The    /// refusals are the open's own: not held, removed, or still arriving.    pub fn name_database_unopened(&self, database: &str) -> Result<NamedDatabase, String> {        if self.placement_database().is_some() {            return Err("a placement-only device keeps no database copy".into());        }        if self.placing.load(std::sync::atomic::Ordering::SeqCst) {            return Err(NOT_ARRIVED.into());        }        if self.removed_from(database).is_some() || !held_ids(&self.layout)?.iter().any(|held| held == database) {            return Err(not_held(database));        }        if let Some(arriving) = self.arriving(database) {            return Err(arriving);        }        let before = NAMED.with(|named| named.replace(Some(database.to_string())));        Ok(NamedDatabase { before })    }    pub(crate) fn reading_database_id(&self)->Option<String> {        NAMED.with(|named|named.borrow().clone()).or_else(||read_record(&self.layout.connection_json()).ok().flatten().and_then(|record|record.mine.workspace_id))    }    /// Close every other database nothing is using — the shown one stays.    ///    /// What a pass calls when it is done with the files it opened in turn: an    /// idle database costs no handle, no page cache and no file descriptor.    pub fn close_idle_databases(&self) {        if let Ok(mut others) = self.others.lock() {            let closed = others.close_idle(OpenFile::idle);            close_handles(&self.layout, &self.feeds, closed);        }    }    /// A feed's answer from one held database that is not this device's own    /// (`feed_index`): kept from the last time the file had the stamp it has    /// now, without opening it; otherwise read by `read`, with the file open,    /// and kept when nothing wrote to it while it was read.    pub fn indexed_read(        &self,        database: &str,        key: &str,        read: impl FnOnce() -> Result<Value, String>,    ) -> Result<Value, String> {        let path = self.layout.replica(database);        let index = || self.feeds.lock().unwrap_or_else(|error| error.into_inner());        if let Some(stamp) = feed_index::stamp(&path) {            if let Some(answer) = index().answer(database, &stamp, key) {                return Ok(answer);            }        }        // Open first, so the stamps either side of the read are both an open        // file's: opening a closed file moves its stamp by itself.        self.open_database(database)?;        let before = feed_index::stamp(&path);        let answer = read()?;        let after = feed_index::stamp(&path);        if let Some(stamp) = before.filter(|before| Some(before) == after.as_ref()) {            index().keep(database, stamp, key.to_string(), answer.clone());        }        Ok(answer)    }    /// The other databases open right now — the device's own is not counted.    #[cfg(test)]    pub fn open_databases(&self) -> Vec<String> {        self.others            .lock()            .map(|others| others.open_ids())            .unwrap_or_default()    }    /// [`Self::with_file`] on a NAMED database.    ///    /// `#[track_caller]`, so a wait for a reader says where its caller asked    /// for it, never this line.    #[track_caller]    pub fn with_file_in<T>(        &self,        database: &str,        work: impl FnOnce(&ReadFile<'_>) -> Result<T, String>,    ) -> Result<T, String> {        let direct = self.short_direct(database).transpose()?;        let open;        let lease;        let reader: &ReadReplica = match &direct {            Some(direct) => direct,            None => {                open = self.open_database(database)?;                lease = take_reader(&open.readers).map_err(read_not_open)?;                &lease            }        };        let mut answer = None;        let mut work = Some(work);        reader            .driver            .transaction(|_| {                if let Some(work) = work.take() {                    answer = Some(work(&ReadFile::of_reader(reader)));                }                Ok(())            })            .map_err(|error| error.to_string())?;        answer.expect("the read transaction ran the work exactly once")    }    /// A LOCAL READ of a named database that never takes its writer and never    /// opens it: the open database's read pool when it is open (the device's    /// own or another), else one read-only connection on its file for this    /// read alone, dropped after.    ///    /// RULE: a person's local read never waits on a write. [`Self::with_file_in`]    /// opens a closed database through its turn and the writer's full open, and    /// a catch-up holds that turn and the writer across every fold batch: on 13    /// Oct 2026 the phone's Devices page (build 269) ran out its six seconds    /// behind the catch-up's folds and blamed the Mac, which it never asked.    /// A closed file read here has not been laddered by this build — a read    /// that does not fit it fails, and the caller leaves that database out.    #[track_caller]    pub fn glance_in<T>(        &self,        database: &str,        work: impl FnOnce(&Driver, &str) -> Result<T, String>,    ) -> Result<T, String> {        if self.placing.load(std::sync::atomic::Ordering::SeqCst) {            return Err(NOT_ARRIVED.into());        }        if self.removed_from(database).is_some() {            let _ = self.let_go_of(database);            return Err(not_held(database));        }        let readers = {            let state = self.state.lock().map_err(|_| locked())?;            state                .as_ref()                .filter(|attached| attached.workspace_id == database)                .map(|attached| Arc::clone(&attached.readers))        };        let readers = match readers {            Some(readers) => Some(readers),            None => self.others.lock().map_err(|_| locked())?.get(database).map(|open| open.readers),        };        let run = |driver: &Driver| {            let mut answer = None;            let mut work = Some(work);            driver                .transaction(|_| {                    if let Some(work) = work.take() {                        answer = Some(work(driver, database));                    }                    Ok(())                })                .map_err(|error| error.to_string())?;            answer.expect("the read transaction ran the work exactly once")        };        if let Some(readers) = readers {            let reader = take_reader(&readers).map_err(read_not_open)?;            return run(&reader.driver);        }        if !held_ids(&self.layout)?.iter().any(|held| held == database) {            return Err(not_held(database));        }        if let Some(arriving) = self.arriving(database) {            return Err(arriving);        }        let path = self.layout.replica(database);        if !path.is_file() {            return Err(NOT_ARRIVED.into());        }        let driver = Driver::open_reader(&path).map_err(read_not_open)?;        run(&driver)    }    /// [`Self::with_writer`] on a NAMED database.    pub fn with_writer_in<T>(        &self,        database: &str,        work: impl FnOnce(&ReadFile<'_>) -> Result<T, String>,    ) -> Result<T, String> {        let open = self.open_database(database)?;        let replica = open.replica.lock().map_err(|_| locked())?;        work(&ReadFile::of(&replica))    }    /// Put the pull schedule on the runtime, if this build has both a runtime    /// and a way to reach the server.    ///    /// Called from [`Self::attach`] with the state lock ALREADY RELEASED: the    /// loop's own first pass takes the replica, and starting it from inside the    /// lock that pass needs is the deadlock this ordering avoids.    /// THE MOVES, after Home and never before it, first of all the    /// background work, with a Mac or without one (passivemove rules 1 and    /// 3): the open database's computed index (the open does not rebuild    /// it; its schema move the open finished, before its kit was kept), then    /// every other held database's move. Each step says which tables it    /// moved (`MOVES_DONE_ORIGIN`), and every read it stalled reads again by    /// itself.    /// Every note this phone keeps about `database` beside its copy — the    /// pass's cursors (`held.json`) and Home's sync line (`home-lines.json`)    /// — forgotten: the account was deleted (`account.forget`).    pub fn forget_notes(&self, database: &str) {        self.home_lines.forget(database);        let _ = cotton_client::connection::held::HeldNotes::beside(&self.layout.connection_json()).forget(database);    }    /// The background moves [`Self::start_moves`] began, waited for: a copy    /// about to be deleted for good (`account.forget`) is let go of by every    /// thread before its folder goes, or the thread opens it again.    pub fn finish_moves(&self) {        let running = self.index_move.lock().ok().and_then(|mut held| held.take());        if let Some(running) = running {            let _ = running.join();        }    }    fn start_moves(&self, workspace_id: &str, replica: &Arc<Mutex<Replica>>) {        let Ok(mut held) = self.index_move.lock() else {            return;        };        if held.as_ref().is_some_and(|running| !running.is_finished()) {            return;        }        let indexed = Arc::clone(replica);        let events = Arc::clone(&self.events);        let own = workspace_id.to_string();        let layout = self.layout.clone();        let clock = Arc::clone(&self.clock);        let random = Arc::clone(&self.random);        let judge = Arc::clone(&self.judge) as Arc<dyn cotton_store::judge::JudgeSource>;        let others = Arc::clone(&self.others);        let opens = Arc::clone(&self.other_opens);        let feeds = Arc::clone(&self.feeds);        let receipt_signer = self.receipt_signer.clone();        let moving = std::thread::Builder::new().name("cotton-index".to_string()).spawn(move || {            // Every other copy another build stamped is counted from the            // start, so Me says how many databases there are to move in all.            // Only those are opened for their move: the sync pass opens every            // one in its turn anyway.            // A served database's copy never moves (29 Oct 2026), so a            // served device counts none.            let served = mine_is_served(&layout);            let stale: Vec<String> = household_ids(&layout).into_iter()                .filter(|id| *id != own && !served)                .filter(|id| cotton_client::unsent::stamped_by_another_build(&layout.replica(id)).is_some())                .collect();            for other in &stale {                cotton_client::moves::expect(other);            }            if let Err(error) = bring_moves_done(&own, &indexed, &events) {                tracing::warn!(workspace_id = %own, %error, "computed index not rebuilt; the next fold rebuilds it");            }            for other in stale {                let judge = cotton_client::ReplicaJudge { judge: Arc::clone(&judge), random: Arc::clone(&random) };                match open_other(&layout, clock.as_ref(), random.as_ref(), judge, receipt_signer.clone(), &others, &opens, &feeds, Arc::clone(&events), &other) {                    Ok(file) => bring_move_on(&layout, &other, &file.replica, &events),                    Err(error) => {                        cotton_client::moves::give_up(&other);                        tracing::warn!(database = %other, %error, "a held database's move waits for its next open");                    }                }            }        });        if let Ok(moving) = moving {            *held = Some(moving);        }    }    fn start_sync_loop(&self, workspace_id: &str, replica: &Arc<Mutex<Replica>>) {        let Ok(mut held) = self.sync_loop.lock() else {            return;        };        if held.is_some() {            return;        }        let Some(runtime) = self.runtime.lock().ok().and_then(|slot| slot.clone()) else {            return;        };        let Some(source) = self.transport.lock().ok().and_then(|slot| slot.clone()) else {            return;        };        let events = Arc::clone(&self.events);        let last_pull_at = Arc::clone(&self.last_pull_at);        let pulled_for = Arc::clone(&self.pulled_for);        let caught_up_for = Arc::clone(&self.caught_up_for);        let caught_up_once_for = Arc::clone(&self.caught_up_once_for);        let generation = self.detaches.load(std::sync::atomic::Ordering::SeqCst);        let tables_events = Arc::clone(&self.events);        let pushed_events = Arc::clone(&self.events);        let sent_workspace = workspace_id.to_string();        let workspace = workspace_id.to_string();        let own = workspace_id.to_string();        let call_tables = self.after_tables.lock().unwrap_or_else(|error|error.into_inner()).clone();        let own_call_tables = call_tables.clone();        let own_index_path = replica.lock().map(|replica| replica.path.clone()).unwrap_or_else(|poisoned| poisoned.into_inner().path.clone());        // When a pass last reached the server, kept beside the copy so a launch says "Synced at 9:53 am" from its        // first frame rather than nothing until the first pass (SYNC SEEN, 26 Nov 2026). Only the time comes back;        // whether this run has pulled (`pulled_for`) is this run's own.        let kept_pull = last_pull_file(&own_index_path);        if let Ok(mut slot) = last_pull_at.lock() {            if slot.is_none() {                *slot = read_last_pull(&kept_pull);            }        }        let held_files = {            let layout = self.layout.clone();            let ids_layout = self.layout.clone();            let clock = Arc::clone(&self.clock);            let random = Arc::clone(&self.random);            let judge = Arc::clone(&self.judge) as Arc<dyn cotton_store::judge::JudgeSource>;            let others = Arc::clone(&self.others);            let receipt_signer = self.receipt_signer.clone();            let opens = Arc::clone(&self.other_opens);            let open_now = Arc::clone(&self.others);            let closing = Arc::clone(&self.others);            let feeds = Arc::clone(&self.feeds);            let closing_feeds = Arc::clone(&self.feeds);            let closing_layout = self.layout.clone();            let held_events = Arc::clone(&self.events);            let opened_events = Arc::clone(&self.events);            let sent_events = Arc::clone(&self.events);            let pass_events = Arc::clone(&self.events);            let pass_lines = self.home_lines.clone();            let pass_clock = Arc::clone(&self.clock);            let index_layout = self.layout.clone();            let index_events = Arc::clone(&self.events);            cotton_client::sync::HeldFiles {                ids: Arc::new(move || household_ids(&ids_layout)),                open: Arc::new(move |database| {                    let judge = cotton_client::ReplicaJudge {                        judge: Arc::clone(&judge),                        random: Arc::clone(&random),                    };                    open_other(                        &layout,                        clock.as_ref(),                        random.as_ref(),                        judge,                        receipt_signer.clone(),                        &others,                        &opens,                        &feeds,                        Arc::clone(&opened_events),                        database,                    )                    .map(|open| open.replica)                }),                open_now: Arc::new(move |database| {                    open_now                        .lock()                        .is_ok_and(|others| others.open_ids().iter().any(|id| id == database))                }),                notes: HeldNotes::beside(&self.layout.connection_json()),                // An idle database costs no handle: what the pass opened in                // turn is closed again, the shown ones excepted.                after_pass: Some(Arc::new(move || {                    if let Ok(mut others) = closing.lock() {                        let closed = others.close_idle(OpenFile::idle);                        close_handles(&closing_layout, &closing_feeds, closed);                    }                })),                on_tables: Some(Arc::new(move |database, tables| {                    if let Some(hook) = &call_tables { hook(database, tables); }                    let payload = json!({                        "workspaceId": database,                        "tables": tables,                        "origin": "pull",                    });                    held_events.emit(EventKind::Data, payload);                    rebuild_index_beside(database, index_layout.replica(database), Arc::clone(&index_events));                })),                // What a pass handed over: a screen reading the outbox (a                // report's "Waiting to sync") reads it again.                on_sent: Some(Arc::new(move |database, tables| {                    let payload = json!({                        "workspaceId": database,                        "tables": tables,                        "origin": "push",                    });                    sent_events.emit(EventKind::Data, payload);                })),                // WHAT EACH DATABASE'S SECTION OF A PASS REPORTED: the only                // thing the Databases sheet says sync by.                on_report: Some(Arc::new(move |report| {                    let standing = pass_lines.heard(                        report.database,                        report.reported,                        report.schema,                        report.moved,                        report.answered,                        pass_clock.now().timestamp_millis(),                    );                    pass_events.emit(                        EventKind::Client,                        database_sync_frame(report.database, report.reported, &standing),                    );                })),            }        };        let after_pull = self            .after_pull            .lock()            .unwrap_or_else(|error| error.into_inner())            .clone();        let after_pass = self            .after_pass            .lock()            .unwrap_or_else(|error| error.into_inner())            .clone();        let own_line = workspace_id.to_string();        let (heal_progress, heals) = (Arc::clone(&self.sync_progress), self.heals());        let mut running =            cotton_client::sync::task::SyncLoop::new(cotton_client::sync::task::SyncLoopInput {                replica: Arc::clone(replica),                workspace_id: workspace_id.to_string(),                transport: source,                clock: Arc::clone(&self.clock),                random: Arc::clone(&self.random),                interval_ms: None,                on_status: Some(Arc::new(move |status| {                    // "Last checked" is the LOOP's now, not the caller's: a                    // pass the timer ran is exactly the one a banner reading                    // "just now" is about.                    // The device's own line only: another held database's                    // line is told on the same stream under its own id.                    if status.database == own {                        // Caught up only on the status of a pass that ended so: a pass starting, failing or stalling                        // says otherwise, and clears it (review of SITES ROWS 2: a copy made again in the running                        // app must never read as caught up from an earlier pass).                        let caught = status.caught_up && status.last_pull_at.is_some();                        // A late word from a copy's earlier generation never touches a newer one's.                        let newer = |held: &Option<(String, u64)>| held.as_ref().is_some_and(|(_, g)| *g > generation);                        if let Ok(mut slot) = caught_up_for.lock() {                            if !newer(&slot) {                                *slot = caught.then(|| (own.clone(), generation));                            }                        }                        if caught {                            if let Ok(mut slot) = caught_up_once_for.lock() {                                if !newer(&slot) {                                    *slot = Some((own.clone(), generation));                                }                            }                        }                        if let Some(at) = &status.last_pull_at {                            if let Ok(mut slot) = last_pull_at.lock() {                                if slot.as_deref() != Some(at.as_str()) {                                    keep_last_pull(&kept_pull, at);                                }                                *slot = Some(at.clone());                            }                            if let Ok(mut slot) = pulled_for.lock() {                                *slot = Some(own.clone());                            }                        }                    }                    events.emit(EventKind::Client, sync_status_event(status));                    // AND WHAT A FINISHED PASS OWES: the device's own line,                    // idle and unrefused, is a pass that ended.                    if status.database == own_line                        && status.state == cotton_client::sync::SyncState::Idle                        && status.last_error.is_none()                    {                        if let Some(hook) = &after_pass {                            hook();                        }                    }                    // A pass that failed: a copy stuck on one page is made                    // again, off this thread.                    if status.database == own_line                        && status.state == cotton_client::sync::SyncState::Waiting                        && status.last_error.is_some()                    {                        heal_if_stuck(&heal_progress, &heals);                    }                })),                on_tables: Some(Arc::new(move |tables| {                    // The placement applier first: a person watching a screen                    // redraw should see the file already written, not written a                    // moment later.                    if let Some(hook) = &after_pull {                        hook(tables);                    }                    // THE SAME `data` EVENT A WRITE CARRIES, now from a pull                    // nobody asked for. Without this a scheduled pull changes                    // the file and no screen redraws until the person happens                    // to navigate.                    if tables.is_empty() {                        return;                    }                    let payload = json!({                        "workspaceId": workspace,                        "tables": tables,                        "origin": "pull",                    });                    if let Some(hook) = &own_call_tables { hook(&workspace, tables); }                    tables_events.emit(EventKind::Data, payload);                    rebuild_index_beside(&workspace, own_index_path.clone(), Arc::clone(&tables_events));                })),                // THE PUSH'S OWN `data` EVENT. A pass that only hands writes                // over folds nothing, so the pull's event above never fires —                // and the Feedback list kept "Waiting to sync" on a report the                // Mac already held until the person switched databases.                on_sent: Some(Arc::new(move |tables| {                    let payload = json!({                        "workspaceId": sent_workspace,                        "tables": tables,                        "origin": "push",                    });                    pushed_events.emit(EventKind::Data, payload);                })),                held: Some(held_files),                time_box: self.time_box.clone(),                on_copy: None,            });        let _entered = runtime.enter();        running.start();        *held = Some(running);        drop(held);        // The captures go up beside the loop, over the same copy.        self.start_media_drain(replica, &runtime);    }    /// Start the drain over `replica` when this device has a way up and none    /// runs yet: on the attached copy, its own timer, woken after every pass.    fn start_media_drain(&self, replica: &Arc<Mutex<Replica>>, runtime: &tokio::runtime::Handle) {        let Some(upload) = self.media_upload.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone() else {            return;        };        let mut held = self.media_drain.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        if held.is_some() {            return;        }        let mut drain = cotton_client::media::MediaDrain::new(cotton_client::media::MediaDrainInput {            replica: Arc::clone(replica),            deps: upload.deps,            clock: Arc::clone(&self.clock),            interval_ms: None,            on_status: upload.on_status,            keep_fetch: None,            evict: None,            unlink: None,            others: None,            held_notes: None,            on_media: None,            watch: Some(Arc::clone(&self.upload_watch)),            after_uploads: upload.after_uploads,        });        let _entered = runtime.enter();        drain.start();        *held = Some(drain);    }    fn stop_media_drain(&self) {        let running = self.media_drain.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take();        if let Some(mut running) = running {            running.stop();        }    }    /// Give this device a way to send its captures UP (`personal.connect`),    /// or take it away. A drain over an earlier way stops; the attached copy's    /// drain starts over this one.    pub fn set_media_upload(&self, upload: Option<MediaUpload>) {        *self.media_upload.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = upload;        self.stop_media_drain();        let runtime = self.runtime.lock().ok().and_then(|slot| slot.clone());        let attached = self.state.lock().ok().and_then(|state| state.as_ref().map(|a| Arc::clone(&a.replica)));        if let (Some(runtime), Some(replica)) = (runtime, attached) {            self.start_media_drain(&replica, &runtime);        }    }    /// Take off this phone every copy of a Photos original the object has    /// confirmed (KEEP 1e): its renditions stay, its row stays with no path.    /// Answers the files and bytes released; nothing when this phone has no    /// device id yet.    pub fn release_photos_copies(&self) -> Result<cotton_client::media::release::Released, String> {        let Some(device) = self.self_device_id() else {            return Ok(Default::default());        };        // Asked over a READ first: a tick with nothing to release never takes the writer.        let due = self.with_file(|f| cotton_client::media::release::releasable(f.driver).map_err(|error| error.to_string()))?;        if due.is_empty() {            return Ok(Default::default());        }        let now = self.clock().now().timestamp_millis();        let mut ids = cotton_client::seams::op_ids(self.random());        let layout = self.layout().clone();        self.with_writer(|f| {            cotton_client::media::release::release_photos_copies(f.driver, f.workspace_id, &device, &layout, &cotton_client::media::SystemEvictDisk, now, &mut ids, crate::phone::storage::held(f))        })    }    /// The uploads in the air on this device (`media.uploads`).    pub fn upload_watch(&self) -> Arc<cotton_client::media::UploadWatch> {        Arc::clone(&self.upload_watch)    }    /// Bring the drain round now: a pass ended, so rows may be due.    pub fn wake_media_drain(&self) {        if let Some(drain) = self.media_drain.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref() {            drain.wake();        }    }    /// Where the drain stands, while one runs.    #[cfg(test)]    pub fn media_drain_status(&self) -> Option<cotton_client::media::MediaDrainStatus> {        self.media_drain.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().map(cotton_client::media::MediaDrain::status)    }    /// Open the replica and build the queue, if this Mac has a workspace.    ///    /// Idempotent, and it re-reads the connection record every time: the person    /// may have joined a server since the last question, and a controller that    /// cached "not connected" would keep saying it.    fn attach(&self) -> Result<(), String> {        if self.state.lock().map_err(|_| locked())?.is_some() {            return Ok(());        }        // ONE OPEN AT A TIME, AND NEVER UNDER THE STATE LOCK. 12 Oct 2026:        // this function held `state` from its first line to its last, so a        // ladder, a write-ahead log replay or a heal on a 732 MB copy held        // every reader of `state` for as long as the open ran — and a        // re-hydrate's detach before its swap, which must let go of the file,        // queued behind an open of that same file. The open now runs under        // its own turn: a second question that needs the file waits for the        // open as before (the boot gate's one status read is the open), while        // `state` is taken for an instant to look and an instant to install.        let turn = self.attaching.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        // The open this one waited behind may have taken.        if self.state.lock().map_err(|_| locked())?.is_some() {            return Ok(());        }        let detaches = self.detaches.load(std::sync::atomic::Ordering::SeqCst);        // A COPY BEING PUT IN PLACE IS NOT OPENED BESIDE ITS CLAIM. 12 Oct        // 2026, the owner's phone: the boot's open met the bootstrap thread's        // claim and ladder on the same file and waited out SQLite's 30 s busy        // timeout, statement after statement, holding this state lock while        // the bootstrap's own attach queued behind it — "Opening your        // database" for minutes. The answer is at once; the card draws the        // copy's own step, and the thread attaches when it is done.        if self.placing.load(std::sync::atomic::Ordering::SeqCst) {            return Err(PLACING_A_COPY.to_string());        }        let stored = read_connection(&self.layout.connection_json())            .map_err(|error| error.to_string())?            .ok_or_else(not_connected_sentence)?;        // A RUNNER KEEPS NO COPY; A READER OPENS ITS OWN, read-only (18 Oct        // 2026: this refused every non-full device with the runner's        // sentence, so a simulator joined as a reader under 139 downloaded        // its copy and drew this refusal on Home). The store refuses a        // reader's every write: `replica.rs` binds the scope on the open.        if cotton_core::device::scope::DeviceScope::parse(stored.device_scope.as_deref()).map_err(str::to_string)?            == cotton_core::device::scope::DeviceScope::Runner {            return Err("this device runs jobs and takes placements; it keeps no database copy".into());        }        let workspace_id = stored            .workspace_id            .clone()            .ok_or_else(not_connected_sentence)?;        // A copy's move into kept-copies a stop interrupted is settled before any copy opens (QUEUE BAD OP 6, LOW).        cotton_client::copy_keep::settle_moves(&self.layout, None);        // THE STEP THE WAIT SCREEN NAMES, decided by the file and not by a        // screen: a write-ahead log left beside the replica means the last run        // stopped before SQLite moved its saved changes into the main file, and        // this open moves them first. Held for exactly as long as the open.        let _opening = OpeningMark::set(            &self.opening,            OpenStep::of(&self.layout.replica(&workspace_id)),        );        #[cfg(test)]        if let Some(hook) = self.during_open.lock().ok().and_then(|slot| slot.clone()) {            hook();        }        // Cloned OUT of the slot before the open, because the closure below        // borrows for the whole call and holding the slot's lock across a        // ladder that can run for minutes would block every `set_` beside it.        let reporter = self            .on_migration            .lock()            .ok()            .and_then(|slot| slot.clone());        let mut report = reporter.map(|reporter| move |event| reporter(event));        // A SERVED DATABASE'S COPY IS NEVER MOVED (29 Oct 2026): another        // build's copy of the object is made again from the object by        // `personal.connect`, its unsent writes sent first; nothing here        // heals, restores or moves it. Only a database this device holds        // alone (Rigby's) moves.        let heal = if stored.mode.has_server() {            refuse_another_builds_copy(&self.layout, &workspace_id)?;            None        } else {            // `cotton_client::dev_heal`: a copy stamped by another build — or            // set aside beside the live name by an earlier build's fallback —            // is moved in place here, before the open, and opened; a copy the            // move cannot take stays where it is and the refusal below says            // why. Nothing here deletes a copy or fetches one.            // THE MOVE REPORTS AS THE LADDER DOES: a phone's copy moves for            // minutes, and with no reporter here the boot page said "Opening            // your database" for all of them and offered Try again and Join            // over a move (build 264, 13 Oct 2026).            // Only the move's first step runs here; the tables it has left            // move after the open, one per transaction, and before the kit            // is kept (below).            let heal = cotton_client::dev_heal::heal_stale_replica_leaving_tables(                &self.layout,                &workspace_id,                cotton_core::flavor::current(),            );            if let Some(refusal) = cotton_client::dev_heal::Heal::stopped(&heal) {                return Err(refusal.to_string());            }            heal        };        let replica = open_replica_with(OpenReplicaInput {            layout: &self.layout,            workspace_id: &workspace_id,            clock: self.clock.as_ref(),            random: self.random.as_ref(),            judge: Some(self.replica_judge()),            // Nothing downloads a snapshot INSIDE this call — a controller            // that fetched half a gigabyte on the way to answering a status            // question would hold the state lock for the length of it. The            // fill is started below, on its own thread.            bootstrap: &mut |_path| Err(NEEDS_SNAPSHOT.to_string()),            // THE LADDER REPORTS FROM HERE. `open_replica`'s thin wrapper — the            // one this call used to be — passes `None`, and a launch with an            // existing file behind this build ran every step of the ladder            // inside this function with nothing able to say so. The bootstrap            // had a screen; an ordinary launch did not, and a schema bump is            // exactly when every returning phone takes this path.            on_migration: report                .as_mut()                .map(|report| report as &mut dyn FnMut(MigrationEvent)),            // Nothing to claim: the four corrections are for a file this call            // just fetched, and this call fetches nothing.            on_bootstrapped: None,            receipt_signer: self.receipt_signer.clone(),        })        .map_err(|error| match error {            ReplicaError::Bootstrap(_) => NEEDS_SNAPSHOT.to_string(),            other => cotton_client::dev_heal::Heal::explain(heal, other.to_string()),        })?;        // THE MOVE FINISHES BEFORE THE KIT IS KEPT (coordinator, 2 Nov 2026):        // open, finish any move the open left, keep, serve. A keep over a        // copy whose tables are still in their old shape reads and writes a        // half-moved schema, so the move is finished here, holding the open,        // and nothing moves this copy after it. Only a database this device        // holds alone moves (a served copy another build wrote is refused        // above and made again from the object), so a move that stops leaves        // a copy no object can make again: it stays as it is, written down        // as not moved, and is served at its stored schema, its kit not kept.        // It opens again at every launch and this attach tries the steps        // left again (coordinator, 3 Nov 2026); the kit is kept once the        // move is whole.        let ready = if replica.moving() {            run_move_steps(&self.layout, &workspace_id, &self.events, &mut || Some(replica.move_step()))        } else {            Ok(())        };        if ready.is_ok() && stored.mode == cotton_client::connection::ConnectionMode::Local {            let tools = cotton_core::genesis::GenesisTools::at(self.layout.root())?;            cotton_tools::kit_keep::keep(&replica.driver, self.clock.now(),                Arc::new(cotton_tools::random::SystemRandom), &tools).map_err(|failure| failure.0)?;            // A kit table no tool carries, laid on a copy made before genesis laid them (Sites' `site`, Post's            // `email_account`); nothing is written when the copy holds them. Only the kit-own tables, and NEVER IN THE            // WAY OF THE OPEN (review of GENESIS KITS, 26 Nov 2026): a kit that does not read, or a lay refused (a copy            // with no identity yet), is written down and the app opens; the next open tries again.            if let Some(note) = lay_kit_tables_at_open(&replica.driver, self.layout.root(), self.clock.now()) {                eprintln!("[kit] {note}");            }            // No object fills this database's engine tables with the columns            // its definitions add (an event's kind), so it takes them here,            // as a copy takes the object's.            let definitions: Vec<serde_json::Value> = replica.driver                .all("SELECT definition FROM cotton_table_definitions", &[])                .map_err(|error| error.to_string())?                .iter()                .map(|row| serde_json::from_str(row.text("definition").unwrap_or_default()).map_err(|error| format!("a table definition does not read ({error})")))                .collect::<Result<_, String>>()?;            cotton_client::transport::object::hold_defined_columns(&replica.driver, &definitions)?;        }        super::diagnostics::opened(&workspace_id, &replica.opened);        // THE READER, opened only now: `open_replica_with` has run the ladder        // and put the file in WAL, so the reader never sees a half-migrated        // file. A reader that will not open is an attach that failed — never        // a quiet fall back onto the writer, which is the wait it removes.        let readers = replica            .open_read_pool()            .map_err(|error| format!("this device's read connection did not open: {error}"))?;        let readers = Arc::new(readers);        let replica = Arc::new(Mutex::new(replica));        let started = (workspace_id.clone(), Arc::clone(&replica));        // A device holding its OWN database has nobody to sync with, and that        // is a state rather than a failure ([`ConnectionMode::Local`]). The        // loop is not started and the drain is not started: both would climb a        // backoff ladder against an address that does not exist, on a battery,        // for ever. `sync_status` names the state `noServerYet` and the phone        // draws "No Mac yet".        let has_server = stored.mode.has_server();        let mut state = self.state.lock().map_err(|_| locked())?;        // LET GO WHILE IT OPENED: the file is being replaced or deleted, and a        // handle installed now would hold the old one. The next question opens        // whatever is there then.        if self.detaches.load(std::sync::atomic::Ordering::SeqCst) != detaches {            drop(state);            drop(turn);            return self.attach();        }        *state = Some(Attached {            connection: stored,            workspace_id,            replica,            readers,        });        // AFTER the lock, not inside it: the loop's first pass takes the        // replica and the state lock is what it would be waiting on.        drop(state);        self.recover_kept_at_open();        self.start_moves(&started.0, &started.1);        if has_server {            self.start_sync_loop(&started.0, &started.1);        }        Ok(())    }    /// QUEUE BAD OP 5: what the kept copies of this database hold (and a carried file beside its copy) is tried each    /// time the copy opens — at launch and after an app update — not only inside a pass; what does not read waits,    /// listed, and nothing here removes it.    fn recover_kept_at_open(&self) {        let Ok((database, _)) = self.attached_replica() else { return };        let layout = self.layout.clone();        let live = layout.replica(&database);        // KEPT FOUR 3 B: a local copy an older build founded a vault in holds the only wrap of its key: into its own        // file now, before anything could remove the copy.        if !self.signed_in() {            if let Err(error) = cotton_client::vault_keep::secure(&layout, &database, &[live.clone()], None) {                eprintln!("[vault] the local vault key could not be kept in its own file yet ({error})");            }        }        if !cotton_client::transport::object::carried_path(&live).exists() && !cotton_client::copy_keep::kept_dir(&layout, &database).exists() {            return;        }        let wall_ms = chrono::Utc::now().timestamp_millis();        let mut ids = cotton_client::seams::op_ids(Arc::new(cotton_client::seams::SystemRandom));        match self.with_writer(|file| cotton_client::copy_keep::recover(&layout, file.workspace_id, file.driver, &live, wall_ms, &mut ids)) {            Ok(recovery) if recovery.sent > 0 || recovery.kept_copies_gone > 0 => {                eprintln!("[copy-keep] at open: {} kept change(s) sent at their own time, {} still kept, {} kept copy(ies) let go", recovery.sent, recovery.still_kept, recovery.kept_copies_gone);            }            Ok(_) => {}            Err(error) => eprintln!("[copy-keep] at open, the kept changes wait for the next pass ({error})"),        }    }    /// The instant this device reads by — the controller's OWN clock seam.    ///    /// A read that bands by time (Home's queue, the mood strip) takes its    /// instant from here rather than calling `Utc::now()` inside itself. The    /// seam is the thing a test replaces, and a wall clock read inside a read    /// is a test with a computable detonation date — the failure this repo has    /// already paid for once.    /// A fresh name off the random seam — a scratch folder an import inflates    /// into, so a test's is fixed too.    pub fn scratch_name(&self) -> String {        cotton_client::seams::uuid_v4(self.random.as_ref())    }    pub fn now_iso(&self) -> String {        self.clock.now_iso()    }    /// The same instant, typed — what the vault's TTL is measured against.    ///    /// The SAME seam `now_iso` reads, so a suite that fixes one has fixed both:    /// a five-minute unlock compared against a wall clock inside a function    /// would be a test with a computable detonation date.    pub fn now(&self) -> chrono::DateTime<chrono::Utc> {        self.clock.now()    }    /// The vault session as THIS CALL's database sees it — locked until    /// something unlocks that database. The database is the one the call    /// named ([`NAMED`]), else the device's own; a key unlocked for one    /// database is never lent to a call on another.    pub fn vault(&self) -> Result<crate::phone::vault::VaultDoor, String> {        Ok(self.vault.of(&self.current_database()?))    }    /// The unlock card's held Allow (`phone::unlock::HeldAllow`).    pub(crate) fn unlock_held(&self) -> std::sync::MutexGuard<'_, Option<crate::phone::unlock::HeldAllow>> {        self.unlock_held.lock().unwrap_or_else(|error| error.into_inner())    }    /// The whole session, for the one act that is about every database:    /// locking.    pub fn vault_session(&self) -> &Arc<crate::phone::vault::VaultSession> {        &self.vault    }    /// The id of the database this call is answered from — the file    /// [`Self::attached_replica`] hands a write, by its own id.    pub fn current_database(&self) -> Result<String, String> {        self.attach()?;        Ok(self.attached_replica()?.0)    }    /// Install the existing device signing capability at open.    pub fn set_tool_signer(&self, signer: Option<cotton_tools::mcp::dispatch::ToolSigner>) {        if let Ok(mut slot) = self.tool_signer.lock() {            *slot = signer;        }    }    /// Hand every replica of this process the device key its receipts are    /// signed with — at open, once.    pub fn set_receipt_signer(&self, signer: Arc<dyn cotton_store::signed::ReceiptSigner>) {        self.receipt_signer.fill(signer);    }    /// The slot every replica of this process signs from, for a path that    /// opens one before this controller does — a bootstrap's claim, a join,    /// a database started on this device (keys slice KS1).    pub fn receipt_signer_slot(&self) -> cotton_store::signed::SignerSlot {        self.receipt_signer.clone()    }    fn tool_signer(&self) -> Option<cotton_tools::mcp::dispatch::ToolSigner> {        self.tool_signer.lock().ok().and_then(|slot| slot.clone())    }    /// This Mac's vault key, for the two unattended callers that may have it:    /// the placement applier and the Dashlane import.    ///    /// It is COPIED out rather than borrowed so the lock is not held across the    /// work, and every caller drops it at the end of its own statement.    pub fn vault_key(&self) -> Option<[u8; 32]> {        *self            .vault_key            .lock()            .unwrap_or_else(|error| error.into_inner())    }    /// Whether `database`'s file already holds this device's vault public    /// half. See the field.    pub fn vault_key_published(&self, database: &str) -> bool {        self.vault_published            .lock()            .unwrap_or_else(|error| error.into_inner())            .1            .contains(database)    }    /// Remember that the publish landed in `database`, so the next pass does    /// not open a write transaction there for a row nobody touched.    pub fn set_vault_key_published(&self, database: &str) {        self.vault_published            .lock()            .unwrap_or_else(|error| error.into_inner())            .1            .insert(database.to_string());    }    /// This device's vault public half, once something has said it.    pub fn vault_public(&self) -> Option<String> {        self.vault_published            .lock()            .unwrap_or_else(|error| error.into_inner())            .0            .clone()    }    /// Keep this device's vault public half. A DIFFERENT one forgets every    /// database the old one landed in: each is owed the new key.    pub fn set_vault_public(&self, public: &str) {        let mut held = self            .vault_published            .lock()            .unwrap_or_else(|error| error.into_inner());        if held.0.as_deref() != Some(public) {            *held = (Some(public.to_string()), std::collections::BTreeSet::new());        }    }    /// What to run after each pass of the loop that ended idle. The handle    /// installs it once.    /// The hook a finished pass calls, called as a pass would (tests of what runs after a pass).    #[cfg(test)]    pub(crate) fn fire_after_pass_for_test(&self) {        let hook = self.after_pass.lock().unwrap_or_else(|error| error.into_inner()).clone();        if let Some(hook) = hook {            hook();        }    }    pub fn set_after_pass(&self, hook: Arc<dyn Fn() + Send + Sync>) {        *self.after_pass.lock().unwrap_or_else(|error| error.into_inner()) = Some(hook);    }    /// The device's own IANA zone, or nothing.    ///    /// Nothing is a real answer and never UTC: see the field.    pub fn time_zone(&self) -> Option<&str> {        self.time_zone.as_deref()    }    /// The pull schedule, when one is running.    fn scheduled(&self) -> Option<()> {        self.sync_loop            .lock()            .ok()            .and_then(|held| if held.is_some() { Some(()) } else { None })    }    /// A write just queued an op: ask the loop to come back now.    ///    /// `SyncLoop::wake`, not `wake_and_reset` and not `push_now`. Not    /// `push_now`, because that is a future that needs a runtime handle on    /// this thread, and a whole cycle costs the same round trip as a push    /// (one exchange carries both directions) while also bringing news down.    /// Not the reset, because a write is not a person saying the conditions    /// changed. **And the wake itself defers during a backoff** — `wake`'s    /// own rule: while `failures > 0` it is a no-op, because a pass it started    /// would fail the same way and climb the ladder, so ten edits on a train    /// would put the loop at its five-minute ceiling for a Mac that comes    /// back a minute later. The op is in the outbox and the attempt already    /// scheduled carries it; the foreground and "sync now" are what put the    /// ladder back on its bottom rung. While healthy, the `Notify` permit    /// coalesces: a hundred writes during one pass are one extra pass.    ///    /// A no-op with no schedule running — a controller with no runtime or no    /// transport — and honest about it: the op is in the outbox, `sync.now`    /// and the next attach both carry it.    pub(crate) fn wake_sync_loop(&self) {        // A write in ANOTHER held database: its note stops speaking for it,        // so the pass this wake starts opens the file and hands the write        // over even if the file has been closed by then. The device's own        // file is always open and answers for itself.        if let Some(database) = named_database() {            if !self.is_own(&database).unwrap_or(true) {                if let Err(error) =                    HeldNotes::beside(&self.layout.connection_json()).note_write(&database)                {                    eprintln!("[cotton-sync] the held note was not marked: {error}");                }            }        }        if let Ok(held) = self.sync_loop.lock() {            if let Some(running) = held.as_ref() {                running.wake();            }        }    }    /// Ask the running schedule for a pass now — something outside a write    /// changed what the next pass has to do. `None` with no schedule running,    /// else whether it was asked (`false` while it waits out a failure: the    /// pass already scheduled carries it, `SyncLoop::wake`).    pub fn nudge_sync(&self) -> Option<bool> {        let held = self.sync_loop.lock().ok()?;        held.as_ref().map(|running| running.wake())    }    /// Come back now, from the bottom of the ladder — the app reached the    /// front.    ///    /// A no-op with no schedule running, which is honest: there is no ladder to    /// put back on its bottom rung.    pub fn sync_wake_and_reset(&self) -> bool {        // The app is in front: no slice's limit outlives that, loop or none.        self.time_box.lift();        match self.sync_loop.lock() {            Ok(held) => match held.as_ref() {                Some(running) => {                    running.wake_and_reset();                    true                }                None => false,            },            Err(_) => false,        }    }    /// The app went to the back, with `left` of its background time. The    /// TIMER STAYS — see `SyncLoop::background`.    pub fn sync_background(&self, left: Option<std::time::Duration>) -> bool {        match self.sync_loop.lock() {            Ok(held) => match held.as_ref() {                Some(running) => {                    running.background(left);                    true                }                None => false,            },            Err(_) => false,        }    }    /// Whether pairing can reach a server. This is a connection fact, not a    /// sync report: callers need no outbox, media or search-index counts.    pub fn has_server(&self) -> Result<bool, String> {        self.attach()?;        Ok(self.no_server_yet().is_none())    }    /// Local observations only: no attach, request, or state-machine wake.    pub(crate) fn database_sync_facts(&self, database: &str) -> (        cotton_client::sync::line::CopyFacts,        Option<cotton_client::sync::SyncStatus>,    ) {        // ONE FACT PER MAC (295 rule 16): the serving Mac's contact is read        // from the lines of every database at its origin, so each database's        // Me and Copies say the same Mac the same way. Asked before the lines        // are taken: the record is a file read.        let peers = mac_peers(&self.layout, database);        let lines = self.home_lines.lines.lock().unwrap_or_else(|e| e.into_inner());        let mut facts = lines.get(database).map(cotton_client::sync::line::HomeLine::facts).unwrap_or_default();        let (answered, silent) = cotton_client::sync::line::mac_contact(peers.iter().filter_map(|id| lines.get(id)));        if answered.is_some() || silent.is_some() {            (facts.mac_answered_at, facts.mac_silent_since) = (answered, silent);        }        drop(lines);        let status = self.sync_loop.lock().unwrap_or_else(|e| e.into_inner()).as_ref()            .map(cotton_client::sync::SyncLoop::status)            .filter(|status| status.database == database);        (facts, status)    }    pub fn sync_status(&self) -> Value {        self.sync_status_of(false)    }    /// [`Self::sync_status`], with each table's rows and newest receipt in    /// its `status` when `detail` — the detail page's ask, never the    /// banner's, which is read after every `data` event.    pub fn sync_status_of(&self, detail: bool) -> Value {        let mut answer = self.sync_status_bare(detail);        // THE ONE QUIET LINE every app's home draws about its sync (SYNC SEEN,        // owner 25 Nov 2026), the same `seen` `shell.home` carries: decided        // once, from this status, by `shell_account::seen_with`.        answer["seen"] = crate::methods::shell_account::seen_with(self, &answer);        answer    }    /// [`Self::sync_status_of`] without its `seen`: what `seen` is decided from.    pub(crate) fn sync_status_bare(&self, detail: bool) -> Value {        match self.attach() {            Err(reason) => not_connected(&reason),            Ok(()) => {                // `state` is copied out of and let go BEFORE the file is read:                // the counts below run on the read connection, and nothing                // here holds the coarse lock or the writer while they do.                let (workspace_id, mode, base_url, readers) = {                    let state = self.state.lock().expect("the client state");                    let Some(attached) = state.as_ref() else {                        return not_connected(&not_connected_sentence());                    };                    (                        attached.workspace_id.clone(),                        attached.connection.mode,                        attached.connection.base_url.clone(),                        Arc::clone(&attached.readers),                    )                };                let this_device = self.self_device_id();                let (held, pending, held_writes, media, search_index, file_facts) = {                    let reader = match take_reader(&readers) {                        Ok(reader) => reader,                        Err(error) => return not_connected(&read_not_open(error)),                    };                    let file = ReadFile::of_reader(&reader);                    // One read transaction, so the outbox count and the media                    // ledger are the same snapshot.                    let read = reader.driver.transaction(|_| {                        Ok((                            file.held.as_str(),                            current_pending(file.driver),                            current_held(file.driver),                            media_activity(&file),                            search_index_fill(file.driver),                            super::sync_status::file_facts(&file, this_device.as_deref(), detail),                        ))                    });                    match read {                        Ok(read) => read,                        Err(error) => {                            return not_connected(&format!(                                "this device's copy could not be read: {error}"                            ))                        }                    }                };                // The one word the banner, the settings row and the boot                // gate all read. `noServerYet` is a device holding its own                // database with no Mac in it yet — not an error, not a                // failure, and never a retry.                let has_server = mode.has_server();                let now_ms = self.clock.now().timestamp_millis();                let standing = self.home_lines.of(&workspace_id, now_ms);                let lines = self.home_lines.all(now_ms);                let status = self.sync_status_said(&workspace_id, !has_server, pending, file_facts, now_ms);                json!({                    // WHERE THIS DEVICE'S SYNC STANDS, as one read                    // (`cotton_core::rules::sync_status`): role, the                    // serving Mac, last contact, receipts both ways, bytes                    // both ways, what came since open by tool, and the one                    // line in the shell's words.                    "status": status,                    "connected": true,                    "workspaceId": workspace_id,                    "mode": mode,                    "state": if has_server { SYNCING_STATE } else { NO_SERVER_YET },                    // `null` rather than the empty string a local connection                    // holds: a screen draws an address or it does not.                    "baseUrl": if has_server {                        Value::from(base_url)                    } else {                        Value::Null                    },                    "held": held,                    // Unsent changes: the outbox and, of them, the writes                    // held for the Mac's time (`heldWrites`), which go once                    // an answer gives it.                    "pending": pending,                    "heldWrites": held_writes,                    // The `_media` ledger — this DEVICE's, never the                    // workspace's — because "Sync & backup" draws two cards and                    // the second one is bytes. Extended here rather than added                    // as a second read (4h): `SyncModel` already derives the                    // live banner from this one answer, and two reads would be                    // two chances to disagree about one banner.                    "media": media,                    // No keep-fetch reading here: this answer is read after                    // every `data` event, and the phone's keep queue is a scan                    // of the whole file — on a standby Mac's copy of the                    // owner's database it outlasted the event rate, 64 reads                    // queued on four connections and the app could not quit                    // (standbyhang, 12 Oct 2026). `read.keepFetch` answers it                    // when the Keeps screen asks.                    "searchIndex": search_index,                    // Absent before the first pass that reached the server —                    // never a zero, which a banner would read as 1970.                    "lastPullAt": self                        .last_pull_at                        .lock()                        .ok()                        .and_then(|held| held.clone()),                    // Said out loud rather than implied by a zero: see                    // NO_TRANSPORT. FALSE on a local connection whatever the                    // transport slot holds — there is no server to reach.                    "canReachServer": has_server                        && self                            .transport                            .lock()                            .expect("the transport slot")                            .is_some(),                    // WHAT THE LOOP IS DOING, for a reader that was not                    // listening when it last said so: the same object the                    // `client` stream carries as `phase: "sync"`, with its                    // state word, the last failure's sentence and when it                    // will try again. `null` while no loop runs — a local                    // database, or a controller that has not attached one                    // yet — and a screen reads that as "nothing in flight",                    // never as "reachable".                    "loop": self                        .loop_status()                        .and_then(|status| serde_json::to_value(status).ok())                        .unwrap_or(Value::Null),                    // WHERE SYNC STANDS, in the engine's words                    // (`cotton_client::sync::line`), for this database and                    // for every database a pass has reported on: `line` is                    // what goes under a cap (empty is the people line) and                    // `sync` the whole standing — state, the page's                    // sentence, percent, what is left.                    "line": standing.words,                    "sync": standing,                    "lines": lines.0,                    "syncs": lines.1,                })            }        }    }    /// The core's [`cotton_core::rules::sync_status::Status`] for    /// `database`, from what the passes keep and what its file said.    /// `local` is a connection with no server: the database lives here alone.    fn sync_status_said(        &self,        database: &str,        local: bool,        pending: Option<i64>,        file: super::sync_status::FileFacts,        now_ms: i64,    ) -> cotton_core::rules::sync_status::Status {        use cotton_core::rules::sync_status::{Bytes, Contact, Facts, Pile, Receipts, Status};        let (facts, _) = self.database_sync_facts(database);        let (applied_at, received) = {            let lines = self.home_lines.lines.lock().unwrap_or_else(|e| e.into_inner());            lines.get(database).map(|line| (line.applied_at(), line.since_open().clone())).unwrap_or_default()        };        // `pending` is the one count of the queue (`current_pending`): the        // outbox and the writes held for the Mac's time, which it already        // holds — the same number the header's changes waiting reads.        let to_send = pending.and_then(|n| u64::try_from(n).ok()).unwrap_or(0);        // No keep-fetch sweep asks a Mac for originals.        let to_fetch = Pile::default();        // THE OTHER END IS COTTON'S SERVER, not a Mac, for a copy of the        // person's object: one `personal.connect` made (it marks every copy),        // or the one this launch connected to its object. Its line names no        // Mac (a phone said "Up to date with your Mac", 22 Nov 2026).        let with_cotton = !local            && (crate::phone::copy_aside::is_objects_copy(&self.layout.replica(database))                || (self.object_door().is_some()                    && read_connection(&self.layout.connection_json()).ok().flatten().and_then(|own| own.workspace_id).as_deref() == Some(database)));        let facts = Facts {            role: file.role,            // An app that never syncs holds its databases here alone,            // whatever an earlier connection left behind.            alone: local || file.serving_here || !self.syncs(),            here: Some(crate::phone::commands::THIS_BUILDS_PLATFORM),            serving: file.serving,            with_cotton,            contact: Contact { answered_at: facts.mac_answered_at, silent_since: facts.mac_silent_since },            receipts: Receipts {                behind: facts.remaining,                at_least: facts.remaining.is_some_and(|n| n >= cotton_client::sync::line::COUNTED_UP_TO),                to_send,                last_applied_at: applied_at,            },            bytes: Bytes { to_fetch, to_send: file.to_send },        };                Status::of(            facts,            &received,            cotton_core::rules::home_arrangement::tool_of_store_table,            file.tables,            &file.words,            now_ms,        )    }    /// WHAT THIS DEVICE SAYS OF ITSELF with every exchange    /// (`cotton_core::device::reported_state`): what the app said    /// (`diagnostics.say`), this build's schema, the loop's last answer and    /// when, what is unsent, and a copy in progress. Asked from inside a pass    /// as its body is built, so it never waits on a lock: a slot that is busy    /// says nothing this time.    pub fn device_state(&self) -> Option<Value> {        let said = super::diagnostics::said();        let status = self            .sync_loop            .try_lock()            .ok()            .and_then(|held| held.as_ref().map(cotton_client::sync::task::SyncLoop::status));        // The attached file's database — or, with no file open (a first copy,        // a stopped open), the one this device's own copy is of.        let workspace = self            .state            .try_lock()            .ok()            .and_then(|state| state.as_ref().map(|attached| attached.workspace_id.clone()))            .or_else(|| read_connection(&self.layout.connection_json()).ok().flatten().and_then(|stored| stored.workspace_id));        let copy = workspace            .and_then(|workspace| {                let standing = self.home_lines.of(&workspace, self.clock.now().timestamp_millis());                (standing.state == cotton_client::sync::line::State::Copying).then_some(standing.words)            })            .or_else(|| self.copy_note.lock().unwrap_or_else(|error| error.into_inner()).clone());        let pass = self.sync_progress().map(|progress| progress.state());        let waiting = self.with_file(|file| cotton_store::outbox::waiting(file.driver).map_err(|error| error.to_string())).ok();        // The loop's last answer; before this launch's first, the pass that last reached the server, kept beside the        // copy (SYNC SEEN), which was an "ok" — never nothing (REPORT FIELDS, 26 Nov 2026).        let (last_exchange_at, last_answer) = last_heard(            status.as_ref().map(|status| &status.peer),            || self.last_pull_at.try_lock().ok().and_then(|held| held.clone()),        );        let state = cotton_core::device::reported_state::ReportedState {            repositories: super::database_files::repositories(&self.layout),            build: said.build,            bundle_id: said.bundle_id,            databases: super::database_files::states(&self.layout),            sha: said.sha,            schema: Some(cotton_store::schema::ddl::SCHEMA_VERSION),            last_exchange_at,            last_answer,            // UNSENT SEEN (26 Nov 2026): the things waiting, each record once, with the raw writes beside them, and            // what waits by table and by refusal code, in names and counts only (`cotton_store::outbox::waiting`).            unsent: match (&waiting, &status) {                (Some(waiting), status) => u64::try_from(waiting.things + status.as_ref().map_or(0, |status| status.held)).ok(),                (None, Some(status)) => u64::try_from(status.pending).ok(),                (None, None) => None,            },            unsent_ops: waiting.as_ref().and_then(|waiting| u64::try_from(waiting.ops + status.as_ref().map_or(0, |status| status.held)).ok()),            waiting_by_table: waiting.as_ref().map(|waiting| counts_of(&waiting.by_table)).unwrap_or_default(),            waiting_by_code: waiting.as_ref().map(|waiting| counts_of(&waiting.by_code)).unwrap_or_default(),            oldest_waiting_at: waiting.as_ref().and_then(|waiting| waiting.oldest_at.clone()),            oldest_seal_waiting_at: waiting.as_ref().and_then(oldest_seal_waiting_at),            pass_done: pass.as_ref().filter(|pass| !pass.caught_up).and_then(|pass| pass.done).and_then(|n| u64::try_from(n).ok()),            pass_total: pass.as_ref().filter(|pass| !pass.caught_up).and_then(|pass| pass.total).and_then(|n| u64::try_from(n).ok()),            parked: self                // Off the parks' keys, absent while they are not known (FIRST SYNC 8): never a count of every park.                .with_file(|file| cotton_client::seal::parked_count(file.driver.connection()))                .ok()                .flatten(),            held: status.as_ref().and_then(|status| u64::try_from(status.held).ok()).filter(|held| *held > 0),            databases_listed: said.databases_listed,            open_problem: said.open_problem,            copy,            usage: said.usage,            sites: said.sites,            albums: said.albums,        };        Some(state.cleaned().to_value())    }    /// The own copy moved (`bytes`), stopped (`failed`) or is over (neither):    /// the cap's line says it.    fn copy_moved(&self, database: &str, bytes: Option<(u64, Option<u64>)>, failed: Option<&str>) {        let mut note = self.copy_note.lock().unwrap_or_else(|error| error.into_inner());        match (bytes, failed) {            (_, Some(reason)) => {                let left = self                    .home_lines                    .of(database, self.clock.now().timestamp_millis());                let to_go = (left.state == cotton_client::sync::line::State::Copying).then_some(left.words);                self.say_copying(database, None);                *note = Some(match to_go {                    Some(words) => format!("stalled ({words}): {reason}"),                    None => format!("copy stalled: {reason}"),                });            }            (Some((written, total)), None) => {                self.say_copying(database, total.map(|total| total.saturating_sub(written)));                *note = None;            }            (None, None) => {                self.say_copying(database, None);                // A received whole copy is contact with the serving Mac,                // independently of its older heartbeat and of catching up.                self.home_lines.heard(database, None, None, None, true, self.clock.now().timestamp_millis());                *note = None;            }        }    }    /// The loop's last exchanges, oldest first (the Debug group); empty while    /// no loop runs.    pub fn exchanges(&self) -> Vec<cotton_client::sync::Exchange> {        self.sync_loop            .lock()            .ok()            .and_then(|held| held.as_ref().map(cotton_client::sync::task::SyncLoop::exchanges))            .unwrap_or_default()    }    /// The loop's own status, when one is running.    ///    /// `SyncLoop::status` is a clone under the loop's lock, never a call into    /// a pass — so this is safe to ask from inside a subscriber that is    /// answering the loop's own event.    /// Whether the loop's last pass failed (a 5xx, nothing reached, any    /// refusal) and none has landed since: the loop is on its ladder.    pub fn last_pass_failed(&self) -> bool {        self.loop_status().is_some_and(|status| status.failures > 0) || self.sync_progress().is_some_and(|progress| progress.state().failing)    }    fn loop_status(&self) -> Option<cotton_client::sync::SyncStatus> {        self.sync_loop            .lock()            .ok()?            .as_ref()            .map(cotton_client::sync::task::SyncLoop::status)    }    /// The answer for a device holding its own database and no server, or    /// `None` when there is a server on the other end.    ///    /// ONE reader of the mode, so "is there a server" is asked in one place    /// rather than spelled `!= Remote` in three.    fn no_server_yet(&self) -> Option<Value> {        let state = self.state.lock().ok()?;        let attached = state.as_ref()?;        if attached.connection.mode.has_server() {            return None;        }        Some(json!({            "pushed": 0,            "pulled": 0,            "behind": 0,            "pending": 0,            "lastPullAt": Value::Null,            "state": NO_SERVER_YET,        }))    }    /// Push whatever is queued, now.    pub fn sync_now(&self) -> Result<Value, String> {        let generation = self.detaches.load(std::sync::atomic::Ordering::SeqCst);        self.attach()?;        // A DEVICE WITH NO SERVER ANSWERS THE STATE, NOT AN ERROR. Pull to        // refresh on a phone that has started its own database and not met a        // Mac is a person asking a question whose honest answer is "there is        // nobody to ask yet" — a refusal there would paint a red banner over a        // database that is perfectly well.        if let Some(answer) = self.no_server_yet() {            return Ok(answer);        }        // THROUGH THE SCHEDULE WHEN THERE IS ONE. Two callers asking at once —        // a pull-to-refresh and a poke arriving together — must be one pass and        // then at most one more, which is the coalescing drain's whole job; two        // direct `run_cycle` calls would be two folds racing on one file.        // `pull_now` also climbs and resets the same ladder the timer does, so        // "sync now" and the schedule cannot disagree about how far behind this        // device is.        if self.scheduled().is_some() {            return self.sync_now_scheduled();        }        let source = {            let slot = self.transport.lock().map_err(|_| locked())?;            slot.clone().ok_or_else(|| NO_TRANSPORT.to_string())?        };        let mut transport = source()?;        // THE STATE IS COPIED OUT, NOT HELD. `self.state` is the lock every        // status, write and read asks for first, and a cycle is round trips —        // up to a request ceiling each. Held across them, as it was until        // 2026-09-29, a Mac with no loop running kept every screen waiting on        // the network even though the file itself was lent per page. The        // replica is an `Arc`, so a detach mid-cycle leaves this cycle its        // file and the next caller a fresh attach.        let (workspace_id, replica) = self.attached_replica()?;        // The copy, lent to the transport for the one write it makes of its        // own (`RefusalAware::lend_file`).        transport.lend_file(Arc::clone(&replica) as Arc<dyn cotton_client::sync::cycle::LendsFile + Send + Sync>);        // A WHOLE CYCLE, not a push. "Sync now" is a person asking to be up to        // date, and a push alone answers half of that — it sends what this        // device wrote and brings back nothing anybody else did. The push-only        // pass stays the re-hydrate's drain and the loop's own, where pulling        // on each of 3,421 batches would be 3,421 round trips for news that        // arrives at most once.        //        // THE PAGED CYCLE, which takes the file for each page's fold and never        // for the round trip — the same shape the scheduled loop runs, so a        // screen's read is not queued behind a 60 s HTTP wait here either.        let report = cotton_client::sync::cycle::run_cycle_paged_within(            &replica,            transport.as_mut(),            &workspace_id,            &self.clock.now_iso(),            &self.time_box,        );        // Folded after itself, like every pass the loop runs.        cotton_client::sync::cycle::fold_wal(&*replica, &workspace_id);        if report.is_err() {            self.heal_if_stuck();        }        let report = report.map_err(|failure| cycle_failure_sentence(&failure))?;        let pending = current_pending(&replica.lock().map_err(|_| locked())?.driver);        let at = self.clock.now_iso();        if let Ok(mut held) = self.last_pull_at.lock() {            *held = Some(at.clone());        }        if let Ok(replica) = replica.lock() {            keep_last_pull(&last_pull_file(&replica.path), &at);        }        if let Ok(mut held) = self.pulled_for.lock() {            *held = Some(workspace_id.clone());        }        let caught = !report.behind && report.remaining.is_none_or(|n| n == 0);        let newer = |held: &Option<(String, u64)>| held.as_ref().is_some_and(|(_, g)| *g > generation);        if let Ok(mut held) = self.caught_up_for.lock() {            if !newer(&held) {                *held = caught.then(|| (workspace_id.clone(), generation));            }        }        if caught {            if let Ok(mut held) = self.caught_up_once_for.lock() {                if !newer(&held) {                    *held = Some((workspace_id.clone(), generation));                }            }        }        let answer = json!({            "pushed": report.pushed,            "pulled": report.pulled,            "behind": report.behind,            // What the serving Mac said still waits, over the pass's last            // answers — what the cap counts down from (`null` unsaid).            "behindBy": report.remaining,            "wakeRefusal": report.wake_refusal,            "pending": pending,            "lastPullAt": at,            // The pass under way or just ended, as its pages landed (MAIL ALL ON PHONE's measure): pages and bytes.            "passPages": self.sync_progress().map(|progress| progress.state().pages),            "passBytes": self.sync_progress().map(|progress| progress.state().pass_bytes),        });        self.events.emit(EventKind::Client, answer.clone());        // THE SAME `data` EVENT A WRITE CARRIES, from the PULL half. A screen        // learns about its own write and about another device's through one        // channel rather than two — which is what makes the invalidation map        // (design P5) one map rather than two, and what makes a phone redraw        // when the Mac writes.        //        // Emitted only when the fold actually touched something: an empty        // `tables` is a pull that brought nothing, and an event for it would        // wake every screen on the app for news that there is none.        if !report.tables.is_empty() {            self.events.emit(                EventKind::Data,                json!({                    "workspaceId": workspace_id,                    "tables": report.tables,                    "origin": "pull",                }),            );        }        Ok(answer)    }    /// THE PROCESS HAS `budget` FROM NOW — a background slice begins. Every    /// pass until the answer is dropped stops between pages once the time is    /// gone, and no request is left in the air past it.    pub fn begin_slice(&self, budget: std::time::Duration) -> Slice {        Slice {            until: self.time_box.close_in(budget),            time_box: self.time_box.clone(),        }    }    /// Is there time in the slice for another page? Always, outside one.    pub fn slice_has_room(&self) -> bool {        self.time_box.room_for_a_page()    }    /// `sync.now`, PASS AFTER PASS, until this device is level or the slice    /// is out of time — what a background slice runs.    ///    /// One pass is ten pages at most, so that the loop breathes; a slice with    /// time left and more waiting asks again at once, because the time is the    /// scarce thing here and iOS decides when the next slice comes. The    /// answer is `sync.now`'s, summed, and its `behind` is the last pass's:    /// true means "schedule another slice".    ///    /// It stops, too, on a pass that moved nothing while still saying behind    /// — that is not a catch-up, and asking it again every few milliseconds    /// for the rest of the slice would be a battery spent on no row.    pub fn sync_now_until_level(&self) -> Result<Value, String> {        let mut answer = self.sync_now()?;        let moved = |answer: &Value, key: &str| answer.get(key).and_then(Value::as_u64).unwrap_or(0);        let behind = |answer: &Value| answer.get("behind").and_then(Value::as_bool) == Some(true);        let mut last_moved = moved(&answer, "pushed") + moved(&answer, "pulled");        while behind(&answer) && last_moved > 0 && self.time_box.room_for_a_page() {            // A LATER PASS FAILING DOES NOT UNDO THE EARLIER ONES: their pages            // are folded. The slice answers what landed, still behind.            let Ok(more) = self.sync_now() else { break };            last_moved = moved(&more, "pushed") + moved(&more, "pulled");            let (pushed, pulled) = (                moved(&answer, "pushed") + moved(&more, "pushed"),                moved(&answer, "pulled") + moved(&more, "pulled"),            );            answer = more;            if let Some(answer) = answer.as_object_mut() {                answer.insert("pushed".to_string(), json!(pushed));                answer.insert("pulled".to_string(), json!(pulled));            }        }        Ok(answer)    }    /// `sync.now` over the running schedule.    ///    /// The `data` event is NOT emitted here: the loop's own `on_tables`    /// listener does it for every pass, whoever asked, and doing it twice would    /// redraw every screen twice for one pull.    fn sync_now_scheduled(&self) -> Result<Value, String> {        let runtime = self            .runtime            .lock()            .map_err(|_| locked())?            .clone()            .ok_or_else(|| NO_TRANSPORT.to_string())?;        // The future is driven from whatever thread called in — an FFI caller's        // — and the loop it belongs to is not held across the await: taking the        // loop's lock for the length of a network cycle would make every status        // question wait on the server.        let scheduled = {            let held = self.sync_loop.lock().map_err(|_| locked())?;            held.as_ref()                .ok_or_else(not_connected_sentence)?                .handle()        };        // Spawn and wait on a channel rather than `Handle::block_on`, which        // panics when the calling thread is already inside this runtime — the        // case a subscriber asking for a sync from inside a `data` event hits.        let (sender, receiver) = std::sync::mpsc::channel();        runtime.spawn(async move {            let _ = sender.send(scheduled.pull_now().await);        });        let report = receiver            .recv()            .map_err(|_| "the runtime dropped a sync before it answered".to_string())?            .map_err(|failure| cycle_failure_sentence(&failure))?;        let pending = self.with_file(|file| Ok(current_pending(file.driver)))?;        let answer = json!({            "pushed": report.pushed,            "pulled": report.pulled,            "behind": report.behind,            // What the serving Mac said still waits, over the pass's last            // answers — what the cap counts down from (`null` unsaid).            "behindBy": report.remaining,            "wakeRefusal": report.wake_refusal,            "pending": pending,            // The pass just ended, as its pages landed (MAIL ALL ON PHONE's measure): pages and bytes.            "passPages": self.sync_progress().map(|progress| progress.state().pages),            "passBytes": self.sync_progress().map(|progress| progress.state().pass_bytes),            "lastPullAt": self                .last_pull_at                .lock()                .ok()                .and_then(|held| held.clone()),        });        self.events.emit(EventKind::Client, answer.clone());        Ok(answer)    }    /// Run one READ against this device's replica.    ///    /// The replica IS the cache (design P5): a read is a SQLite query on a local    /// file, so there is nothing to remember between two of them and no cache    /// library to keep coherent. What this gives a read method is the driver,    /// the workspace id and the owner id.    ///    /// **ON THE READ CONNECTION, never the writer's mutex.** An offline-first    /// app never makes a screen wait on a sync write: the fold holds the    /// writer for a batch at a time, and a read that queued behind it drew a    /// spinner over a list that answers in milliseconds. The reader is    /// read-only (a write here fails loudly — use [`Self::with_writer`]) and    /// the whole closure runs in ONE read transaction, so every query in it    /// sees the same committed snapshot even while a fold commits beside it;    /// a fresh transaction per call is what makes this device's own write,    /// committed a moment ago, visible to the next read. `#[track_caller]`,    /// like [`Self::with_file_in`]: a slow hold names its caller.    #[track_caller]    pub fn with_file<T>(        &self,        work: impl FnOnce(&ReadFile<'_>) -> Result<T, String>,    ) -> Result<T, String> {        if let Some(database)=NAMED.with(|named|named.borrow().clone()) {            return self.with_file_in(&database,work);        }        self.attach()?;        let readers = self.attached_readers()?;        let reader = take_reader(&readers).map_err(read_not_open)?;        let mut answer = None;        let mut work = Some(work);        reader            .driver            .transaction(|_| {                if let Some(work) = work.take() {                    answer = Some(work(&ReadFile::of_reader(&reader)));                }                Ok(())            })            .map_err(|error| error.to_string())?;        answer.expect("the read transaction ran the work exactly once")    }    /// When a pull from the serving Mac last landed on this device's own    /// file, as this process knows it — `None` until one has, since launch.    pub fn last_pull_at(&self) -> Option<String> {        self.last_pull_at.lock().ok().and_then(|held| held.clone())    }    /// A pull that landed at `at`, as a pass notes one: for tests whose copy    /// stands for a phone that has synced.    #[cfg(test)]    pub(crate) fn note_pull_for_test(&self, at: &str) {        if let Ok(mut slot) = self.last_pull_at.lock() {            *slot = Some(at.to_string());        }        if let Ok(database) = self.current_database() {            if let Ok(mut slot) = self.pulled_for.lock() {                *slot = Some(database);            }        }    }    /// A pass that reached the server, for a database that is not the one attached (another number's, before a    /// sign-out).    #[cfg(test)]    pub(crate) fn note_pull_of_another_database_for_test(&self, at: &str) {        if let Ok(mut slot) = self.last_pull_at.lock() {            *slot = Some(at.to_string());        }        if let Ok(mut slot) = self.pulled_for.lock() {            *slot = Some("11111111-0000-4000-8000-another-number".to_string());        }    }    /// Whether a pass that reached the server was for `database` (the one attached now, as the caller names it).    pub fn pulled(&self, database: &str) -> bool {        self.pulled_for.lock().ok().is_some_and(|held| held.as_deref() == Some(database))    }    /// Whether this run's last pass for `database` ended with nothing still to pull: what a reader that acts on    /// the absence of a row waits for (Sites' migration and its cleanup).    pub fn caught_up(&self, database: &str) -> bool {        let now = self.detaches.load(std::sync::atomic::Ordering::SeqCst);        self.caught_up_for.lock().ok().is_some_and(|held| held.as_ref().is_some_and(|(db, generation)| db == database && *generation == now))    }    /// Whether this copy of `database` has been caught up at least once since it opened: what a list waits for    /// before it stops saying "Loading" (a pass running does not take it back).    pub fn caught_up_once(&self, database: &str) -> bool {        let now = self.detaches.load(std::sync::atomic::Ordering::SeqCst);        self.caught_up_once_for.lock().ok().is_some_and(|held| held.as_ref().is_some_and(|(db, generation)| db == database && *generation == now))    }    /// Run one WRITE against this device's file that is not a tool's — a    /// device-local ledger stamp (`_media`), a retry of parked ops.    ///    /// The writer connection, under the writer's mutex, exactly as `write`    /// and the sync fold take it; [`Self::with_file`] is read-only and refuses    /// a write.    pub fn with_writer<T>(        &self,        work: impl FnOnce(&ReadFile<'_>) -> Result<T, String>,    ) -> Result<T, String> {        self.attach()?;        let (_workspace_id, replica) = self.attached_replica()?;        let replica = replica.lock().map_err(|_| locked())?;        work(&ReadFile::of(&replica))    }    /// The writer's own driver, held outright for the call: for work that sets    /// a handler on its connection (rusqlite 0.41 takes `&mut Connection`).    pub fn with_writer_driver<T>(&self, work: impl FnOnce(&mut Driver) -> Result<T, String>) -> Result<T, String> {        self.attach()?;        let (_workspace_id, replica) = self.attached_replica()?;        let mut replica = replica.lock().map_err(|_| locked())?;        work(&mut replica.driver)    }    /// Say that rows of `tables` moved in `workspace_id`'s file — the `data`    /// event every list re-reads on — for a write that is not a tool's (a    /// parked op's retry). Call it with no lock held.    /// This file's bus and how often it has moved on (`EventBus::moved`): a    /// read kept beside it stands while it is the same.    pub(crate) fn moved(&self) -> (u64, u64) {        self.events.moved()    }    /// This file's bus, for a read kept beyond one call (`EventBus::stands`).    pub(crate) fn bus(&self) -> Arc<EventBus> {        Arc::clone(&self.events)    }    pub(crate) fn emit_data(&self, workspace_id: &str, tables: Vec<String>, origin: &str) {        self.events.emit(            EventKind::Data,            json!({ "workspaceId": workspace_id, "tables": tables, "origin": origin }),        );    }    /// Say a background move of this file done (`MOVES_DONE_ORIGIN`): the    /// `data` event naming `tables`, so what read over them while they moved    /// reads again by itself. Call it with no lock held.    pub(crate) fn say_moves_done(&self, tables: Vec<String>) {        if let Ok((workspace_id, _)) = self.attached_replica() {            self.emit_data(&workspace_id, tables, MOVES_DONE_ORIGIN);        }    }    /// The id of the database a call made now is about (the named one, else    /// this device's own) — what a typed refusal names as its `database`.    pub(crate) fn attached_database(&self) -> Option<String> {        self.attached_replica().ok().map(|(workspace_id, _)| workspace_id)    }    /// Run this file's background move now — the computed index's rebuild    /// the open left — and say it done; for a suite that holds the move's    /// two sides apart.    #[cfg(test)]    pub(crate) fn bring_moves_done_for_tests(&self) -> Result<bool, String> {        self.settle_moves_for_tests();        // A suite may ask before its first call has opened the copy.        if self.attached_replica().is_err() {            self.attach()?;        }        let (workspace_id, replica) = self.attached_replica()?;        bring_moves_done(&workspace_id, &replica, &self.events)    }    /// Wait for the background move the open started to end — a join, not    /// a poll — so a suite's own stale index is not rebuilt under it.    #[cfg(test)]    pub(crate) fn settle_moves_for_tests(&self) {        let moving = self.index_move.lock().ok().and_then(|mut held| held.take());        if let Some(moving) = moving {            let _ = moving.join();        }    }    /// The bus this controller emits on, for a suite that reads what it said.    #[cfg(test)]    pub(crate) fn events_for_tests(&self) -> &Arc<EventBus> {        &self.events    }    /// The workspace id and the replica handle, with `state` ALREADY LET GO.    ///    /// `state` is the coarse lock — it guards the connection record, the    /// workspace id and the ingest queue as well as the replica — so anything    /// holding it across slow work stops every other caller, including ones    /// that never wanted the database. Everything a read or a write needs out    /// of it is an `Arc` and a `String`, so it is taken, copied, and dropped    /// before the work starts.    ///    /// The REPLICA lock is a different matter and is deliberately not narrowed:    /// one file, one WRITER connection, and `Driver` is not `Sync`. Only    /// writes take it — every read is on the reader ([`Self::attached_readers`])    /// — and it is NEVER held across the network: a write ends at its    /// transaction, and the sync loop's paged passes take the mutex for a    /// batch and a fold and let it go for the round trip    /// (`cotton_client::sync::cycle::{run_cycle_paged, push_only_paged}`).    fn attached_replica(&self) -> Result<(String, Arc<Mutex<Replica>>), String> {        if let Some(database) = named_database() {            let open = self.open_database(&database)?;            return Ok((open.workspace_id, open.replica));        }        let state = self.state.lock().map_err(|_| locked())?;        let attached = state.as_ref().ok_or_else(not_connected_sentence)?;        Ok((attached.workspace_id.clone(), Arc::clone(&attached.replica)))    }    /// This device is the file's writer of record for what time makes (a    /// repeating todo's next occurrence: [`cotton_tools::rails::ThisFile::unserved`]):    /// no machine serves its copy of `workspace_id` yet (the device started    /// its own database and has met no Mac, `ConnectionMode::Local`, or the    /// database was made here and no server has taken it, `pending`), or the    /// copy's todos are sealed on its object, which cannot read a series'    /// words to copy them (e2e rulings R3, 15 Nov 2026): every device of the    /// person's mints, and two that overlap write the same derived ids. Off the connection record alone; a record    /// that cannot be read answers `false`, so a copy that cannot say it is    /// alone waits for its server.    /// The kit this app keeps to, as its open kept it beside the data    /// (`AppKit::at`); `None` for the whole object, and for a kit file that    /// does not read (the open that wrote it would have refused first).    fn app_kit(&self) -> Option<Arc<cotton_core::kit::AppKit>> {        cotton_core::kit::AppKit::at(self.layout.root()).ok().flatten().map(Arc::new)    }    fn unserved(&self, workspace_id: &str) -> bool {        let Ok(Some(record)) = read_record(&self.layout.connection_json()) else {            return false;        };        !record.mine.mode.has_server()            || record.places.iter().any(|place| place.id == workspace_id && place.pending)            || self.todos_sealed(workspace_id)    }    /// Whether this copy's `todo` table is sealed, as its object serves it    /// (e2e rulings R1): then the object makes no occurrence and this device    /// does ([`Self::unserved`]). A copy a Mac serves holds no seal block.    fn todos_sealed(&self, workspace_id: &str) -> bool {        let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX;        let Ok(file) = rusqlite::Connection::open_with_flags(self.layout.replica(workspace_id), flags) else { return false };        file.query_row("SELECT definition FROM cotton_table_definitions WHERE id = 'todo'", [], |row| row.get::<_, String>(0))            .ok()            .and_then(|text| serde_json::from_str::<Value>(&text).ok())            .is_some_and(|definition| definition.get("seal").is_some_and(|seal| !seal.is_null()))    }    /// The read connections, with `state` already let go — the reads' twin of    /// [`Self::attached_replica`]. A read takes one free connection for itself    /// (`Driver` is not `Sync`), so it never waits on the writer, and waits on    /// another read only when every connection of the pool is in one.    fn attached_readers(&self) -> Result<Arc<ReadPool>, String> {        if let Some(database) = named_database() {            return Ok(self.open_database(&database)?.readers);        }        let state = self.state.lock().map_err(|_| locked())?;        let attached = state.as_ref().ok_or_else(not_connected_sentence)?;        Ok(Arc::clone(&attached.readers))    }    /// The personal database's id, as this device holds it.    fn personal_id(&self) -> Option<String> {        self.databases().ok()?.into_iter().find(|database| database.personal).map(|database| database.id)    }    /// The database the call names, when it is not the personal one.    fn shared_named(&self) -> Option<String> {        let named = named_database()?;        (Some(named.as_str()) != self.personal_id().as_deref()).then_some(named)    }    /// Run one READ TOOL against this device's replica.    ///    /// The same handler an assistant reaches, over the same context a write    /// uses — which is what makes "the project page on the Mac counts what the    /// phone's counts" survive the port. Nothing is queued and nothing is    /// pushed: a read tool writes no rows, and the catalogue's own scope is    /// what says which tools those are (`reads_tests.rs` holds the table to    /// it).    pub fn read_tool(        &self,        tool: &str,        args: &serde_json::Map<String, Value>,    ) -> Result<Value, String> {        self.read_tool_rows(tool, &mut |ctx| {            let handler = cotton_tools::mcp::dispatch::handler_for(tool)                .ok_or_else(|| format!("{tool} is not implemented on this build yet"))?;            handler(ctx, args).map_err(|error| error.to_string())        })    }    /// A tool read whose caller also keeps typed inputs from the same handler.    /// The personal-file and filing rails are identical to read_tool's.    pub(crate) fn read_tool_rows(        &self,        tool: &str,        body: &mut dyn FnMut(&mut cotton_tools::mcp::dispatch::Ctx<'_>) -> Result<Value, String>,    ) -> Result<Value, String> {        // Read where it is written: a private kind answers from the personal        // database, whatever the call names (`write`).        if cotton_tools::mcp::places_classes::personal_refusal(self.genesis(), tool).is_some() {            self.require_personal()?;        }        let _personal = lives_in_personal(tool)            .then(|| self.name_database(None))            .transpose()?;        // Before the file is taken: how this device's owner keeps a shared        // database's filed chats.        self.attach()?;        // THE READER, never the writer's mutex — see `with_file`.        let direct = named_database().and_then(|database| self.short_direct(&database)).transpose()?;        let readers;        let lease;        let reader: &ReadReplica = match &direct {            Some(direct) => direct,            None => {                readers = self.attached_readers()?;                lease = take_reader(&readers).map_err(read_not_open)?;                &lease            }        };        let clock = ServerShapedClock(Arc::clone(&self.clock));        let device_key = self.self_device_id();        let input = WriteInput {            workspace_id: &reader.workspace_id,            identity: &reader.identity,            owner_id: &reader.owner_id,            device_id: &reader.device_id,            device_key: device_key.as_deref(),            clock: &clock,            random: Arc::new(ServerShapedRandom(Arc::clone(&self.random))),            vault: None,            held: Some(cotton_tools::rails::FileHeld::Replica),            unserved: false,            kit: self.app_kit(),            tool_signer: self.tool_signer(),        };        // IN ONE TRANSACTION, so every query the handler runs sees the same        // committed snapshot while a sync fold commits beside it. The        // connection is read-only, so a handler that tries to write is refused        // by SQLite itself; the op check below names the catalogued read that        // minted ops.        let answer = reader            .driver            .transaction(|db| {                let (answer, ops) = crate::authoring::read_with_ctx(db, &input, body)                    .map_err(cotton_store::StoreError::refused)?;                // Loud rather than quiet. A "read" that minted ops is a tool                // whose scope in the catalogue disagrees with what it does.                if !ops.is_empty() {                    return Err(cotton_store::StoreError::refused(format!(                        "{tool} is catalogued as a read but wrote {} op(s) — rolling the write \                         back rather than leaving rows in this replica that nothing will push",                        ops.len()                    )));                }                Ok(answer)            })            .map_err(|error| {                wrote_on_the_reader(error.to_string(), || {                    format!("{tool} is catalogued as a read but wrote")                })            })?;        Ok(answer)    }    /// Run one COMPOSED read against this device's replica.    ///    /// [`Self::read_tool`]'s twin, and the twinning is the point: same attach,    /// same lock, same `Ctx::phone`, same transaction, same refusal if anything    /// wrote. The one difference is that the body is the caller's closure rather    /// than a single handler, which is what a screen whose answer is SEVERAL    /// tools plus a join needs — `/accounts` is a list of accounts and the audit's    /// open counts; a chat thread is its messages, its receipts and its calls.    /// Composing them here rather than making the app ask four times is design    /// P4's whole argument, and composing them over this context is what keeps    /// each part the handler an assistant would have run.    ///    /// `label` is the read's own name, so a refusal names the screen's read    /// rather than a tool the caller never asked for.    /// Engine page reads use an independent snapshot on a serving Mac.    /// A missing snapshot rail refuses; it never falls back to the writer.    pub fn read_rows_snapshot(        &self, label: &str,        body: &mut dyn FnMut(&mut cotton_tools::mcp::dispatch::Ctx<'_>) -> Result<Value, String>,    ) -> Result<Value, String> {        let clock = ServerShapedClock(Arc::clone(&self.clock));        let key = self.self_device_id();        self.with_file(|file| {            let input = WriteInput {                workspace_id: file.workspace_id, identity: file.identity,                owner_id: file.owner_id, device_id: file.device_id,                device_key: key.as_deref(), clock: &clock,                random: Arc::new(ServerShapedRandom(Arc::clone(&self.random))),                vault: None, held: Some(file.held), unserved: false, kit: self.app_kit(), tool_signer: self.tool_signer(),            };            let (answer, ops) = crate::authoring::read_with_ctx(file.driver, &input, body)?;            if !ops.is_empty() { return Err(format!("read.{label} wrote {} op(s)", ops.len())); }            Ok(answer)        })    }    pub fn read_tool_snapshot(&self, tool: &str, args: &serde_json::Map<String, Value>) -> Result<Value, String> {        let entry = cotton_tools::mcp::protocol::tool_by_name(tool)            .filter(|entry| entry.scope == cotton_tools::mcp::protocol::McpScope::Read)            .ok_or_else(|| format!("{tool} is not a read-only tool"))?;        let _ = entry;        let handler = cotton_tools::mcp::dispatch::handler_for(tool)            .ok_or_else(|| format!("{tool} is not implemented on this build"))?;        self.read_rows_snapshot(tool, &mut |ctx| handler(ctx, args).map_err(|error| error.to_string()))    }    pub fn read_rows(        &self,        label: &str,        body: &mut dyn FnMut(            &mut cotton_tools::mcp::dispatch::Ctx<'_>,        ) -> Result<Value, String>,    ) -> Result<Value, String> {        self.read_rows_on(label, body)    }    fn read_rows_on(        &self,        label: &str,        body: &mut dyn FnMut(            &mut cotton_tools::mcp::dispatch::Ctx<'_>,        ) -> Result<Value, String>,    ) -> Result<Value, String> {        self.attach()?;        // THE READER, never the writer's mutex — see `with_file`.        let direct = named_database().and_then(|database| self.short_direct(&database)).transpose()?;        let readers;        let lease;        let reader: &ReadReplica = match &direct {            Some(direct) => direct,            None => {                readers = self.attached_readers()?;                lease = take_reader(&readers).map_err(read_not_open)?;                &lease            }        };        let clock = ServerShapedClock(Arc::clone(&self.clock));        let device_key = self.self_device_id();        let input = WriteInput {            workspace_id: &reader.workspace_id,            identity: &reader.identity,            owner_id: &reader.owner_id,            device_id: &reader.device_id,            device_key: device_key.as_deref(),            clock: &clock,            random: Arc::new(ServerShapedRandom(Arc::clone(&self.random))),            vault: None,            held: Some(cotton_tools::rails::FileHeld::Replica),            unserved: false,            kit: self.app_kit(),            tool_signer: self.tool_signer(),        };        let answer = reader            .driver            .transaction(|db| {                let (answer, ops) = crate::authoring::read_with_ctx(db, &input, body)                    .map_err(cotton_store::StoreError::refused)?;                // The same loud refusal `read_tool` makes, for the same reason:                // a screen that wrote something by being LOOKED AT is a defect,                // and the rollback is what stops it leaving a row behind.                if !ops.is_empty() {                    return Err(cotton_store::StoreError::refused(format!(                        "read.{label} wrote {} op(s) — rolling the write back rather than \                         leaving rows in this replica that nothing will push",                        ops.len()                    )));                }                Ok(answer)            })            .map_err(|error| {                wrote_on_the_reader(error.to_string(), || format!("read.{label} wrote"))            })?;        Ok(answer)    }    /// Write, as this device, by calling the tool an assistant would call.    ///    /// Design P3, and the phone's ONE write method. The vocabulary is the whole    /// tool surface rather than the window's closed seventeen: a screen that    /// needs a verb has to ADD THE TOOL, which the verb grid already forces, so    /// the app cannot invent a write the assistants do not have — and the    /// hand-ported `validateX` argument checks defend the app's own writes for    /// free.    ///    /// Everything else is [`Self::decide`]'s: the same `authoring` body, the    /// same `Ctx::phone`, the same outbox, the same "a write does not fail    /// because the server is unreachable".    pub fn write(        &self,        tool: &str,        args: &serde_json::Map<String, Value>,    ) -> Result<Value, String> {        // A READER'S OWN MARK ON A FILED CHAT (pin, mute, archive, clear) is        // kept in their personal database, naming the shared one the copy is        // in (`PlacesClass::PersonalInto`, `messages::marks`): never on the        // copy everybody there reads. So an act on a chat of the shared        // database on screen runs in the personal one, about that database.        let mut about: Option<serde_json::Map<String, Value>> = None;        if matches!(            cotton_tools::mcp::places_classes::class_of(tool),            Some(cotton_tools::mcp::places_classes::PlacesClass::PersonalInto)        ) && !args.contains_key("database")        {            if let Some(shared) = self.shared_named() {                let mut named = args.clone();                named.insert("database".to_string(), Value::from(shared));                about = Some(named);            }        }        let args = about.as_ref().unwrap_or(args);        // A PRIVATE KIND IS WRITTEN TO THE PERSONAL DATABASE BY ID, whatever        // the call names: a mood or a bank line recorded while a project is on        // screen must never be filed into a file other people read.        if cotton_tools::mcp::places_classes::personal_refusal(self.genesis(), tool).is_some() || about.is_some() {            self.require_personal()?;        }        let _personal = (lives_in_personal(tool) || about.is_some())            .then(|| self.name_database(None))            .transpose()?;        self.refuse_writes()?;        self.attach()?;        // `state` is taken and let go here — see `attached_replica`. The        // replica lock is held for the TRANSACTION and nothing else.        let (workspace_id, replica) = self.attached_replica()?;        // THE LOCK ENDS WITH THIS BLOCK, and the events are emitted after it.        // A subscriber runs on the emitting thread and is somebody else's code:        // one that answers a `data` event by reading the screen it just        // invalidated — which is exactly what a screen does — would re-enter        // this controller and block for ever on a lock its own call stack        // holds. So the write finishes, the guards drop, and only then does        // anyone get told.        //        // AND NO NETWORK INSIDE IT. The push is the sync loop's        // (`wake_sync_loop`, below): a round trip run here, under this mutex,        // queued every screen read on the phone behind a 60 s request ceiling        // whenever the Mac was slow to answer — `authoring::write_through_outbox`        // says what that cost.        let answer = {            let replica = replica.lock().map_err(|_| locked())?;            let clock = ServerShapedClock(Arc::clone(&self.clock));            let device_key = self.self_device_id();            let input = WriteInput {                workspace_id: &workspace_id,                identity: &replica.identity,                owner_id: &replica.owner_id,                device_id: &replica.device_id,                device_key: device_key.as_deref(),                clock: &clock,                random: Arc::new(ServerShapedRandom(Arc::clone(&self.random))),                vault: None,                held: Some(cotton_tools::rails::FileHeld::Replica),                unserved: self.unserved(&workspace_id),                kit: self.app_kit(),                tool_signer: self.tool_signer(),            };            crate::authoring::write_through_outbox(&replica.driver, tool, args, &input)?        };        let Value::Object(mut answer) = answer else {            return Err("a write answered with something that is not an object".to_string());        };        // The rows it moved go on the event alone, never into the answer.        let rows = answer.remove("rows").unwrap_or(Value::Null);        // The phone names a write by the TOOL it called, where the window names        // a decision by its verb: the same envelope, one field apart.        answer.insert("tool".to_string(), json!(tool));        let answer = Value::Object(answer);        // A WRITE THAT LEFT THE INDEX STALE — `add_tool`, `import_tool` or a        // definition edit redefining a table — brings it current here, after        // the write and outside its lock. Left to the pass beside a pull, the        // next write reading a computed column was refused ("This list is        // being worked out") until a pull brought rows or the app opened        // again, and a phone not signed in pulls nothing (af81b8d8e).        let current = cotton_tools::derive::is_current(&replica.lock().map_err(|_| locked())?.driver)            .map_err(|error| error.to_string())?;        if !current {            bring_moves_done(&workspace_id, &replica, &self.events)?;        }        // The op is in the outbox; the loop carries it, starting now rather        // than at its minute. Before the events, so the round trip is already        // in the air while the screens redraw.        self.wake_sync_loop();        // THE INVALIDATION (design P5). The replica IS the cache — a read is a        // SQLite query on a local file — so what a screen needs after a write        // is not an expiry, it is the list of TABLES that moved, and that is        // the whole of the event. It used to carry a `serverSeq` beside them;        // there is no server sequence any more, and no reader ever decoded it.        let tables = answer            .get("tables")            .cloned()            .unwrap_or_else(|| Value::Array(Vec::new()));        let payload = json!({            "workspaceId": workspace_id,            "tables": tables,            "rows": rows,            "origin": "write",        });        if moved_something(&payload) {            self.events.emit(EventKind::Data, payload);        }        self.events.emit(EventKind::Client, answer.clone());        Ok(answer)    }}/// The decision path takes the SERVER's clock and random traits — it is the/// server's own tool handler doing the writing — and this controller holds the/// client's. Identical shapes in two crates, so these are the bridge rather/// than a second clock and a second generator with their own drift.#[derive(Debug)]struct ServerShapedClock(Arc<dyn Clock>);impl cotton_tools::clock::Clock for ServerShapedClock {    fn now(&self) -> chrono::DateTime<chrono::Utc> {        self.0.now()    }}/// `{phase:"databaseSync", workspaceId, line, sync, reported, pushed?, pulled?, behind?, behindBy?}` —/// what one pass REPORTED for one database: rows the peer took, rows taken/// in, and whether more waits; `reported: false` when its section did not/// answer. Said as a pass ends, never as one starts (owner, 11 Oct 2026).////// `line` is what goes under that database's cap after this pass — the/// words of `cotton_client::sync::line`, drawn as they are, empty for the/// people line — and `sync` the whole standing they come from (state, the/// page's sentence, percent, what is left).pub fn database_sync_frame(    database: &str,    reported: Option<cotton_client::sync::Reported>,    standing: &cotton_client::sync::line::Standing,) -> Value {    match reported {        Some(report) => json!({            "phase": "databaseSync",            "workspaceId": database,            "line": standing.words,            "sync": standing,            "reported": true,            "pushed": report.pushed,            "pulled": report.pulled,            "behind": report.behind,            "behindBy": report.remaining,        }),        None => json!({            "phase": "databaseSync",            "workspaceId": database,            "line": standing.words,            "sync": standing,            "reported": false,        }),    }}/// Where the sync of every database this device's passes have reported on/// stands, by database id. One map for the loop's own passes and the passes/// to other people's Macs, so a database has one line whoever carries it.////// The catch-ups in flight, and when a Mac last answered, are kept in the/// device's own file (`Layout::home_lines_json`), so a relaunch picks the/// percent up where it was instead of starting it again.#[derive(Clone)]struct HomeLines {    lines: Arc<Mutex<std::collections::BTreeMap<String, cotton_client::sync::line::HomeLine>>>,    kept_at: Arc<std::path::PathBuf>,}impl HomeLines {    /// The lines, with what the last run left.    fn kept_at(path: std::path::PathBuf) -> Self {        HomeLines {            lines: Arc::new(Mutex::new(cotton_client::sync::line::stored(&path))),            kept_at: Arc::new(path),        }    }    /// One database's section of a pass that finished at `now_ms`; answers    /// where it stands now.    fn heard(        &self,        database: &str,        reported: Option<cotton_client::sync::Reported>,        refused: Option<cotton_client::sync::SchemaStanding>,        moved: Option<cotton_client::sync::TableMoves<'_>>,        answered: bool,        now_ms: i64,    ) -> cotton_client::sync::line::Standing {        let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        let line = lines.entry(database.to_string()).or_default();        let was = line.clone();        match reported {            Some(report) => line.answered(                cotton_client::sync::line::Answered {                    // Receipts, not rows: the unit the Mac's count of what                    // was owed is in (`sync::line`).                    sent: report.handed as u64,                    received: report.passed as u64,                    unsent: report.unsent,                    owed_at_start: report.owed_at_start,                    remaining: report.remaining,                    behind: report.behind,                },                now_ms,            ),            None if answered => line.contacted(refused, now_ms),            None => line.unanswered(refused, now_ms),        }        if let Some(moved) = moved {            line.came(moved.received, moved.owed);        }        let standing = line.standing(now_ms);        // Written only when a catch-up began, moved or ended, and every few        // minutes for the time a Mac last answered — never once a pass.        if !line.same_place(&was) {            cotton_client::sync::line::store(&self.kept_at, &lines);        }        standing    }    /// Nothing of `database` stays in the lines: its account was deleted (`account.forget`).    fn forget(&self, database: &str) {        let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        if lines.remove(database).is_some() {            cotton_client::sync::line::store(&self.kept_at, &lines);        }    }    /// A file copy of `database` has `bytes_to_go` left, or is over.    fn copying(        &self,        database: &str,        bytes_to_go: Option<u64>,        now_ms: i64,    ) -> cotton_client::sync::line::Standing {        let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        let line = lines.entry(database.to_string()).or_default();        line.copying(bytes_to_go);        line.standing(now_ms)    }    /// A database nothing is known to be wrong with: level, and silent.    fn current() -> cotton_client::sync::line::Standing {        cotton_client::sync::line::HomeLine::default().standing(0)    }    /// Where a database stands; one no pass has reported on yet is level as    /// far as anyone knows.    fn of(&self, database: &str, now_ms: i64) -> cotton_client::sync::line::Standing {        self.lines            .lock()            .unwrap_or_else(|poisoned| poisoned.into_inner())            .get(database)            .map_or_else(Self::current, |line| line.standing(now_ms))    }    /// Every database's words, and every database's standing, by database id.    fn all(&self, now_ms: i64) -> (Value, Value) {        let lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        let mut words = serde_json::Map::new();        let mut standings = serde_json::Map::new();        for (database, line) in lines.iter() {            let standing = line.standing(now_ms);            words.insert(database.clone(), Value::from(standing.words.clone()));            standings.insert(database.clone(), json!(standing));        }        (Value::Object(words), Value::Object(standings))    }}/// Did a pass fail because the serving Mac refuses this build's schema — the/// one failure the home says as "update app" rather than waiting out?#[derive(Debug)]struct ServerShapedRandom(Arc<dyn Random>);impl cotton_tools::random::Random for ServerShapedRandom {    fn fill(&self, out: &mut [u8]) {        self.0.fill(out)    }}/// A database OTHER than the device's own whose copy has not arrived — a/// listed one still downloading, or one whose download did not finish. Said/// on a phone and a Mac alike, so it names neither; [`ClientController::arriving`]/// adds how far the download is or why the last one stopped.const NOT_ARRIVED: &str =    "This database has not arrived on this device yet. It is on its way and appears here when its \     download has finished.";/// Where the first fill of one listed database stands in this process.#[derive(Debug, Clone, PartialEq, Eq)]enum Fill {    Downloading { written: u64, total: Option<u64> },    Failed(String),}/// Why the replica cannot be opened yet, said in the words a person can act on.const NEEDS_SNAPSHOT: &str =    "This Mac has no copy of your database yet. Connect it to a server from the menu bar — the \     first sync brings the file down.";/// A copy has arrived and is being checked, unpacked and claimed; it opens by/// itself when that is done.pub const PLACING_A_COPY: &str =    "Your database has arrived on this device and is being checked and unpacked. It opens by itself when that is done.";/// How many failed uploads the banner is handed.////// Twenty — the number the TypeScript asked for/// (`packages/store/src/client/mediaLedger.ts`). Not a default of the ledger's:/// `media_ledger::failed_media` takes its limit and has none of its own, so/// this constant is the whole decision. A cap rather than the lot: "Sync &/// backup" prints one line per failed file and a ledger with a thousand of them/// is a wall, not an answer.const FAILED_MEDIA_LIMIT: i64 = 20;/// The `_media` ledger, as the second card on "Sync & backup" reads it.////// Counts AND the failed rows with their last error, because the card says both/// "3 files backing up" and names the ones that could not go. Device-local, and/// never synced: this is what THIS phone still owes the server.////// A ledger that cannot be read answers `null` with the reason beside it rather/// than zeros — a card that said "nothing to back up" because a query failed/// would be the silent fallback this repo does not allow.fn media_activity(file: &ReadFile<'_>) -> Value {    let counts =        match cotton_store::media_ledger::media_counts(file.driver, file.workspace_id) {            Ok(counts) => json!({                "pending": counts.pending,                "synced": counts.synced,                "failed": counts.failed,                "deletePending": counts.delete_pending,            }),            Err(error) => {                return json!({ "counts": Value::Null, "failed": Value::Null,                            "unreadable": error.to_string() })            }        };    let failed = match cotton_store::media_ledger::failed_media(        file.driver,        file.workspace_id,        FAILED_MEDIA_LIMIT,    ) {        Ok(rows) => rows            .iter()            .map(|row| {                json!({                    // The object KEY, not a path: the card draws its last                    // segment, and where the bytes are is `read.mediaPath`'s                    // question.                    "key": row.key,                    "lastError": row.last_error,                    "updatedAt": row.updated_at,                })            })            .collect::<Vec<Value>>(),        Err(error) => {            return json!({ "counts": counts, "failed": Value::Null,                            "unreadable": error.to_string() })        }    };    json!({ "counts": counts, "failed": failed })}/// Name the read when the READ connection refused a write it attempted.////// A read that writes is a defect — a catalogue scope that disagrees with its/// handler, a screen that wrote by being looked at — and on a device holding a/// copy SQLite itself refuses it, because every read runs on the read-only/// connection. Its own sentence ("attempt to write a readonly database") names/// neither the read nor what went wrong, so this puts the read's name in/// front. Any other failure passes through untouched./// A pool connection that would not open, said as the attach says it.fn read_not_open(error: cotton_store::StoreError) -> String {    format!("this device's read connection did not open: {error}")}fn wrote_on_the_reader(error: String, what: impl FnOnce() -> String) -> String {    if error.contains("readonly database") {        format!(            "{} — this device's read connection refused the write, so nothing was left in the \             file: {error}",            what()        )    } else {        error    }}fn not_connected(reason: &str) -> Value {    json!({ "connected": false, "reason": reason })}/// The refusal a database this device does not hold answers with.fn not_held(database: &str) -> String {    format!("this device does not hold the database {database}")}fn locked() -> String {    "the client's own state is locked; restart CottonDB and try again".to_string()}#[cfg(test)]#[path = "sync_state_read_tests.rs"]mod sync_state_read_tests;#[cfg(test)]#[path = "reader_sync_tests.rs"]mod reader_sync_tests;// A read never queues behind a write: the guard, and the by-hand measurement.#[cfg(test)]#[path = "read_connection_tests.rs"]mod read_connection_tests;// Home, the Tools board and Today never wait on the shared read pool (readpool).#[cfg(test)]#[path = "read_pool_starve_tests.rs"]mod read_pool_starve_tests;// The starvation on a generated household, by hand in release (readpool).#[cfg(test)]#[path = "read_pool_household_tests.rs"]mod read_pool_household_tests;// ─────────────────────────────────────────────────────────────────────────────// The phone's own writes (4p §3) — appended as its own block so the merge with// the sibling lanes is one hunk.// ─────────────────────────────────────────────────────────────────────────────impl ClientController {    /// The data directory this controller was built over.    ///    /// The media methods need it — the content-addressed store is a PATH under    /// the root and `cotton_client::media::store` takes the layout — and asking    /// the controller beats every caller remembering the same root a second    /// time.    pub fn layout(&self) -> &Layout {        &self.layout    }    /// Give the controller a way to bring bytes DOWN. Until something does,    /// `media.ensure` refuses by name rather than answering a path that is not    /// there.    pub fn set_media_fetch(&self, fetch: Option<Arc<dyn crate::phone::media::MediaFetch>>) {        *self.media_fetch.lock().expect("the media fetch slot") = fetch;    }    /// The media keys the far end answered 404 for, and how long each waits.    pub(crate) fn absent_media(&self) -> &cotton_client::media::absent::AbsentKeys {        &self.absent_media    }    /// Hold the door to the person's own object, from `personal.connect` on.    pub fn set_object_door(&self, door: Option<Arc<crate::phone::personal_object::ObjectDoor>>) {        *self.object_door.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = door;    }    /// The door to the person's own object, or None before `personal.connect`.    /// The data keys this device holds for its databases' sealed tables.    pub fn data_keys(&self) -> &Arc<cotton_client::seal::HeldDataKeys> {        &self.data_keys    }    /// Say that `object`'s copy is this phone's own local database `local`, backed up (`phone::adopt`), or forget it.    pub fn set_carried_key(&self, carried: Option<(String, String)>) {        *self.carried_key.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = carried;    }    /// The local database whose data key `object` may take as its own, when one is being carried into it.    pub fn carried_key_from(&self, object: &str) -> Option<String> {        self.carried_key.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|(into, _)| into == object).map(|(_, local)| local.clone())    }    /// The Cotton Calling call this device holds (`phone::calls`).    pub fn call_slot(&self) -> &Mutex<cotton_core::calling::Call> {        &self.call    }    /// The calls that ended here lately (`phone::calls`): memory only.    pub fn ended_calls(&self) -> &Mutex<Vec<(String, i64, cotton_core::calling::wire::EndReason)>> {        &self.ended_calls    }    /// The notes this phone takes on a call (`phone::call_notes`).    pub fn notes_slot(&self) -> &Mutex<crate::phone::call_notes::Notes> {        &self.notes    }    pub fn chat_memory(&self) -> &Mutex<crate::phone::cotton_chat::ChatMemory> {        &self.chat    }    pub fn object_door(&self) -> Option<Arc<crate::phone::personal_object::ObjectDoor>> {        self.object_door.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Hold the adopt this launch runs (`phone::adopt`).    pub fn set_adopting(&self, adopting: Option<Arc<crate::phone::adopt::Adopting>>) {        *self.adopting.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = adopting;    }    /// The adopt this launch ran or runs, if any.    pub fn adopting(&self) -> Option<Arc<crate::phone::adopt::Adopting>> {        self.adopting.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Hold the pictures sweep the after-pass hook starts    /// (`phone::media_sweep::kick`).    pub fn set_pictures_sweep(&self, sweep: Option<Arc<crate::phone::media_sweep::PicturesSweep>>) {        *self.pictures_sweep.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = sweep;    }    pub fn pictures_sweep(&self) -> Option<Arc<crate::phone::media_sweep::PicturesSweep>> {        self.pictures_sweep.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Hold where the passes to the personal object stand ([`Self::sync_progress`]).    pub fn set_sync_progress(&self, progress: Option<Arc<cotton_client::transport::object::SyncProgress>>) {        *self.sync_progress.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = progress;    }    /// Hold the object's definitions as the passes hold them ([`Self::served_definitions`]).    pub fn set_served_definitions(&self, held: Option<Arc<cotton_client::transport::object::HeldDefinitions>>) {        *self.served_definitions.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = held;    }    /// The object's definitions as the passes last held them, when the    /// personal object is the far end.    pub fn served_definitions(&self) -> Option<Arc<cotton_client::transport::object::HeldDefinitions>> {        self.served_definitions.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Where the passes to the personal object stand, when it is the far end.    pub fn sync_progress(&self) -> Option<Arc<cotton_client::transport::object::SyncProgress>> {        self.sync_progress.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Hold what makes the copy again when its passes are stuck on one page    /// (`personal.connect`), or let it go.    pub fn set_sync_heal(&self, heal: Option<SyncHeal>) {        *self.sync_heal.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = heal;    }    /// After a pass that failed: make the copy again when it is stuck.    /// Install what makes the copy again after the server was put back (RESTORE 2), or none.    pub fn set_restore_heal(&self, heal: Option<RestoreHeal>) {        *self.restore_heal.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = heal;    }    fn heals(&self) -> Heals {        Heals { stuck: Arc::clone(&self.sync_heal), healed: Arc::clone(&self.copy_healed), restore: Arc::clone(&self.restore_heal), restoring: Arc::clone(&self.copy_restoring) }    }    fn heal_if_stuck(&self) {        heal_if_stuck(&self.sync_progress, &self.heals());    }    /// The saved choices of this device's kept space. No keep-fetch sweep    /// measures what a Mac would send, so nothing is fetched or coming.    pub fn keep_fetch_status(&self, device: &str) -> Result<serde_json::Value, String> {        let (cap, rules) = self.with_file(|f| {            Ok((cotton_client::media::keep_fetch::cap(f.driver, f.workspace_id, device).map_err(|e| e.to_string())?,                cotton_client::media::keep_fetch::byte_rules(f.driver, f.workspace_id, device).map_err(|e| e.to_string())?))        })?;        Ok(serde_json::json!({"keptSpaceBytes":cap,"fetchedBytes":null,"full":null,"fullLine":null,"coming":[],"byteRules":rules}))    }    /// The bytes-down seam, when there is one.    /// The open replica, when this device has one.    ///    /// The `Arc` itself rather than a closure over it, because the one caller    /// — the replicator (`shell/replicate.rs`) — takes and releases the lock    /// PER OBJECT with a download in between, which `with_file` cannot express:    /// it holds the lock for the whole closure, which is exactly what a    /// download must never do.    pub fn replica(&self) -> Option<Arc<Mutex<Replica>>> {        self.state            .lock()            .ok()?            .as_ref()            .map(|attached| Arc::clone(&attached.replica))    }    /// The clock every stamped row on this device reads.    pub fn clock(&self) -> Arc<dyn Clock> {        Arc::clone(&self.clock)    }    /// The random every op id minted on this device draws from.    pub fn random(&self) -> Arc<dyn Random> {        Arc::clone(&self.random)    }    pub fn media_fetch(&self) -> Option<Arc<dyn crate::phone::media::MediaFetch>> {        self.media_fetch            .lock()            .expect("the media fetch slot")            .clone()    }    /// Swap in a different disk — the app's, which can read the free space    /// this core cannot, or a test's, which can be three gigabytes full    /// without writing anything.    #[cfg(test)]    pub fn set_disk(&self, disk: Arc<dyn crate::phone::disk::Disk>) {        *self.disk.lock().expect("the disk seam") = disk;    }    /// The disk seam this controller reads through.    pub fn disk(&self) -> Arc<dyn crate::phone::disk::Disk> {        Arc::clone(&self.disk.lock().expect("the disk seam"))    }    /// Write ROWS as this device, for the writes the tool surface deliberately    /// has no verb for.    ///    /// FIVE CALLERS, not the three this note used to name — the 4h/4i/4j lanes    /// added theirs, and behind each one is a written reason the verb is    /// absent rather than a gap:    ///    /// * [`crate::phone::capture`] — `capture.create`;    /// * [`crate::phone::media`] — `capture.media`;    /// * [`crate::phone::dictation`] — `dictation.create`;    /// * [`crate::phone::page`] — `page.save`;    /// * `phone::settings_writes` — the five `settings.*`    ///   writes, which share one call site.    ///    /// [`Self::write`]'s twin, and the twinning is the point: same attach, same    /// two locks in the same order, same `Ctx::phone`, same outbox, same wake    /// of the loop that pushes, same `data` event carrying `tables` as the    /// invalidation (design P5),    /// same "a write does not fail because the server is unreachable". The one    /// difference is that the body is the caller's closure rather than a tool    /// handler — see [`crate::authoring::author_through_outbox`] for WHY the    /// first five cannot be tools, and `phone::settings_writes`' own module    /// note for why the `settings.*` five are a different class again.    ///    /// `label` is what the answer is named by, where [`Self::write`] puts the    /// tool's name: an app receipt reads `capture.create` rather than a verb    /// that does not exist.    pub fn write_rows(        &self,        label: &str,        body: &mut dyn FnMut(            &mut cotton_tools::mcp::dispatch::Ctx<'_>,        ) -> Result<Value, String>,    ) -> Result<Value, String> {        self.write_rows_with_vault(label, None, body)    }    /// The same write, with the VAULT rail in the context.    ///    /// Every write on a device runs with `ToolServices::none()` and every tool    /// that needs a vault refuses by name — which is what stops a model on a    /// phone from ever sealing anything. What is passed here is the CAPABILITY    /// and never the key.    pub fn write_rows_with_vault(        &self,        label: &str,        vault: Option<Arc<dyn cotton_tools::rails::VaultRail>>,        body: &mut dyn FnMut(            &mut cotton_tools::mcp::dispatch::Ctx<'_>,        ) -> Result<Value, String>,    ) -> Result<Value, String> {        self.refuse_writes()?;        self.attach()?;        let (workspace_id, replica) = self.attached_replica()?;        // THE LOCK ENDS WITH THIS BLOCK and the events are emitted after it —        // `write`'s rule, for `write`'s reason: a subscriber that answers a        // `data` event by re-reading the screen it just invalidated runs on        // this thread and would deadlock on a lock its own stack holds. And no        // network inside it, for `write`'s other reason.        let answer = {            let replica = replica.lock().map_err(|_| locked())?;            let clock = ServerShapedClock(Arc::clone(&self.clock));            let device_key = self.self_device_id();            let input = WriteInput {                workspace_id: &workspace_id,                identity: &replica.identity,                owner_id: &replica.owner_id,                device_id: &replica.device_id,                device_key: device_key.as_deref(),                clock: &clock,                random: Arc::new(ServerShapedRandom(Arc::clone(&self.random))),                vault: vault.clone(),                held: Some(cotton_tools::rails::FileHeld::Replica),                unserved: self.unserved(&workspace_id),                kit: self.app_kit(),                tool_signer: self.tool_signer(),            };            crate::authoring::author_through_outbox(&replica.driver, &input, body)?        };        let Value::Object(mut answer) = answer else {            return Err("a write answered with something that is not an object".to_string());        };        let rows = answer.remove("rows").unwrap_or(Value::Null);        answer.insert("method".to_string(), json!(label));        // Nothing queued, nothing for the loop to carry: no pass is asked        // (`authoring::carries`: a write run after every pass must not bring        // the next one by itself).        let carries = crate::authoring::carries(&answer);        let answer = Value::Object(answer);        if carries {            self.wake_sync_loop();        }        let tables = answer            .get("tables")            .cloned()            .unwrap_or_else(|| Value::Array(Vec::new()));        let payload = json!({            "workspaceId": workspace_id,            "tables": tables,            "rows": rows,            "origin": "write",        });        if moved_something(&payload) {            self.events.emit(EventKind::Data, payload);        }        self.events.emit(EventKind::Client, answer.clone());        Ok(answer)    }}/// What an import writes with: this device's replica under its lock, and the/// three seams every stamp in an import comes from.pub struct ImportSeams<'a> {    pub replica: &'a Replica,    pub layout: &'a Layout,    pub clock: &'a dyn Clock,    pub random: &'a dyn Random,    pub ids: &'a mut dyn cotton_store::outbox::IdSource,}impl ClientController {    /// Run one IMPORT against this device's replica — the WhatsApp export    /// the phone was handed — through the applier the Mac's ingest sources    /// write with (`cotton_client::messages_import`), wake the loop that    /// pushes it, and say which tables moved.    ///    /// The shape is [`Self::write_rows`]' for [`Self::write_rows`]' reasons:    /// the replica lock ends before the events go out, no network runs under    /// it, a write never fails because the server is unreachable, and the    /// answer is named by `label`.    /// The one difference is the body: an import applies the engine's own    /// `LocalChange`s through the store's outbox rather than running a tool    /// over a `Ctx`, so what it is handed is the replica and the seams, not a    /// context. `tables` is what the body says it touched, for the `data`    /// event a screen re-reads on.    pub fn import_rows(        &self,        label: &str,        tables: &[&str],        body: &mut dyn FnMut(&mut ImportSeams<'_>) -> Result<Value, String>,    ) -> Result<Value, String> {        self.require_personal()?;        self.refuse_writes()?;        self.attach()?;        let (workspace_id, replica) = self.attached_replica()?;        // THE LOCK ENDS WITH THIS BLOCK — `write_rows`' rule, for its reason.        let answer = {            let replica = replica.lock().map_err(|_| locked())?;            let mut ids = op_ids(Arc::clone(&self.random));            let mut seams = ImportSeams {                replica: &replica,                layout: &self.layout,                clock: self.clock.as_ref(),                random: self.random.as_ref(),                ids: &mut ids,            };            body(&mut seams)?        };        let Value::Object(mut answer) = answer else {            return Err("an import answered with something that is not an object".to_string());        };        answer.insert("method".to_string(), json!(label));        let answer = Value::Object(answer);        // The rows are in the outbox; the loop carries them, starting now.        self.wake_sync_loop();        let payload = json!({            "workspaceId": workspace_id,            "tables": tables,            "origin": "write",        });        self.events.emit(EventKind::Data, payload);        self.events.emit(EventKind::Client, answer.clone());        Ok(answer)    }}/// What an open of the replica is doing — the step a wait screen names.////// **The core says it; the screen never guesses.** The wait after an update/// used to say "the app was closed suddenly" whatever the open was doing. A/// ladder reports its own steps (`MigrationEvent`); this is the rest of an/// open, and it is decided by the file on disk.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum OpenStep {    /// Opening the file, with nothing left over from the last run.    Reading,    /// A non-empty write-ahead log sits beside the file: the last run stopped    /// before SQLite moved its saved changes into the main file, and this open    /// moves them in first.    Recovering,}impl OpenStep {    /// The step an open of the file at `replica` is about to take.    pub fn of(replica: &std::path::Path) -> OpenStep {        let mut wal = replica.as_os_str().to_owned();        wal.push("-wal");        match std::fs::metadata(std::path::PathBuf::from(wal)) {            Ok(info) if info.len() > 0 => OpenStep::Recovering,            _ => OpenStep::Reading,        }    }    /// The word `migrate.status` answers.    pub fn as_str(self) -> &'static str {        match self {            OpenStep::Reading => "reading",            OpenStep::Recovering => "recovering",        }    }}/// Sets the controller's open step for the length of one open, and clears it/// however the open ends — an early `?` included.struct OpeningMark<'a>(&'a Mutex<Option<OpenStep>>);impl<'a> OpeningMark<'a> {    fn set(slot: &'a Mutex<Option<OpenStep>>, step: OpenStep) -> Self {        *slot.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(step);        OpeningMark(slot)    }}impl Drop for OpeningMark<'_> {    fn drop(&mut self) {        *self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None;    }}#[cfg(test)]pub(crate) mod phone_tests {    use cotton_client::transport::{DeviceRefusal, RefusalKind, RefusalMemory};    use super::*;    /// RULE: background indexing never holds the replica mutex; 18 Oct 2026, build 151 on one Mac was silent 68 s before listening and another Mac was refused after 180 s; Home must read while indexing runs.    #[test]    fn macopen_client_rebuild_releases_the_replica_mutex() {        let (_dir, client) = attached();        client.attach_now().unwrap();        let (workspace, replica) = client.attached_replica().unwrap();        client.settle_moves_for_tests();        {            let held = replica.lock().unwrap();            cotton_store::derived::mark_rebuilt(&held.driver, "foreign-build").unwrap();        }        let boundaries = Mutex::new(Vec::new());        assert!(bring_moves_done_with_progress(&workspace, &replica, &client.events, |progress| {            assert!(replica.try_lock().is_ok(), "Home's replica mutex is held during {progress:?}");            boundaries.lock().unwrap().push(progress);        }).unwrap());        let boundaries = boundaries.into_inner().unwrap();        assert!(matches!(boundaries.as_slice(), [cotton_tools::derive::IndexProgress::Started,            cotton_tools::derive::IndexProgress::Finished { success: true, .. }]));        assert!(cotton_tools::derive::is_current(&replica.lock().unwrap().driver).unwrap());    }    /// RULE: a Reader's household copy that arrives after its own copy has    /// opened rebuilds its local `_computed` index, so its figures answer.    ///    /// WHY: walker298 found no In, Out, Net or running balance on 18 Oct 2026:    /// `start_moves` rebuilt only the attached Personal copy, while the sync    /// loop opened each later household copy through `open_other`.    #[test]    fn a_readers_late_household_copy_rebuilds_money_figures() {        let dir = tempfile::tempdir().expect("a synthetic reader home");        let layout = Layout::new(dir.path());        std::fs::create_dir_all(layout.client_dir()).expect("the client folder");        // not a copy: a test home's connection file.        std::fs::write(            layout.connection_json(),            serde_json::to_vec_pretty(&json!({                "mode": "remote", "baseUrl": "https://server.invalid",                "workspaceId": "reader-personal", "ownerId": crate::fixture::OWNER,                "connectedAt": "2026-10-18T09:00:00.000Z", "deviceScope": "reader",                "places": [{"id": crate::fixture::WORKSPACE, "name": "Household", "available": true, "unavailableSince": null}],            }))            .expect("json"),        )        .expect("the connection record");        let path = layout.replica(crate::fixture::WORKSPACE);        std::fs::create_dir_all(path.parent().expect("a parent")).expect("the replica folder");        let seeded = crate::fixture::seeded(&path);        seeded.run(            "INSERT INTO cotton_money_accounts (id, workspace_id, kind, subtype, name, currency, created_at, updated_at) VALUES ('reader-bank',?,'asset','bank','Synthetic bank','INR','2026-10-01T00:00:00.000Z','2026-10-01T00:00:00.000Z')",            &[rusqlite::types::Value::Text(crate::fixture::WORKSPACE.to_string())],        ).expect("a money account");        seeded.run(            "INSERT INTO cotton_money_transactions (id, workspace_id, account_id, occurred_on, amount_minor, direction, currency, status, created_at, updated_at) VALUES ('reader-income',?,'reader-bank','2026-10-18',4200,'in','INR','actual','2026-10-18T00:00:00.000Z','2026-10-18T00:00:00.000Z')",            &[rusqlite::types::Value::Text(crate::fixture::WORKSPACE.to_string())],        ).expect("a money movement");        cotton_store::derived::mark_rebuilt(&seeded, "a different build").expect("a stale index");        drop(seeded);        let client = controller(layout.clone());        let opened = open_other(            &layout, client.clock.as_ref(), client.random.as_ref(), client.replica_judge(),            client.receipt_signer.clone(), &client.others, &client.other_opens, &client.feeds,            Arc::clone(&client.events), crate::fixture::WORKSPACE,        ).expect("the reader opens the arrived household copy");        for _ in 0..500 {            if cotton_tools::derive::is_current(&opened.replica.lock().expect("the replica").driver).expect("the index state") {                break;            }            std::thread::sleep(std::time::Duration::from_millis(10));        }        let replica = opened.replica.lock().expect("the rebuilt copy");        assert!(cotton_tools::derive::is_current(&replica.driver).expect("the index state"));    }    fn controller(layout: Layout) -> ClientController {        ClientController::new(            layout,            Arc::new(EventBus::new()),            Some("Asia/Kolkata".to_string()),            None,        )    }    #[test]    fn a_write_on_a_phone_that_has_not_paired_says_so_rather_than_failing_oddly() {        let dir = tempfile::tempdir().expect("a temp container");        let client = controller(Layout::new(dir.path().to_path_buf()));        let error = client            .write("create_todo", &serde_json::Map::new())            .expect_err("a refusal");        assert_eq!(error, not_connected_sentence());    }    #[test]    fn a_read_on_a_phone_that_has_not_paired_says_the_same_thing() {        let dir = tempfile::tempdir().expect("a temp container");        let client = controller(Layout::new(dir.path().to_path_buf()));        let error = client            .read_tool("list_todos", &serde_json::Map::new())            .expect_err("a refusal");        assert_eq!(error, not_connected_sentence());    }    /// A phone that HAS a workspace and a file: the connection record plus the    /// synthetic replica at the build's own schema version, so `attach` finds    /// both and the write and read    /// paths run for real. Nothing real in it ever    /// ([nothing-real-ever-goes-in-cotton-s-public-tree]).    pub(crate) fn attached() -> (tempfile::TempDir, Arc<ClientController>) {        let (dir, client, _) = attached_on_a_clock();        (dir, client)    }    /// The same phone, with the clock it reads by HANDED BACK.    ///    /// A suite about a five-minute unlock has to be able to say "and then six    /// minutes later", and the only honest way to do that is to move the seam    /// the controller actually reads. `attached` is this, with the clock    /// dropped, so there is one assembly of a paired phone rather than two.    pub(crate) fn attached_on_a_clock() -> (        tempfile::TempDir,        Arc<ClientController>,        Arc<cotton_client::seams::FixedClock>,    ) {        attached_on_a_clock_in("remote")    }    /// [`attached_on_a_clock`] with the connection record in `mode` —    /// `"remote"` for a paired phone, `"local"` for one that started its own    /// database and has met no Mac.    pub(crate) fn attached_on_a_clock_in(mode: &str) -> (        tempfile::TempDir,        Arc<ClientController>,        Arc<cotton_client::seams::FixedClock>,    ) {        let dir = tempfile::tempdir().expect("a temp container");        let layout = Layout::new(dir.path());        std::fs::create_dir_all(layout.client_dir()).expect("the client folder");        // not a copy: a test home's connection file.        std::fs::write(            layout.connection_json(),            serde_json::to_vec_pretty(&json!({                "mode": mode,                // Never reached: this controller is given no transport, which                // is the state a real phone is in between pushes anyway.                "baseUrl": "https://server.invalid",                "workspaceId": crate::fixture::WORKSPACE,                "ownerId": crate::fixture::OWNER,                "connectedAt": "2026-09-08T10:00:00.000Z",            }))            .expect("json"),        )        .expect("the connection record");        let path = layout.replica(crate::fixture::WORKSPACE);        std::fs::create_dir_all(path.parent().expect("a parent")).expect("the replica folder");        let seeded = crate::fixture::seeded(&path);        // A PAIRED phone's copy holds its own device row — it arrived with the        // first pull after approval — and every write it authors is asked by        // the owner at that row.        crate::fixture::this_devices_row(&seeded);        drop(seeded);        let clock = Arc::new(cotton_client::seams::FixedClock::default_start());        let client = Arc::new(            ClientController::new(                layout,                Arc::new(EventBus::new()),                Some("Asia/Kolkata".to_string()),                None,            )            .with_seams(                Arc::clone(&clock) as Arc<dyn Clock>,                Arc::new(cotton_client::seams::SeededRandom::default()),            )            .heard_the_serving_mac(),        );        // A PAIRED phone knows the id its server admits it by — `cotton_open`        // installs it from the same identity read the transport signs with, so        // a harness that left it out would be testing an UNPAIRED phone while        // claiming to test a paired one.        client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.to_string()));        (dir, client, clock)    }    pub(crate) fn args(pairs: &[(&str, Value)]) -> serde_json::Map<String, Value> {        pairs            .iter()            .map(|(key, value)| ((*key).to_string(), value.clone()))            .collect()    }    fn todos(client: &ClientController) -> i64 {        client            .with_file(|replica| {                replica                    .driver                    .get("SELECT COUNT(*) AS n FROM cotton_todos", &[])                    .map_err(|error| error.to_string())?                    .and_then(|row| row.int("n"))                    .ok_or_else(|| "no count came back".to_string())            })            .expect("the count")    }    #[test]    fn a_tool_that_writes_is_refused_when_it_is_asked_for_as_a_read() {        // The catalogue's scope is what says which tools are reads, and this is        // what happens when that disagrees with what a handler does. It has to        // be a REFUSAL and not a quietly-dropped op list: the handler folds its        // row as it goes, so swallowing the ops would leave a row in this        // replica that no sync will ever push — a write the person made that        // silently never leaves the phone.        //        // On a device holding a copy the read runs on the READ-ONLY connection,        // so SQLite refuses at the handler's first write and the sentence still        // names the catalogue (`wrote_on_the_reader`).        let (_dir, client) = attached();        let before = todos(&client);        let error = client            .read_tool(                "create_todo",                &args(&[("title", json!("Water the plants"))]),            )            .expect_err("a read that wrote is refused");        assert!(            error.contains("catalogued as a read but wrote"),            "the refusal has to name what went wrong: {error}"        );        // AND the write is undone. A refusal that left the row behind would be        // the worse half of both outcomes.        assert_eq!(            todos(&client),            before,            "the refused write was rolled back, not merely unreported"        );        client            .with_file(|replica| {                assert_eq!(                    current_pending(replica.driver),                    Some(0),                    "nothing was left in the outbox either"                );                Ok(())            })            .expect("reads");    }    #[test]    fn a_read_tool_still_answers_normally() {        // The other half of the case above: the transaction the refusal needs        // must not make an ordinary read fail or come back empty.        let (_dir, client) = attached();        let answer = client            .read_tool("list_todos", &serde_json::Map::new())            .expect("a read answers");        assert!(answer.is_object() || answer.is_array(), "{answer}");    }    // ─────────────────────────────────────────────────────────────────────────    // The `data` event is emitted with every lock RELEASED.    // ─────────────────────────────────────────────────────────────────────────    /// What the re-entrant subscriber below reports back.    struct Reentry {        client: *const ClientController,        read_answered: std::sync::atomic::AtomicBool,    }    // Only ever handed to the callback on the SAME thread that emits, and the    // controller outlives the subscription (it is unsubscribed before the test    // ends). That is the C ABI's own contract, exercised here rather than    // assumed.    unsafe impl Send for Reentry {}    unsafe impl Sync for Reentry {}    extern "C" fn read_from_inside_the_event(        ctx: *mut std::ffi::c_void,        line: *const std::ffi::c_char,    ) {        let reentry = unsafe { &*(ctx as *const Reentry) };        let text = unsafe { std::ffi::CStr::from_ptr(line) }            .to_string_lossy()            .to_string();        if !text.contains("\"kind\":\"data\"") {            return;        }        // A screen answers a `data` event by re-reading what it invalidated.        // If `write` still held the state or replica lock here, this call would        // block for ever on a lock its own call stack holds.        let client = unsafe { &*reentry.client };        if client            .read_tool("list_todos", &serde_json::Map::new())            .is_ok()        {            reentry                .read_answered                .store(true, std::sync::atomic::Ordering::SeqCst);        }    }    /// RULE: A board write emits the board table's data event, because Home must redraw a changed face without a restart.    #[test]    fn a_board_write_invalidates_the_live_board_reader() {        extern "C" fn collect_board_event(ctx: *mut std::ffi::c_void, line: *const std::ffi::c_char) {            let seen = unsafe { &*(ctx as *const Mutex<Vec<Value>>) };            let text = unsafe { std::ffi::CStr::from_ptr(line) }.to_string_lossy();            if let Ok(event) = serde_json::from_str(&text) { seen.lock().unwrap().push(event); }        }        let (_dir, client) = attached();        let seen = Box::new(Mutex::new(Vec::<Value>::new()));        client.events.subscribe(&*seen as *const _ as *mut std::ffi::c_void, Some(collect_board_event));        let saved = client.write("update_board", &args(&[            ("id", json!("home")),            ("definition", json!({"id":"home","parts":[{"kind":"tools","face":"grid"}]})),        ]));        client.events.subscribe(std::ptr::null_mut(), None);        assert!(saved.is_ok(), "{saved:?}");        assert!(seen.lock().unwrap().iter().any(|event| event["kind"] == "data"            && event["payload"]["tables"].as_array().is_some_and(|tables| tables.contains(&json!("cotton_board_definitions")))));        let drawn = client.read_tool("get_board", &args(&[("id", json!("home"))])).unwrap();        assert_eq!(drawn["definition"]["parts"][0]["face"], "grid");    }    #[test]    fn a_subscriber_can_read_from_inside_the_data_event_without_deadlocking() {        use std::sync::atomic::Ordering;        use std::time::Duration;        let (dir, client) = attached();        let reentry = Arc::new(Reentry {            client: Arc::as_ptr(&client),            read_answered: std::sync::atomic::AtomicBool::new(false),        });        client.events.subscribe(            Arc::as_ptr(&reentry) as *mut std::ffi::c_void,            Some(read_from_inside_the_event),        );        // On a thread with a channel, so a deadlock is a FAILING test rather        // than a run that hangs until CI kills it.        let (done, waiting) = std::sync::mpsc::channel();        let writer = Arc::clone(&client);        let thread = std::thread::spawn(move || {            let answer = writer.write("create_todo", &args(&[("title", json!("Buy milk"))]));            let _ = done.send(answer.is_ok());        });        let wrote = waiting            .recv_timeout(Duration::from_secs(20))            .unwrap_or_else(|_| {                panic!(                "the write never finished: a subscriber that read from inside the `data` event \                 deadlocked against a lock the write was still holding"            )            });        thread.join().expect("the writing thread");        client.events.subscribe(std::ptr::null_mut(), None);        assert!(            wrote,            "the write itself has to succeed for this to prove anything"        );        assert!(            reentry.read_answered.load(Ordering::SeqCst),            "the subscriber never got its read in — the `data` event was not delivered"        );        drop(dir);    }    #[test]    fn the_loops_status_rides_the_client_stream_tagged_as_sync() {        // The media drain's frame carries `state` and `pending` too, and the        // two share state words — so the loop's frame is the one that says        // which it is, and a reader keys on the word rather than the shape.        let status = cotton_client::sync::SyncStatus {            state: cotton_client::sync::SyncState::Waiting,            pending: 3,            last_error: Some("the server did not answer".to_string()),            next_attempt_at: Some("2026-09-25T10:00:30.000Z".to_string()),            failures: 2,            ..cotton_client::sync::SyncStatus::default()        };        let frame = sync_status_event(&status);        assert_eq!(frame["phase"], serde_json::json!(SYNC_PHASE));        assert_eq!(frame["state"], serde_json::json!("waiting"));        assert_eq!(frame["pending"], serde_json::json!(3));        assert_eq!(frame["lastError"], serde_json::json!("the server did not answer"));        assert_eq!(frame["nextAttemptAt"], serde_json::json!("2026-09-25T10:00:30.000Z"));        assert_eq!(frame["failures"], serde_json::json!(2));        assert_eq!(frame["stoppedReason"], serde_json::Value::Null);    }    #[test]    fn a_schema_mismatch_rides_the_stream_as_a_word_and_is_absent_otherwise() {        // Home's update slip is drawn off this one word — which side is        // behind — and never off the sentence in `lastError`.        let behind = cotton_client::sync::SyncStatus {            state: cotton_client::sync::SyncState::Waiting,            schema: Some(cotton_client::sync::SchemaStanding::PhoneBehind),            ..cotton_client::sync::SyncStatus::default()        };        assert_eq!(sync_status_event(&behind)["schema"], serde_json::json!("phoneBehind"));        let mac_behind = cotton_client::sync::SyncStatus {            schema: Some(cotton_client::sync::SchemaStanding::ServerBehind),            ..cotton_client::sync::SyncStatus::default()        };        assert_eq!(sync_status_event(&mac_behind)["schema"], serde_json::json!("serverBehind"));        let level = cotton_client::sync::SyncStatus::default();        assert!(            sync_status_event(&level).get("schema").is_none(),            "no mismatch, no field — a screen one build behind reads nothing"        );    }    #[test]    fn a_stopped_loop_names_its_code_on_the_stream() {        // A screen tells a revocation (the wall) from a key mismatch (the        // banner) by the CODE, never by parsing the sentence.        let status = cotton_client::sync::SyncStatus {            state: cotton_client::sync::SyncState::Stopped,            stopped_reason: Some("the server could not verify this phone's signature".to_string()),            stopped_code: Some("device_bad_signature".to_string()),            ..cotton_client::sync::SyncStatus::default()        };        let frame = sync_status_event(&status);        assert_eq!(frame["state"], serde_json::json!("stopped"));        assert_eq!(frame["stoppedCode"], serde_json::json!("device_bad_signature"));    }    fn refused_for_good(client: &ClientController, kind: RefusalKind, code: &str) {        let memory = Arc::new(RefusalMemory::default());        memory.note(Some(DeviceRefusal {            kind,            code: code.to_string(),            server_url: Some("https://server.invalid".to_string()),            server_name: Some("study".to_string()),            at: "2026-09-25T10:00:00.000Z".to_string(),            erase: false,            refuser: cotton_client::transport::Refuser::Unnamed,            serving_epoch: None,            device: None,        }));        client.set_refusals(Some(memory));    }    #[test]    fn a_standing_terminal_refusal_turns_every_authoring_entry_away_and_moves_no_op() {        // THE GUARANTEE IS THE CORE'S. The app's banner says "nothing new is        // saved"; this is what makes it true for every path that authors —        // the tool path, the row path every `capture.*` / `dictation.create`        // / `session.*` / `settings.*` write takes, and the import path — with        // the crate's own sentence and not one op queued.        let (_guard, client) = attached();        let before = client.sync_status()["pending"].clone();        refused_for_good(&client, RefusalKind::BadSignature, "device_bad_signature");        let sentence = cotton_client::connection::terminal_device_sentence("device_bad_signature")            .expect("a sentence");        assert_eq!(client.write_refusal().as_deref(), Some(sentence.as_str()));        let refused = client            .write("create_todo", &args(&[("title", json!("Buy milk"))]))            .expect_err("the tool path is refused");        assert_eq!(refused, sentence);        let mut ran = false;        let refused = client            .write_rows("capture.create", &mut |_ctx| {                ran = true;                Ok(json!({}))            })            .expect_err("the row path is refused");        assert_eq!(refused, sentence);        assert!(!ran, "the body never runs: nothing opens a transaction");        let refused = client            .import_rows("import.whatsappExport", &[], &mut |_seams| {                ran = true;                Ok(json!({}))            })            .expect_err("the import path is refused");        assert_eq!(refused, sentence);        assert!(!ran);        assert_eq!(            client.sync_status()["pending"],            before,            "not one op queued behind a refusal"        );        // And every read still answers: the copy is the person's own.        client            .read_tool("list_todos", &serde_json::Map::new())            .expect("a read under the banner");    }    #[test]    fn a_standing_refusal_that_names_its_machine_still_erases_after_a_relaunch() {        // A note now records WHICH MACHINE refused (`Refuser`), so the name        // moving to another Mac earns one fresh attempt. None of that may        // soften a real revoke: the owner ticked "erase" on the Mac that still        // answers, and the note the phone and the Mac read back off        // `refusal.json` must still say so and still hold every write.        let (_guard, client) = attached();        let dir = tempfile::tempdir().expect("a temp dir");        let path = dir.path().join("client").join("refusal.json");        RefusalMemory::at(&path).note(Some(DeviceRefusal {            kind: RefusalKind::Revoked,            code: "device_revoked".to_string(),            server_url: Some("https://server.invalid".to_string()),            server_name: Some("study".to_string()),            at: "2026-09-28T10:00:00.000Z".to_string(),            erase: true,            refuser: cotton_client::transport::Refuser::Server("mac-a".to_string()),            serving_epoch: None,            device: None,        }));        client.set_refusals(Some(Arc::new(RefusalMemory::at(&path))));        let standing = client.standing_refusal().expect("the note outlived the launch");        assert_eq!(standing["code"], json!("device_revoked"));        assert_eq!(standing["erase"], json!(true), "the app still takes the erase unasked");        assert!(client.write_refusal().is_some(), "and nothing new is saved");    }    #[test]    fn a_refusal_that_is_not_for_good_holds_no_write() {        // A clock the person fixes is the one non-terminal kind: the loop        // retries it, and so does a write.        let (_guard, client) = attached();        refused_for_good(&client, RefusalKind::Clock, "device_clock");        assert_eq!(client.write_refusal(), None);        client            .write("create_todo", &args(&[("title", json!("Buy milk"))]))            .expect("a write under a clock hold");        // And clearing the note lets a refused device write again — the join        // that let it back in clears it (`RefusalMemory::note(None)`).        refused_for_good(&client, RefusalKind::Revoked, "device_revoked");        assert!(client.write_refusal().is_some());        client.refusals.lock().expect("the slot").as_ref().expect("a memory").note(None);        assert_eq!(client.write_refusal(), None);    }    #[test]    fn a_cold_status_read_carries_the_loop_or_says_there_is_none() {        // No runtime on this fixture, so no loop was started: the key is        // PRESENT and null, which a screen reads as "nothing in flight" and        // never as "reachable".        let (_guard, client) = attached();        let status = client.sync_status();        assert_eq!(status["connected"], serde_json::json!(true));        assert!(            status.get("loop").is_some(),            "the loop's slot is always answered: {status}"        );        assert_eq!(status["loop"], serde_json::Value::Null);    }    /// RULE: The status read and every pass's frame say where a database's sync stands in the engine's words — `line` for under the cap (empty is the people line; "syncing · N%", "offline", "update app", "copying · N MB to go" otherwise) and `sync` for the page and the device row — so no surface composes its own, and "catching up", "up to date" and counts of changes never reach a cap (sync programme, lane A, 12 Oct 2026).    #[test]    fn the_status_read_says_sync_in_the_engines_words() {        use cotton_client::sync::line::{OFFLINE, OFFLINE_AFTER_MS, UPDATE_APP};        let (_guard, client, clock) = attached_on_a_clock();        let workspace = client.sync_status()["workspaceId"]            .as_str()            .expect("the attached database")            .to_string();        let status = client.sync_status();        assert_eq!(status["line"], json!(""), "before any pass reported: the people line");        assert_eq!(status["sync"]["state"], json!("current"));        // A big catch-up: the Mac counted 40,000 owed at its start.        let behind = cotton_client::sync::Reported {            pushed: 0,            pulled: 4_000,            behind: true,            remaining: Some(10_000),            owed_at_start: Some(40_000),            unsent: 0,            handed: 0,            passed: 4_000,        };        client.say_reported(&workspace, Some(behind), None, None);        let status = client.sync_status();        assert_eq!(status["line"], json!("syncing \u{00B7} 10%"));        assert_eq!(status["lines"][&workspace], status["line"], "the same words by database id");        assert_eq!(status["sync"]["state"], json!("syncing"));        assert_eq!(status["sync"]["page"], json!("Syncing \u{00B7} 10% \u{00B7} 36,000 changes to go"));        assert_eq!(status["sync"]["percent"], json!(10));        assert_eq!(status["sync"]["toGo"], json!(36_000));        assert_eq!(status["syncs"][&workspace], status["sync"]);        assert_eq!(status["sync"]["coming"], json!(["Everything \u{00B7} 4,000 of 40,000"]));        // What each tool still has coming, once the Mac has counted by table.        let received = std::collections::BTreeMap::from([("cotton_emails".to_string(), 1_000usize)]);        let owed = std::collections::BTreeMap::from([            ("cotton_emails".to_string(), 39_000u64),            ("cotton_todos".to_string(), 1_000u64),        ]);        client.say_reported(            &workspace,            Some(cotton_client::sync::Reported { pulled: 0, passed: 0, ..behind }),            None,            Some(cotton_client::sync::TableMoves { received: &received, owed: Some(&owed) }),        );        assert_eq!(            client.sync_status()["sync"]["coming"],            json!(["Email \u{00B7} 1,000 of 39,000", "Todos \u{00B7} 0 of 1,000", "Everything else \u{00B7} up to date"])        );        // A copy of the whole file, said by the lane that carries it.        client.say_copying(&workspace, Some(400_000_000));        let status = client.sync_status();        assert_eq!(status["line"], json!("copying \u{00B7} 400 MB to go"));        assert_eq!(status["sync"]["page"], json!("Copying your database \u{00B7} 400 MB to go"));        assert_eq!(status["sync"]["bytesToGo"], json!(400_000_000u64));        client.say_copying(&workspace, None);        assert_eq!(client.sync_status()["line"], json!("syncing \u{00B7} 10%"));        // A refusal of this build is said at once; a pass that does not        // answer says nothing until a quarter of an hour has gone by with        // none that did — and the status read tells the time itself.        client.say_reported(&workspace, None, Some(cotton_client::sync::SchemaStanding::PhoneBehind), None);        assert_eq!(client.sync_status()["line"], json!(UPDATE_APP));        client.say_reported(&workspace, None, None, None);        assert_eq!(client.sync_status()["line"], json!("syncing \u{00B7} 10%"));        clock.advance(chrono::Duration::milliseconds(OFFLINE_AFTER_MS));        let status = client.sync_status();        assert_eq!(status["line"], json!(OFFLINE));        assert_eq!(status["sync"]["state"], json!("offline"));        assert!(status["sync"]["since"].is_i64(), "the page says since when: {status}");        let level = cotton_client::sync::Reported {            pushed: 0,            pulled: 3,            behind: false,            remaining: Some(0),            owed_at_start: None,            unsent: 0,            handed: 0,            passed: 3,        };        client.say_reported(&workspace, Some(level), None, None);        let status = client.sync_status();        assert_eq!(status["line"], json!(""));        assert_eq!(status["sync"]["state"], json!("current"));        assert_eq!(status["sync"]["page"], json!(""), "the page's slot is empty when current");    }    /// RULE: A pass's frame carries the standing beside the counts — `line`, `sync`, and `behindBy` for the device row — answered or not, so the sheet and the page move on the frame alone.    #[test]    fn a_passes_frame_carries_the_line_and_the_standing() {        let mut line = cotton_client::sync::line::HomeLine::default();        line.answered(            cotton_client::sync::line::Answered {                received: 500,                remaining: Some(10_000),                behind: true,                ..Default::default()            },            0,        );        let behind = cotton_client::sync::Reported {            pushed: 0,            pulled: 500,            behind: true,            remaining: Some(10_000),            owed_at_start: None,            unsent: 0,            handed: 0,            passed: 500,        };        let frame = database_sync_frame("a-database", Some(behind), &line.standing(0));        assert_eq!(frame["behindBy"], json!(10_000));        assert_eq!(frame["line"], json!("syncing \u{00B7} 0%"));        assert_eq!(frame["sync"]["state"], json!("syncing"));        line.unanswered(Some(cotton_client::sync::SchemaStanding::PhoneBehind), 0);        let unanswered = database_sync_frame("a-database", None, &line.standing(0));        assert_eq!(unanswered["line"], json!("update app"));        assert_eq!(unanswered["sync"]["state"], json!("updateApp"));        assert_eq!(unanswered["reported"], json!(false));        let status = cotton_client::sync::SyncStatus {            behind_by: Some(10_000),            ..cotton_client::sync::SyncStatus::default()        };        assert_eq!(sync_status_event(&status)["behindBy"], json!(10_000));    }    #[test]    fn sync_status_is_a_state_a_first_launch_can_draw() {        // Never a refusal: the boot gate reads this before anything has been        // paired, and a screen has to be able to draw the answer.        let dir = tempfile::tempdir().expect("a temp container");        let client = controller(Layout::new(dir.path().to_path_buf()));        let status = client.sync_status();        assert_eq!(status["connected"], serde_json::json!(false));        assert!(status["reason"].as_str().expect("a sentence").len() > 40);    }}/// Where a copy keeps when a pass last reached the server: beside its replica.fn last_pull_file(replica: &std::path::Path) -> std::path::PathBuf {    replica.with_file_name("last_pull_at")}/// Keep `at` (an ISO time) as when a pass last reached the server. A stamp that cannot be written is only said later.fn keep_last_pull(file: &std::path::Path, at: &str) {    // not a copy: when a pass last reached the server (last_pull_at).    if let Err(error) = std::fs::write(file, at) {        tracing::debug!(file = %file.display(), %error, "the last pull time could not be kept");    }}/// The kept last pull time, when one is kept and reads as a time.fn read_last_pull(file: &std::path::Path) -> Option<String> {    let at = std::fs::read_to_string(file).ok()?;    let at = at.trim();    cotton_store::protocol::js::parse_date_ms(at).map(|_| at.to_string())}#[cfg(test)]mod last_pull_kept_tests {    use super::*;    /// RULE (SYNC SEEN): when a pass last reached the server is kept beside the copy and read back on the next    /// launch, so a home says when it last synced from its first frame; what does not read as a time is not said.    #[test]    fn the_last_pull_time_is_kept_beside_the_copy_and_read_back() {        let dir = tempfile::tempdir().expect("a folder");        let file = last_pull_file(&dir.path().join("replica.db"));        assert_eq!(file, dir.path().join("last_pull_at"));        assert_eq!(read_last_pull(&file), None);        keep_last_pull(&file, "2026-11-26T07:40:00.000Z");        assert_eq!(read_last_pull(&file).as_deref(), Some("2026-11-26T07:40:00.000Z"));        std::fs::write(&file, "not a time").unwrap();        assert_eq!(read_last_pull(&file), None);    }    /// RULE (REPORT FIELDS, 26 Nov 2026): before this launch's first answer, the report says the pass that last    /// reached the server and "ok", never nothing; once the loop has an answer, the report says it.    #[test]    fn a_report_before_the_first_answer_says_the_kept_pull() {        let kept = || Some("2026-11-26T15:40:00.000Z".to_string());        let fresh = cotton_client::sync::PeerHeard::default();        assert_eq!(last_heard(Some(&fresh), kept), (Some("2026-11-26T15:40:00.000Z".into()), Some("ok".into())));        assert_eq!(last_heard(None, kept), (Some("2026-11-26T15:40:00.000Z".into()), Some("ok".into())), "a busy loop says the kept pull too");        assert_eq!(last_heard(Some(&fresh), || None), (None, None), "a phone that never reached the server says nothing");        let mut heard = cotton_client::sync::PeerHeard::default();        heard.refused("offline: no route", "2026-11-26T15:49:00.000Z");        assert_eq!(last_heard(Some(&heard), kept), (Some("2026-11-26T15:49:00.000Z".into()), Some("offline: no route".into())));    }}/// The report's last exchange and answer: the loop's last answer, or, before this launch's first, the pass that last/// reached the server (`kept`, SYNC SEEN), which answered "ok". Nothing only when neither is known.fn last_heard(peer: Option<&cotton_client::sync::PeerHeard>, kept: impl FnOnce() -> Option<String>) -> (Option<String>, Option<String>) {    match peer.and_then(|peer| peer.answered_at.clone().map(|at| (at, peer.answer.clone()))) {        Some((at, answer)) => (Some(at), answer),        None => kept().map_or((None, None), |at| (Some(at), Some("ok".to_string()))),    }}/// A waiting count map as the report carries it.fn counts_of(counts: &std::collections::BTreeMap<String, i64>) -> std::collections::BTreeMap<String, u64> {    counts.iter().filter_map(|(name, n)| Some((name.clone(), u64::try_from(*n).ok()?))).collect()}/// When the oldest write held because this phone cannot seal it (`seal_*`) was made.pub(crate) fn oldest_seal_waiting_at(waiting: &cotton_store::outbox::Waiting) -> Option<String> {    waiting.oldest_by_code.iter().filter(|(code, _)| code.starts_with("seal_")).map(|(_, at)| at.clone()).min()}/// The kit-own tables an app's kit lists (`cotton_core::kit::kit_own_tables`), laid on a local copy at its open when it/// lacks them. NEVER IN THE WAY OF THE OPEN (review of GENESIS KITS, 26 Nov 2026): a kit that does not read, or a lay/// refused (a copy with no identity yet), answers the note to write down, and the app opens; the next open tries again.pub(crate) fn lay_kit_tables_at_open(driver: &cotton_store::Driver, root: &std::path::Path, now: chrono::DateTime<chrono::Utc>) -> Option<String> {    let kit_tables: Vec<String> = match cotton_core::kit::AppKit::at(root) {        Ok(kit) => kit.map(|kit| kit.tables).unwrap_or_default().into_iter().filter(|id| cotton_core::kit::kit_own_tables().any(|own| own == id)).collect(),        Err(error) => return Some(format!("the app kit did not read, so no kit table was laid at this open: {error}")),    };    if kit_tables.is_empty() {        return None;    }    cotton_tools::kit::lay_kit_tables(driver, now, Arc::new(cotton_tools::random::SystemRandom), None, &kit_tables)        .err()        .map(|failure| format!("the kit's own tables were not laid at this open; the app opens and the next open tries again: {}", failure.0))}