Cotton code
1686 lines · 79.5 KB · RustRaw
//! What `cotton_open` builds and `cotton_close` drops: the runtime, the event//! stream, the data directory, and the server's state.//!//! Design M2. One multi-threaded tokio runtime lives here for the life of the//! app; `cotton_call` is `block_on` of a bounded piece of work and is always//! called off the main thread from Swift.//!//! **ONE `OpenConfig`, TWO MODES** (H1). What used to be two `#[cfg]`-gated//! structs — a Mac's with `home` and a phone's with `containerPath` — is one//! struct whose [`OpenMode`] says which kind of process this is. A host opens//! the data directory a Mac has to be talked out of an iCloud folder for and//! runs the server in-process; a phone opens the app group's container and//! holds a replica. The WIRE JSON is unchanged, so neither app's open call moved.use std::path::PathBuf;use std::sync::Arc;use cotton_client::data_dir::{prepare_locked_data_dir, LockedDataDirError, PrepareOps};use cotton_client::{    identity_storage_for, load_or_mint_rehearsal_seed, DeviceIdentity, IdentityStorage, Layout,    REHEARSAL_MARK,};use serde::{Deserialize, Serialize};use crate::events::{EventBus, EventKind};use crate::shell::client::ClientController;use crate::shell::log_ring::LogRing;/// What kind of process this is, and where its file lives.////// The two are DIFFERENT QUESTIONS, which is why this is an enum rather than a/// bag of optional paths. A Mac has to be talked out of an iCloud folder, adopt/// an older directory once, and say so in the log; and it may mint a rehearsal/// identity beside a scratch database. A phone is HANDED its container by iOS:/// there is no other place the file could be, nothing can move it, no refusal/// it could carry, and the Keychain is the whole of its identity story.#[derive(Debug, Clone, PartialEq, Eq)]pub enum OpenMode {    /// A machine that HOLDS the database: the server runs inside this process    /// and every `read.*` / `write` runs over the file it serves.    Host {        /// The person's home folder. Swift reads it from the OS and passes        /// it, so every rule below stays pure and a test can pin it.        home: String,        /// `COTTON_MAC_DATA_DIR`, when it is set.        data_dir_override: Option<String>,        /// Whether to run the data directory's refusals and its one-time        /// adoption. Always true in the app; a test that has already prepared        /// a directory says false.        prepare_data_dir: bool,        /// What this machine calls itself. Passed in rather than read here,        /// so `machine_name` stays pure and a test can pin it. It labels the        /// machine that IMPORTED a row (`meta.source.device`).        hostname: Option<String>,        /// True inside a signed app bundle. It decides ONE thing — where the        /// device seed lives — and it is false for `swift run` and for every        /// test.        packaged: bool,        /// The bundle version and build for move bookings, separate from app_version.        app_build_label: Option<String>,        /// The address the server listens on. Absent is every interface: the        /// Mac app's phone reaches it over the LAN. A headless `serve` names        /// loopback unless told otherwise, so a development server is not        /// open to the network it happens to sit on.        bind_host: Option<String>,    },    /// A device that holds a REPLICA of a file served elsewhere.    Phone {        /// THE DATA DIRECTORY, handed down whole — a folder in the app's OWN        /// container (`PhoneDataDirectory` in CottonKit), never the app        /// group's: iOS kills a suspended app that holds a lock on a file in a        /// shared container (0xDEAD10CC), and the replica is always open. The        /// extensions never read it. No default: there is no rule this        /// core could apply to guess a container path.        container_path: String,        /// The app group's container, which held the data directory before        /// 6 Oct 2026: the folder the media rows' paths name on a phone that        /// has not yet recorded one (`follow_data_dir`).        previous_container_path: Option<String>,    },}/// What Swift hands down at open.////// The wire shape is [`OpenConfigWire`] — the same camelCase keys both apps/// have always sent, with `deny_unknown_fields` so a newer app against an/// older core fails loudly on the way in rather than having a setting silently/// ignored. `home` names a host and `containerPath` a phone; a config naming/// both, neither, or a host's field beside a container is refused BY NAME in/// [`OpenConfig::try_from`], which is where the two structs became one.#[derive(Debug, Clone, Deserialize)]#[serde(try_from = "OpenConfigWire")]pub struct OpenConfig {    pub mode: OpenMode,    /// The app's own version, for the status a menu bar draws.    pub app_version: Option<String>,    /// THE DEVICE'S OWN IANA ZONE, read by Swift (`TimeZone.current.identifier`    /// on the phone; the Mac's, read BEFORE anything pinned this process to    /// UTC). Calendar arithmetic takes an explicit zone; a host that guessed    /// would file somebody's Tuesday on Monday night.    ///    /// On the phone it is the whole of what a banding read bands by: a mood's    /// day, a journal day and every "today" the app draws are the DEVICE's    /// calendar day, so the reader takes its zone from the same place the    /// writer already stamps one from. Absent is a NAMED state and never UTC —    /// see `ClientController::time_zone`.    pub time_zone: Option<String>,    /// THE DEVICE SEED, base64url, read out of the Keychain by Swift (design    /// M8). Absent on an unpackaged host with an overridden data directory,    /// which mints a rehearsal one beside the synthetic database; absent    /// anywhere else means this device has no identity, which is a NAMED    /// state — a Mac's server starts with no root device to admit a first    /// phone with until one arrives, and a phone pairs before it can read or    /// write anything.    pub device_secret: Option<String>,    /// THIS MAC'S VAULT PRIVATE KEY, base64url, 32 bytes — the X25519 half that    /// unwraps the workspace's vault master key (spec §7.1,    /// Cotton note "The vault — the honest sentence").    ///    /// Read out of the Keychain by Swift beside the device seed, and **guarded    /// by the login session rather than by biometry**: the server opens an    /// assistant's API key with nobody at the keyboard, and the placement    /// applier writes a file into a build nobody is watching. The reveal screen    /// on the Mac asks for Touch ID before it reads the item, which is a    /// courtesy the SCREEN performs and not an access control the key carries.    ///    /// A HOST field only. A phone never sends one: its vault key is guarded by    /// presence and crosses per call, as `vault.unlock`'s parameter, so that    /// nothing holds it between two reveals.    pub vault_secret: Option<String>,    /// **WHICH APP THIS IS** — CottonDB or Cotton Dev (`cotton_core::flavor`),    /// read by Swift out of the bundle (`CottonFlavor`) and sent as `flavor`.    ///    /// Absent, blank or misspelt is Cotton Dev: a build that forgot to say    /// lands on the side that cannot reach the real household. It decides the    /// Mac's data folder (`~/CottonDB` or `~/CottonDev`) and refuses the other    /// app's; `cotton_open` declares it for the whole process, which is what    /// every relay-name seam reads. Both modes carry it: a phone's container    /// is already its bundle's own, but which households it may JOIN is not.    pub flavor: cotton_core::flavor::Flavor,    /// **WHICH BUSINESS APP THIS IS**, when it is one: the app bundle's    /// `flavour.json` (`FlavourManifest.swift`), sent as `manifest` exactly as    /// the bundle carries it. Absent is Cotton. Kept whole here; the core's    /// reading of it is the manifest schema's.    pub manifest: Option<serde_json::Value>,}/// Whether a manifest is one of Cotton's own apps, by its own word: one that/// founds Personal (`genesis` "personal", the default Swift's FlavourManifest/// writes when the file says none) keeps the build's real/dev identity; one that/// founds nothing (`genesis` "none", a business app) opens as a business/// (`Flavor::Business`). Never a list of flavours: a new app is Cotton's own the/// moment its manifest says so (Books once opened as a business, "missing field/// `slug`", until a list here named it).fn founds_personal(manifest: &serde_json::Value) -> bool {    manifest.get("genesis").and_then(serde_json::Value::as_str).is_none_or(|genesis| genesis == "personal")}/// The JSON as it crosses the boundary — every key optional, so that WHICH/// keys are present can say what this process is.#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]struct OpenConfigWire {    home: Option<String>,    container_path: Option<String>,    previous_container_path: Option<String>,    data_dir_override: Option<String>,    app_version: Option<String>,    app_build_label: Option<String>,    bind_host: Option<String>,    prepare_data_dir: Option<bool>,    hostname: Option<String>,    time_zone: Option<String>,    packaged: Option<bool>,    device_secret: Option<String>,    vault_secret: Option<String>,    flavor: Option<String>,    manifest: Option<serde_json::Value>,}impl TryFrom<OpenConfigWire> for OpenConfig {    type Error = String;    fn try_from(wire: OpenConfigWire) -> Result<Self, String> {        if wire.home.is_some() && wire.previous_container_path.is_some() {            return Err("previousContainerPath is a phone's; this config names a host's `home`".into());        }        let mode = match (wire.home, wire.container_path) {            (Some(_), Some(_)) => {                return Err("a config names `home` (a host) or `containerPath` (a phone), never \                            both"                    .to_string())            }            (None, None) => {                return Err(                    "a config names `home` (a host) or `containerPath` (a phone); this one names \                     neither"                        .to_string(),                )            }            (Some(home), None) => OpenMode::Host {                home,                data_dir_override: wire.data_dir_override,                prepare_data_dir: wire.prepare_data_dir.unwrap_or(true),                hostname: wire.hostname,                packaged: wire.packaged.unwrap_or(false),                app_build_label: wire.app_build_label,                bind_host: wire.bind_host,            },            (None, Some(container_path)) => {                // A host's fields beside a container are refused by name: a                // phone has no home folder to override under, no machine name                // that labels an import, and no unpackaged build with a                // rehearsal seed. Silently ignoring one would be the setting                // `deny_unknown_fields` exists to refuse.                let stray = [                    ("dataDirOverride", wire.data_dir_override.is_some()),                    ("prepareDataDir", wire.prepare_data_dir.is_some()),                    ("hostname", wire.hostname.is_some()),                    ("packaged", wire.packaged.is_some()),                    ("appBuildLabel", wire.app_build_label.is_some()),                    ("bindHost", wire.bind_host.is_some()),                    // The vault key is the MAC's, held for the process's life                    // because the server and the placement applier run                    // unattended. A phone's crosses per call behind Face ID and                    // is never held, so a phone sending one here is a build                    // that has confused the two and is told so.                    ("vaultSecret", wire.vault_secret.is_some()),                ]                .into_iter()                .filter_map(|(name, present)| present.then_some(name))                .collect::<Vec<_>>();                if !stray.is_empty() {                    return Err(format!(                        "{} {} a host's, and this config names a phone's `containerPath`",                        stray.join(", "),                        if stray.len() == 1 { "is" } else { "are" }                    ));                }                OpenMode::Phone {                    container_path,                    previous_container_path: wire.previous_container_path,                }            }        };        Ok(OpenConfig {            mode,            app_version: wire.app_version,            time_zone: wire.time_zone,            device_secret: wire.device_secret,            vault_secret: wire.vault_secret,            flavor: if wire.manifest.as_ref().is_some_and(|manifest| !founds_personal(manifest)) { cotton_core::flavor::Flavor::Business } else { cotton_core::flavor::Flavor::from_declared(wire.flavor.as_deref()) },            manifest: wire.manifest,        })    }}/// Why `cotton_open` refused. Carried out through `out_error` as one JSON/// object, so Swift can put a title and a message in an alert without parsing a/// sentence.#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct OpenError {    pub code: String,    pub title: String,    pub message: String,}impl OpenError {    pub fn new(code: &str, title: &str, message: impl Into<String>) -> Self {        Self {            code: code.to_string(),            title: title.to_string(),            message: message.into(),        }    }}fn process_holder() -> Result<cotton_store::process_lock::Holder, OpenError> {    cotton_store::process_lock::Holder::current(chrono::Utc::now().to_rfc3339())        .map_err(|error| OpenError::new("folder_lock_failed", "CottonDB could not lock its folder", error.to_string()))}fn process_lock_error(error: cotton_store::process_lock::LockError) -> OpenError {    let (code, title) = match &error {        cotton_store::process_lock::LockError::Held { .. } => ("folder_in_use", cotton_store::process_lock::HELD_TITLE),        _ => ("folder_lock_failed", "CottonDB could not lock its folder"),    };    OpenError::new(code, title, error.message())}fn claim_folder(path: &std::path::Path) -> Result<Arc<cotton_store::process_lock::ProcessLock>, OpenError> {    cotton_store::process_lock::ProcessLock::claim(path, process_holder()?).map_err(process_lock_error)}/// Where the server is. In 3a it is always `Stopped` — nothing starts a server/// yet — and 3b fills it in; the SHAPE is settled now because the menu bar draws/// exactly these four states.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pub enum ServerPhase {    Stopped,    Starting,    Running,    Error,}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct ServerStatus {    pub state: ServerPhase,    /// The BOUND port, never the configured one — `PORT=0` is legal and the    /// address is what the listener actually took.    pub port: Option<u16>,    pub tunnel_port: Option<u16>,    /// The sentence to show when `state` is `error`.    pub error: Option<String>,}impl Default for ServerStatus {    fn default() -> Self {        Self {            state: ServerPhase::Stopped,            port: None,            tunnel_port: None,            error: None,        }    }}/// How this install's device identity was found.#[derive(Debug, Clone, PartialEq, Eq)]pub struct IdentityRead {    pub device_id: Option<String>,    /// `keychain`, `rehearsal-file`, or `none`.    pub source: &'static str,    /// True the one time a rehearsal seed was minted.    pub minted: bool,    /// Why there is no device id, when there is none.    pub reason: Option<String>,}/// How long a close waits for the server and the replica to stop.////// **The bounds are a LADDER, and each rung is wider than the one inside it**,/// so the innermost deadline is the one that fires and the outer ones only/// catch what it could not: `cotton_server::start::STOP_TIMEOUT` (20 s) bounds/// the worker join, this bounds the whole quiesce, [`RUNTIME_SHUTDOWN_TIMEOUT`]/// bounds what is left on the blocking pool, and `CottonRuntime.closeTimeout`/// in Swift (45 s) sits outside the sum of the two. A rung narrower than the/// one inside it would report the wrong step.pub const QUIESCE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);/// How long the runtime's blocking pool gets after everything has been told to/// stop, before what is left is the operating system's problem.////// Short, because by here nothing SHOULD be running: a closure still going past/// this is one that ignored a stop it was already told about.pub const RUNTIME_SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);/// How long a shared core's close waits for a control request already/// running to let go of it ([`CottonHandle::close_shared`]). The outermost/// rung but Swift's: 5 s + the quiesce + the runtime stays under its 45 s.pub const SHARED_RELEASE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);/// The live core, behind the opaque pointer Swift holds.pub struct CottonHandle {    runtime: tokio::runtime::Runtime,    events: Arc<EventBus>,    data_dir: PathBuf,    _process_lock: Arc<cotton_store::process_lock::ProcessLock>,    layout: Layout,    app_version: String,    log: Arc<LogRing>,    /// The CLIENT half (design M6): the replica, the ingest queue and the sync    /// loop — or, on a serving Mac, the file the server holds open. An `Arc`    /// for the same reason the server is one — a long job is spawned onto the    /// runtime and has to outlive the borrow that started it.    client: Arc<ClientController>,    identity: IdentityRead,    /// The three long-running commands' state — one join and one bootstrap at a    /// time, and where each got to for a screen that missed an event.    commands: Arc<crate::phone::commands::Commands>,    /// Every session terminal this device has open, and the reader thread    /// behind each one.    ///    /// On the handle because a terminal outlives the call that opened it: the    /// bytes arrive as events for as long as the tab is up, and `cotton_close`    /// is what ends them. Empty on a device nobody has opened one on, which is    /// every device most of the time.    terminals: Arc<cotton_client::session_host::TerminalHub>,    /// Which app identity opened this core: a development-only method    /// (`developer.*`) answers only in Cotton Dev.    flavor: cotton_core::flavor::Flavor,    /// Which of Cotton's own cards this app's fan holds beside the tools    /// (the manifest's `fan`), for `shell.fan`.    fan: cotton_core::flavor::FanCards,    /// Where the gate's wait stands, for `shell.home`.    home: Arc<crate::methods::shell_home::Watch>,    /// The app's own name, off the manifest it opened with (`shell.home`'s    /// words).    app_name: String,    /// The app's slug, its manifest's `flavour` (`notes`, `books`), `cotton`    /// for Cotton with none: what a shaken report says it came from.    app_slug: String,    /// THIS HANDLE, AS THE `Arc` IT IS HELD IN — set once by [`Self::shared`],    /// which is how the app's FFI holds it. Weak, or the handle would own    /// itself. The control socket needs it: a verb a shell sends runs a    /// method, and a method runs on the handle, from a thread of its own.    /// Empty on a handle nobody shared (a test's local, the headless binary,    /// which binds its own socket), and then [`Self::bind_control`] binds none.    me: std::sync::OnceLock<std::sync::Weak<CottonHandle>>,    /// Whether Story is reading a script file in (`story.bring_in`) right    /// now: one at a time, so a second tap on Bring in is refused, never a    /// second copy of the same script.    story_bringing: std::sync::atomic::AtomicBool,}impl std::fmt::Debug for CottonHandle {    /// The folder and the server's state, never the runtime or the event    /// stream: a `{:?}` of a core is something a log line holds.    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        let mut fields = f.debug_struct("CottonHandle");        fields.field("data_dir", &self.data_dir);        fields.finish_non_exhaustive()    }}/// The sentence a host-mode open answers on a build that carries no server.pub const NO_SERVER_IN_THIS_BUILD: &str =    "this build carries no server, so it cannot open as a host — it is the client build the \     iPhone links; pass `containerPath`, or build with the `host` feature";/// Whether `CottonHandle::open` starts the handle's background work: the/// session-host loop, the vault's first pass — and the/// process-wide `tracing` sink pointed at this handle's bus.////// `Quiet` lets a test control startup, including what a fresh handle/// buffered. Each of those four writes lines into the buffer on its own clock/// (a session host that cannot dial its helper notes it; the tracing sink/// carries every PARALLEL test's server lines to the last bus attached), so a/// count taken with them on is a count of a race — CI run 360 saw 5 where the/// handle itself had said 1 (todo dd754230).#[derive(Clone, Copy, PartialEq, Eq, Debug)]enum Background {    Start,}enum LocalSourceHome {    MachineHome,}/// The home definition an app's manifest carries, declared for the process/// (`cotton_tools::presentation::declare_home`). None is the shipped Home —/// Cotton's own manifest names Personal and no Home; every business manifest/// names one, held by its file's guards (`business_home.rs`).fn business_home(manifest: &serde_json::Value) -> Result<(), String> {    match manifest.get("home") {        None => Ok(()),        Some(home) => cotton_tools::presentation::declare_home(home),    }}impl CottonHandle {    /// Prepare the data directory, then build the runtime.    ///    /// The order is the Electron shell's, and it is the point: the data    /// directory's refusals run before anything opens a file, because a refusal    /// that arrives after a file is open is not a refusal.    pub fn open(config: OpenConfig) -> Result<Self, OpenError> {        // This core's age, for a copy shared by several apps on one phone (copy_keep::core_built).        cotton_client::copy_keep::set_core_built(env!("COTTON_BUILD_COMMIT_TIME").parse().unwrap_or(0));        Self::open_with(config, Background::Start)    }    /// `open`, saying whether the handle's background work starts with it.    /// Every caller outside a test starts it; `Background::Quiet` is the    /// test's seam — see [`Background`].    fn open_with(config: OpenConfig, background: Background) -> Result<Self, OpenError> {        Self::open_with_sources(config, background, LocalSourceHome::MachineHome)    }    fn open_with_sources(        config: OpenConfig,        background: Background,        sources: LocalSourceHome,    ) -> Result<Self, OpenError> {        // Everything it gates is the host's; the client build has none of it.        #[allow(unused_variables)]        let start = background == Background::Start;        let events = Arc::new(EventBus::new());        // An app's Home is its manifest's (owner, 19 Oct 2026): held for the        // process before any board is read; a manifest naming none draws the        // shipped Home, and one naming a board this build cannot draw is a        // broken build, said at open.        if let Some(manifest) = &config.manifest {            business_home(manifest)                .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        }        // Whether this app syncs at all (the manifest's `sync`): a word that        // is not true or false is a broken build, said at open.        let syncs = if config.manifest.is_none() && config.flavor == cotton_core::flavor::Flavor::Business {            cotton_core::flavor::business_manifest().map(|manifest| manifest.sync)        } else { cotton_core::flavor::syncs(config.manifest.as_ref()) }            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        // Served is the manifest's sync (architect, 22 Oct 2026): what a        // definition shows only to a served app asks this process-wide fact.        cotton_core::flavor::declare_serving(syncs);        // Which Settings rows this app can use (a row's `needs`), from its manifest.        cotton_tools::presentation::declare_settings_reach(            config.manifest.as_ref().map_or(cotton_tools::presentation::SettingsReach::EVERY, cotton_tools::presentation::SettingsReach::of));        // Which database this app shows (`shell::scope`), read before anything        // is held: a word it does not know is a broken build, never "every".        let genesis = if config.manifest.is_none() && config.flavor == cotton_core::flavor::Flavor::Business {            cotton_core::flavor::business_manifest().map(|manifest| manifest.genesis)        } else { cotton_core::genesis::Genesis::of(config.manifest.as_ref()) }            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", reason))?;        // The genesis set: the manifest's `tools`, which every database this        // app founds is born with (architect, 22 Oct 2026). A tool this build        // does not have is a broken manifest, said at open.        let genesis_tools = if config.manifest.is_none() && config.flavor == cotton_core::flavor::Flavor::Business {            cotton_core::flavor::business_manifest()                .and_then(|manifest| cotton_core::genesis::GenesisTools::checked(manifest.tools.clone()))        } else { cotton_core::genesis::GenesisTools::of(config.manifest.as_ref()) }            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        // The kit this app keeps to (`kit::AppKit`): none is the whole object.        let app_kit = cotton_core::kit::AppKit::of(config.manifest.as_ref())            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        // The dial's own cards (the manifest's `fan`): a fan that does not        // read is a broken build, said at open.        let fan = if config.manifest.is_none() && config.flavor == cotton_core::flavor::Flavor::Business {            cotton_core::flavor::business_manifest().map(|manifest| manifest.fan.clone())        } else { cotton_core::flavor::FanCards::of(config.manifest.as_ref()) }            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        let scope = crate::shell::scope::DatabaseScope::of(config.manifest.as_ref())            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        // The app's own name, off the manifest it opened with. Cotton's own        // apps (Cotton, Books, Music, Cinemas, Rigby) open as real or dev,        // never as a declared business, so the business manifest is not        // theirs to read: read there, Cotton Cinemas 1.0 (1) found no        // manifest and opened on the old Start screen (6 Nov 2026).        let app_name = match &config.manifest {            Some(manifest) => manifest.get("name").and_then(serde_json::Value::as_str).unwrap_or_default().to_string(),            None if config.flavor == cotton_core::flavor::Flavor::Business => cotton_core::flavor::business_manifest()                .map(|manifest| manifest.name.clone())                .unwrap_or_default(),            None => String::new(),        };        let app_slug = config            .manifest            .as_ref()            .and_then(|manifest| manifest.get("flavour"))            .and_then(serde_json::Value::as_str)            .filter(|slug| !slug.trim().is_empty())            .unwrap_or("cotton")            .to_string();        // A host that cannot serve is not a host. Refused HERE, by name, on the        // build that has no `cotton-server` — rather than opening a Mac-shaped        // data directory that no method could ever start a server over.        if matches!(config.mode, OpenMode::Host { .. }) {            return Err(OpenError::new(                "no_server_in_this_build",                "This build cannot hold a database",                NO_SERVER_IN_THIS_BUILD,            ));        }        // WHERE THE FILE LIVES, decided by the MODE because the question is        // different. A Mac has to be talked out of an iCloud folder, adopt an        // older directory once, and say so in the log. A phone is HANDED its        // container by iOS: there is no other place it could be, nothing can        // move it, and no refusal it could carry.        let mut phone_data_dir_note: Option<String> = None;        let (data_dir, process_lock) = match &config.mode {            OpenMode::Host {                home,                data_dir_override,                prepare_data_dir: true,                ..            } => {                let sink = Arc::clone(&events);                let ops = PrepareOps::system().with_log(move |line| sink.log(line));                match prepare_locked_data_dir(                    config.flavor,                    std::path::Path::new(home),                    data_dir_override.as_deref(),                    &ops,                    process_holder()?,                ) {                    Ok(owned) => owned,                    Err(LockedDataDirError::Lock(error)) => return Err(process_lock_error(error)),                    Err(LockedDataDirError::Refused(refusal)) => {                        return Err(OpenError::new(                            "data_dir_refused",                            &refusal.title,                            refusal.message,                        ))                    }                }            }            OpenMode::Host {                home,                data_dir_override,                prepare_data_dir: false,                ..            } => {                let home = std::path::Path::new(home);                let data_dir = cotton_client::data_dir::resolve_data_dir(                    config.flavor,                    home,                    data_dir_override.as_deref(),                )                .path;                // NOT PREPARING IS NOT ADMITTING: the other app's folder is                // refused here too (`cotton_core::flavor`), because skipping                // the adoption and the synced-folder checks says nothing about                // whose folder this is.                if let Some(refusal) =                    cotton_client::data_dir::foreign_folder_refusal(config.flavor, home, &data_dir)                {                    return Err(OpenError::new(                        "data_dir_refused",                        &refusal.title,                        refusal.message,                    ));                }                let lease = claim_folder(&data_dir)?;                (data_dir, lease)            }            OpenMode::Phone {                container_path,                previous_container_path,            } => {                let data_dir = PathBuf::from(container_path);                // Created here rather than assumed: the app group's container                // exists, but the folder inside it is ours and a first launch                // has never made it. A refusal here is the real one — a                // container the app cannot write is an entitlement that did                // not take, and it should say so at open rather than at the                // first write.                std::fs::create_dir_all(&data_dir).map_err(|error| {                    OpenError::new(                        "container_unwritable",                        "Cotton cannot reach its own storage",                        format!("{} could not be created ({error}).", data_dir.display()),                    )                })?;                let lease = claim_folder(&data_dir)?;                // Before anything opens a replica: the media rows name files                // by absolute path, and this folder may not be the one they                // were written under. A failure is logged and the open goes on                // — a stale path reads as a file not yet downloaded.                if let Err(error) = cotton_client::data_dir::follow_data_dir(                    &data_dir,                    previous_container_path.as_deref().map(std::path::Path::new),                ) {                    phone_data_dir_note =                        Some(format!("data dir: media paths not rewritten ({error})"));                }                (data_dir, lease)            }        };        let layout = Layout::new(data_dir.clone());        genesis.keep(layout.root())            .and_then(|()| genesis_tools.keep(layout.root()))            .and_then(|()| cotton_core::kit::AppKit::keep(app_kit.as_ref(), layout.root()))            .map_err(|reason| OpenError::new("manifest_unwritten", "This app could not keep its manifest", reason))?;        // The ring AND the file, from the first line: `server.log` is where an        // operator reads a run that has already ended, and `datadir.status`        // names that path. A ring with no file behind it is what left the        // window's log unreadable from anywhere but the window — which has no        // page for it either.        let log = Arc::new(LogRing::to_file(            crate::shell::log_ring::LOG_RING_SIZE,            layout.server_log(),        ));        let runtime = tokio::runtime::Builder::new_multi_thread()            .enable_all()            .thread_name("cotton-core")            .build();        let runtime = runtime.map_err(|error| {            OpenError::new(                "runtime_failed",                "CottonDB could not start",                format!("The app could not start its background workers ({error})."),            )        })?;        // WHO THIS DEVICE IS, decided once at open — before anything starts,        // so a server's first boot already has a root device to write. A host        // has three places to look; a phone has the Keychain and nothing else.        let identity = match &config.mode {            OpenMode::Host {                packaged,                data_dir_override,                ..            } => read_identity(                &layout,                *packaged,                data_dir_override.as_deref(),                config.device_secret.as_deref(),            ),            OpenMode::Phone { .. } => read_keychain_identity(config.device_secret.as_deref()),        };        if let Some(reason) = &identity.reason {            events.log(reason.clone());        }        if let Some(note) = phone_data_dir_note {            events.log(note);        }        // AND THE KEY THAT IS NOT THIS MAC'S, if it is still lying there.        if matches!(config.mode, OpenMode::Host { .. }) {            if let Some(note) = legacy_device_key_note(&layout) {                events.log(note);            }        }        // Read once: the server's own facts and the label every imported row        // carries as `meta.source.device` are the same machine's name. `None`        // on a phone, which imports nothing off its own disk.        let machine = match &config.mode {            OpenMode::Host { home, hostname, .. } => Some(crate::shell::client::MachineSources {                device: hostname.clone().unwrap_or_else(|| "mac".to_string()),                home: PathBuf::from(home),            }),            OpenMode::Phone { .. } => None,        };        // The client attaches LAZILY: a device nobody has connected yet has no        // workspace and no replica, and that is the ordinary state of a fresh        // install rather than a reason to refuse to open.        let machine = match sources {            LocalSourceHome::MachineHome => machine,        };        let client = ClientController::new(            layout.clone(),            Arc::clone(&events),            // THE DEVICE'S OWN ZONE, straight through. Every banding read the            // phone makes (`read.home`, `read.mood`, `read.memoryReview`) draws            // the DEVICE's calendar day, which is what `record_mood`'s            // `timezone` argument already stamps on the way in — so the reader            // and the writer take it from one place, and a check-in tapped at            // half past midnight cannot be written to tomorrow and then            // filtered out of today.            config.time_zone.clone(),            machine,        );        client            .declare_flavor(config.flavor)            .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        if scope == crate::shell::scope::DatabaseScope::Every {            crate::shell::scope::keep(&layout, &scope)                .map_err(|reason| OpenError::new("scope_unwritten", "This app could not keep its databases", &reason))?;        } else {            client                .limit_to(scope)                .map_err(|reason| OpenError::new("scope_unwritten", "This app could not keep its databases", &reason))?;        }        if !syncs {            client                .without_sync()                .map_err(|reason| OpenError::new("manifest_refused", "This app's manifest is broken", &reason))?;        }        let client = Arc::new(client);        // Published databases (cities, holidays, airports, words) are read        // through this client's signed-in door (`phone::published_reader`).        cotton_store::published::install(Some(Arc::new(crate::phone::published_reader::PhoneReader::new(&client))));        // THE ID THE SERVER ADMITS THIS DEVICE BY, on EVERY build — a phone's        // as much as a Mac's, because it is what `cotton_vault_keys` files a        // device's wrap under (`shell/client.rs`, `self_device_id`). The        // AUTHOR id on the replica is a different id answering a different        // question and is never this one.        client.set_self_device_id(identity.device_id.clone());        // THE DEVICE KEY, once: it signs this device's tool calls and receipts.        let signing = config            .device_secret            .as_deref()            .filter(|value| !value.is_empty())            .and_then(|encoded| {                use base64::engine::general_purpose::URL_SAFE_NO_PAD;                use base64::Engine;                URL_SAFE_NO_PAD.decode(encoded).ok()            })            .and_then(|bytes| DeviceIdentity::from_secret(&bytes).ok())            .map(Arc::new);        let tool_signer = signing.as_ref().map(|identity| {            let identity = Arc::clone(identity);            cotton_tools::mcp::dispatch::ToolSigner {                author: cotton_core::definitions::ToolAuthor {                    device: identity.device_id(),                    name: "This device".to_string(),                },                sign: Arc::new(move |payload| Ok(identity.sign(payload))),            }        });        client.set_tool_signer(tool_signer.clone());        // AND IT SIGNS EVERY RECEIPT THIS DEVICE MINTS (keys slice KS1): the        // replicas' writers and, on a Mac, the server's own.        if let Some(identity) = &signing {            let signer: Arc<dyn cotton_store::signed::ReceiptSigner> = identity.clone();            client.set_receipt_signer(Arc::clone(&signer));        }        // THE COMMANDS' STATE: a phone's copy gate reads whether a whole-file        // copy was just refused off it.        let commands = Arc::new(crate::phone::commands::Commands::default());        // THE RUNTIME THE PULL SCHEDULE RUNS ON, for every phone. A phone on        // the owner's personal object reaches its one peer through        // `personal.connect` (`phone/personal_object.rs`); a business app's        // cache syncs through `phone/business.rs`.        client.set_runtime(Some(runtime.handle().clone()));        drop(signing);        // THE LADDER'S SCREEN, on the path that had none. A launch with an        // existing file runs the whole migration ladder inside the        // controller's `attach`, and until this was installed it ran with        // `on_migration: None` — so `migrate.status` answered `{running:        // false}` through a real ladder run and the boot gate held on a blank        // screen for however long the steps took. Built before the handle        // because both halves are needed to wire it: the commands own the        // progress the screen reads, the events are what a live screen is        // subscribed to.        {            let noting = Arc::clone(&commands);            let emitting = Arc::clone(&events);            client.set_migration_reporter(Some(Arc::new(move |step| {                let said = crate::phone::commands::migration_json(&step);                noting.note_migration(step);                emitting.emit(EventKind::Client, said);            })));        }        // THIS DEVICE'S VAULT KEY, INTO EVERY DATABASE IT HOLDS — every build,        // a phone included. Each database has its own vault, so one admitted        // (or taken by the server) after the launch's publish is owed the key        // on its first pass, and a refused publish is asked again on the next.        // Nothing is written once every database holds it.        //        // OFF THE CALLER'S STACK, ONE AT A TIME. The hook is called from the        // loop's status listener, and the loop publishes a status while its        // caller holds the controller's locks — `attach` holds the replica slot        // as it starts the loop, a write's wake holds the loop's slot. The        // publish is a write, which takes both: run in place, it waited on a        // lock its own stack held, and every machine that serves nothing (a        // phone, a joined Mac) hung on the attach after its first fill. So it        // runs on its own thread, and a call while one runs is dropped — the        // next idle pass asks again.        {            let publishing = Arc::downgrade(&client);            let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));            client.set_after_pass(Arc::new(move || {                // The pictures sweep, on its own thread and with its own                // turn: a phone on the personal object fetches the                // thumbnails its copy now names (`phone::media_sweep`).                if let Some(client) = publishing.upgrade() {                    crate::phone::media_sweep::kick(&client);                    // And the captures UP: a pass ended, so the drain comes                    // round now rather than on its minute.                    client.wake_media_drain();                }                if busy.swap(true, std::sync::atomic::Ordering::SeqCst) {                    return;                }                let publishing = publishing.clone();                let done = Arc::clone(&busy);                let spawned = std::thread::Builder::new()                    .name("cotton-vault-publish".to_string())                    .spawn(move || {                        if let Some(client) = publishing.upgrade() {                            if let Some(Err(refusal)) = crate::phone::vault::publish_owed(&client) {                                tracing::warn!(                                    "vault: this device could not publish its key — {}. It will \                                     ask again on the next pass.",                                    refusal.message                                );                            }                            // A wrap the object holds for this device's own key under an                            // older row id (a founding made before sign-in) is taken here,                            // so the parked collision heals on the pull that brought it.                            if let Err(refusal) = crate::phone::vault::take_own_key(&client) {                                tracing::warn!("vault: this device's own key was not taken — {}", refusal.message);                            }                            // The person key, published once per launch to a signed-in                            // personal object, so it verifies unlock grants and allowlist changes.                            if let Some(Err(refusal)) = crate::phone::person_key::publish_owed(&client) {                                tracing::warn!("person key: not published — {}. It is asked again on the next pass.", refusal.message);                            }                            // Unlock windows: the seal version advance after one ends, and the                            // fast poll while a request waits.                            crate::phone::unlock::after_pass(&client);                            // KEPT FOUR 3 C: a local vault key goes only when the server holds every row it sealed,                            // sealed again (a complete read, every page).                            crate::phone::vault_carry::settle_after_pass(&client);                            // The in-place trim of a copy made before 151: a few bounded steps a pass.                            crate::phone::trim::carry(&client);                            // The WhatsApp timer's Bin and Blocked's 30 days, on their own turn after a pass (ABSENCE 6).                            crate::phone::cotton_chat::sweep_after_pass(&client);                            // Post's held mail whose time is up, and any on its way, sent or resumed through the                            // object's ledger (UNDO SEND 5: the lists never do network work).                            crate::phone::chat_app::mail::post::send_after_pass(&client);                            // Each app's lines about people (Comms, Post, Days, Albums: `person_fact`), from the tables this                            // copy holds, at most every 15 minutes; Contacts' tiers read them.                            crate::phone::contacts_facts::after_refresh(&client);                            // A note edit the object refused as moved, merged over the newer body.                            if let Err(why) = crate::phone::notes::merge_waiting(&client) {                                tracing::warn!("notes: a refused edit was not merged — {why}; asked again after the next pass");                            }                            // Me's name and picture, one way to the owner's                            // person in every shared database (Me, piece 2).                            if let Err(refusal) = crate::phone::owner_face::carry(&client) {                                tracing::warn!("me: your name and picture were not carried — {refusal}");                            }                            // The synced Files choice on this Mac's device row                            // is applied after the fold that brought it here.                            // `set_keep_rule` is idempotent, so a later file                            // or a transient writer failure is retried on the                            // next pass rather than being silently omitted.                            match crate::phone::device_keep_bytes::apply(&client) {                                Ok(0) => {}                                Ok(files) => tracing::info!(                                    "storage: applied this Mac's Files choice in {files} database(s)"                                ),                                Err(refusal) => tracing::warn!(                                    "storage: this Mac's Files choice was not applied — {refusal}. It will retry on the next pass."                                ),                            }                            // What this device keeps: what its rules no                            // longer keep leaves its copy, what they keep and                            // it lacks is fetched (`phone::keep::reconcile`).                            match crate::phone::keep::reconcile(&client) {                                Ok(done) if done.dropped + done.fetched > 0 => tracing::info!(                                    "keep: {} rows left this device, {} were fetched, {} are owed and stay",                                    done.dropped,                                    done.fetched,                                    done.owed                                ),                                Ok(_) => {}                                Err(refusal) => tracing::warn!("keep: this device's copy was not settled — {refusal}"),                            }                            // The indexes a moved copy makes after its move                            // (SCHEMA 155): each reads every mail, so here,                            // never at the open; reads answer from the table                            // meanwhile.                            // A vault opened before the copy held its data key's row takes the key                            // now that a pass brought it (SEAL KEY LATE).                            crate::phone::seal::take_late(&client);                            // The parks' keys an older build left, a slice at a time (FIRST SYNC 8).                            if let Err(refusal) = crate::phone::seal::fill_park_keys(&client) {                                tracing::warn!("seal: the parks' keys were not filled this pass — {refusal}");                            }                            // The Bin's 30 days, never as the Bin opens (MAIL PREDICATE phase 2).                            if let Err(refusal) = crate::phone::chat_app::mail::post::keep_the_bin(&client) {                                tracing::warn!("post: the Bin was not kept this pass — {}", refusal.message);                            }                            // Held mail's landing times from the object, paged, a slice at a time (MAIL PREDICATE                            // phase 2): until a mail has one, no cut covers it.                            if let Err(refusal) = crate::phone::landed::fill(&client) {                                tracing::warn!("landed: the landing times were not filled this pass — {refusal}");                            }                            if let Err(refusal) = crate::phone::mail_index::build_later(&client) {                                tracing::warn!("index later: an index was refused — {refusal}. The next pass goes on.");                            }                            // The copy's own check of itself, read-only, once a                            // build or a week (SCHEMA 155 REVIEW): what a move                            // that only adds no longer reads at the open.                            crate::phone::file_check::carry(&client);                            // Mail's wide search index, a slice at a time                            // (mailsearch, v122): this thread is never the                            // screen's, and the replica is freed between slices.                            if let Err(refusal) = crate::phone::mail_index::fill(&client, crate::phone::mail_index::PASS_BUDGET) {                                tracing::warn!("mail index: a slice was refused — {refusal}. The next pass goes on.");                            }                            // Chat's search index the same way (chat-search, v149).                            if let Err(refusal) = crate::phone::mail_index::fill_chat(&client, crate::phone::mail_index::PASS_BUDGET) {                                tracing::warn!("chat index: a slice was refused — {refusal}. The next pass goes on.");                            }                            // What an erase left in the search pages, merged out (DELETE FAST): within the hour                            // while Comms is open, else at the next launch's first pass.                            if let Err(refusal) = crate::phone::mail_index::purge(&client, crate::phone::mail_index::PURGE_BUDGET) {                                tracing::warn!("search purge: a merge was refused — {refusal}. The next pass goes on.");                            }                        }                        done.store(false, std::sync::atomic::Ordering::SeqCst);                    });                if spawned.is_err() {                    busy.store(false, std::sync::atomic::Ordering::SeqCst);                }            }));        }        crate::phone::voice_words::start(&client, runtime.handle());        Ok(Self {            flavor: config.flavor,            fan,            home: Arc::default(),            app_name,            app_slug,            runtime,            events,            layout,            data_dir,            _process_lock: process_lock,            app_version: config.app_version.unwrap_or_default(),            log,            client,            identity,            commands,            terminals: Arc::new(cotton_client::session_host::TerminalHub::new()),            me: std::sync::OnceLock::new(),            story_bringing: std::sync::atomic::AtomicBool::new(false),        })    }    /// Hold this handle in an `Arc` that knows itself — the shape the app's    /// FFI holds a core in, and the one a control socket can be bound for    /// ([`Self::bind_control`]).    pub fn shared(self) -> Arc<Self> {        Arc::new_cyclic(|me| {            let _ = self.me.set(me.clone());            self        })    }    /// Close a SHARED core ([`Self::shared`]): the control socket first, so    /// no new request takes a reference, then [`Self::close`] once the    /// requests already running have let go — bounded, because the caller is    /// a person's app. A request that is still running past the bound keeps    /// the core alive until it ends; everything was told to stop first.    pub fn close_shared(handle: Arc<Self>) {        let deadline = std::time::Instant::now() + SHARED_RELEASE_TIMEOUT;        let mut handle = handle;        loop {            match Arc::try_unwrap(handle) {                Ok(owned) => return owned.close(),                Err(shared) if std::time::Instant::now() < deadline => {                    handle = shared;                    std::thread::sleep(std::time::Duration::from_millis(20));                }                Err(shared) => {                    tracing::error!(                        "cotton-core: a control request still held the core at close — stopping \                         it, and the last request lets it go"                    );                    shared.quiesce();                    return;                }            }        }    }    pub fn commands(&self) -> Arc<crate::phone::commands::Commands> {        Arc::clone(&self.commands)    }    /// The terminals this device has open.    pub fn terminals(&self) -> Arc<cotton_client::session_host::TerminalHub> {        Arc::clone(&self.terminals)    }    pub fn events(&self) -> &Arc<EventBus> {        &self.events    }    /// The runtime every bounded call blocks on and every worker is spawned    /// into.    pub fn runtime(&self) -> &tokio::runtime::Runtime {        &self.runtime    }    pub fn data_dir(&self) -> &std::path::Path {        &self.data_dir    }    pub fn layout(&self) -> &Layout {        &self.layout    }    pub fn app_version(&self) -> &str {        &self.app_version    }    /// Which app identity opened this core.    pub fn flavor(&self) -> cotton_core::flavor::Flavor {        self.flavor    }    /// The controller, cloned so a bounded call can carry it onto the runtime.    /// The client half — the replica, the ingest queue and the sync loop.    /// The dial's own cards this app holds (the manifest's `fan`).    pub fn fan(&self) -> &cotton_core::flavor::FanCards {        &self.fan    }    /// The app's own name, as its manifest says it ("" for Cotton with none).    pub fn app_name(&self) -> &str {        &self.app_name    }    /// The app's slug (`notes`, `books`; `cotton` for Cotton).    pub fn app_slug(&self) -> &str {        &self.app_slug    }    /// Whether a script file is being read into Story (`story.bring_in`).    pub(crate) fn story_bringing(&self) -> &std::sync::atomic::AtomicBool {        &self.story_bringing    }    /// Where the gate's wait stands (`shell.home`).    pub fn home(&self) -> Arc<crate::methods::shell_home::Watch> {        Arc::clone(&self.home)    }    pub fn client(&self) -> Arc<ClientController> {        Arc::clone(&self.client)    }    pub fn log(&self) -> &Arc<LogRing> {        &self.log    }    pub fn identity(&self) -> &IdentityRead {        &self.identity    }    /// Drive a bounded piece of work to completion from whatever thread called    /// in.    ///    /// NOT `Runtime::block_on`, deliberately: that panics when the calling    /// thread is already inside this runtime, which is exactly what happens when    /// Swift's event handler asks the core a question from the thread the event    /// was emitted on. Spawning and waiting on a channel works from either side.    pub fn block_on<F, T>(&self, work: F) -> T    where        F: std::future::Future<Output = T> + Send + 'static,        T: Send + 'static,    {        let (sender, receiver) = std::sync::mpsc::channel();        self.runtime.spawn(async move {            let _ = sender.send(work.await);        });        receiver            .recv()            .expect("the runtime dropped a call before it answered")    }    /// Close the core: quiesce, then let the runtime go — BOUNDED at every    /// step, because the caller is a person's app, a test, or a shared CI    /// runner and none of them has anywhere to wait for ever.    ///    /// **The order is the whole of it, and it used to be backwards.** There was    /// no `close` here at all: `cotton_close` dropped the box, and a struct's    /// fields drop in declaration order, so `runtime` — the FIRST field — went    /// before the server and the client that live on it. Dropping a    /// multi-threaded tokio runtime cancels its async tasks but WAITS, with no    /// deadline anywhere, for every `spawn_blocking` closure still running: a    /// SQLite pass, an upload, the vault placement sweep this very `open`    /// fires. On an idle Mac that wait is milliseconds and nobody sees it; on a    /// loaded one it stretches, and on a wedged one it never ends — and the    /// thread it was holding was a Swift cooperative-pool thread    /// (Cotton note "Repo landmines — why the build's rules exist").    ///    /// So: stop the server and let go of the replica FIRST, with the runtime    /// still under them; drop everything but the runtime; and end with    /// `shutdown_timeout` rather than a drop, so a blocking closure that will    /// not finish is left to the operating system with a line in the log rather    /// than parking the caller.    pub fn close(self) {        self.quiesce();        // `..` drops the server, the client, the relay and the rest HERE —        // before the runtime they ran on, which is the point.        let CottonHandle { runtime, _process_lock, .. } = self;        runtime.shutdown_timeout(RUNTIME_SHUTDOWN_TIMEOUT);        drop(_process_lock);    }    /// Tell everything that lives on the runtime to stop, and wait no longer    /// than [`QUIESCE_TIMEOUT`] for it to.    fn quiesce(&self) {        // `Runtime::block_on` panics when the calling thread is already inside        // this runtime, and so does dropping the runtime there. `cotton_close`        // is always called from Swift's own queue, so this is the pathological        // case rather than the expected one — and the honest answer to it is to        // skip the wait, not to trade a hang for a panic.        // FIRST, and off the runtime entirely: a terminal's reader is a plain        // thread holding a socket, and one still pumping into an event bus        // nobody is subscribed to would outlive the handle it belongs to.        self.terminals.detach_all();        if tokio::runtime::Handle::try_current().is_ok() {            tracing::error!(                "cotton-core: close was called from inside the core's own runtime — nothing was \                 stopped first"            );            return;        }        let client = Arc::clone(&self.client);        let stopped = self.runtime.block_on(async move {            tokio::time::timeout(QUIESCE_TIMEOUT, async move {                // The pull schedule and the uploader, off the replica, before                // the replica's handle goes.                client.detach();            })            .await            .is_ok()        });        if !stopped {            tracing::error!(                "cotton-core: the server and the replica did not stop within {} s — closing \                 anyway; whatever is still running is named above",                QUIESCE_TIMEOUT.as_secs()            );        }    }}fn keychain_identity(device_secret: Option<&str>) -> Option<IdentityRead> {    use base64::engine::general_purpose::URL_SAFE_NO_PAD;    use base64::Engine;    let encoded = device_secret.filter(|value| !value.is_empty())?;    Some(        match URL_SAFE_NO_PAD            .decode(encoded)            .ok()            .and_then(|bytes| DeviceIdentity::from_secret(&bytes).ok())        {            Some(identity) => IdentityRead {                device_id: Some(identity.device_id()),                source: "keychain",                minted: false,                reason: None,            },            // NOT a fallback to minting one here. A seed that will not decode            // means the Keychain answered with something that is not a key, and            // minting a second identity would quietly leave every op this            // device already pushed authored by a device the server no longer            // sees.            None => IdentityRead {                device_id: None,                source: "none",                minted: false,                reason: Some(                    "the device key the Keychain handed over is not a key — this device has no \                     identity until one is minted again"                        .to_string(),                ),            },        },    )}/// A PHONE's whole identity story: the Keychain, or nothing.////// There is no rehearsal file and no unpackaged build here. An absent seed is a/// named state — the app has not minted one yet, or the Keychain is locked/// before first unlock — and pairing is what fixes it (design P15), never a/// silent mint somewhere else on disk.fn read_keychain_identity(device_secret: Option<&str>) -> IdentityRead {    keychain_identity(device_secret).unwrap_or(IdentityRead {        device_id: None,        source: "none",        minted: false,        reason: Some(            "no device identity yet — this phone mints one in the Keychain and pairs with a \             server before it can read or write anything"                .to_string(),        ),    })}/// The Electron era's device key, when it is still on disk — said once, and/// left exactly where it is.////// `<dataDir>/identity/device.key` was the Electron app's: an Ed25519 key in/// PEM, wrapped with Electron's `safeStorage` (the `v10` prefix Chromium's/// encryptor writes) and unreadable by anything that is not that app with that/// app's own Keychain item. The Swift app cannot open it, and #395 deleted the/// only thing that could.////// It is NOT adopted and NOT deleted. Not adopted, because reading it would/// mean carrying Chromium's key derivation and a second Keychain item into/// this app for one machine's one-time migration; not deleted, because it is/// the only copy of a key, and a file that is the only copy of a key is not/// something a boot throws away. What it costs is one line, and that line is/// worth having: on this Mac the registry's self-approved root device is the/// key inside this file, so anyone reading the log later can see why the root/// row names a device id no Keychain holds.////// A REHEARSAL's own seed lives at the same path (`Layout::rehearsal_device_key`)/// and says so in its first bytes, so it is passed over in silence.fn legacy_device_key_note(layout: &Layout) -> Option<String> {    let path = layout.rehearsal_device_key();    let head = std::fs::read(&path).ok()?;    if head.starts_with(REHEARSAL_MARK.as_bytes()) {        return None;    }    Some(format!(        "{} is the Electron era's wrapped device key — this app cannot read it, does not mint \         over it and does not delete it; this Mac's identity is the Keychain's",        path.display()    ))}/// Where a HOST's device seed comes from, and what it makes: the Keychain,/// then a rehearsal file beside a scratch database, then nothing.fn read_identity(    layout: &Layout,    packaged: bool,    data_dir_override: Option<&str>,    device_secret: Option<&str>,) -> IdentityRead {    if let Some(read) = keychain_identity(device_secret) {        return read;    }    if identity_storage_for(packaged, data_dir_override) == IdentityStorage::RehearsalFile {        let path = layout.rehearsal_device_key();        return match load_or_mint_rehearsal_seed(&path) {            Ok(read) => IdentityRead {                device_id: DeviceIdentity::from_secret(&read.secret)                    .ok()                    .map(|identity| identity.device_id()),                source: "rehearsal-file",                minted: read.minted,                reason: None,            },            Err(error) => IdentityRead {                device_id: None,                source: "none",                minted: false,                reason: Some(error.to_string()),            },        };    }    IdentityRead {        device_id: None,        source: "none",        minted: false,        reason: Some(            "no device identity — this Mac cannot be the root device until the Keychain is              available"                .to_string(),        ),    }}/// A test's host config: a temp home, unpackaged, no seed — what `swift run`/// against a scratch folder looks like.#[cfg(test)]pub(crate) fn host_config(home: &std::path::Path) -> OpenConfig {    OpenConfig {        mode: OpenMode::Host {            home: home.to_string_lossy().to_string(),            data_dir_override: None,            prepare_data_dir: true,            hostname: Some("studio.local".to_string()),            packaged: false,            app_build_label: None,            bind_host: None,        },        app_version: Some("0.1.0".to_string()),        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    }}/// A test's phone config: a container and nothing else.#[cfg(test)]pub(crate) fn phone_config(container: &std::path::Path) -> OpenConfig {    OpenConfig {        mode: OpenMode::Phone {            container_path: container.to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: Some("0.1.0".to_string()),        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    }}/// The wire shape, on every build: which keys name which mode, and what is/// refused by name.#[cfg(test)]mod wire_tests {    use super::*;    fn parse(json: &str) -> Result<OpenConfig, String> {        serde_json::from_str::<OpenConfig>(json).map_err(|error| error.to_string())    }    /// RULE: a manifest that founds Personal (every one of Cotton's own apps, read from the registry's apps and their    /// flavour.json files) keeps the build's real/dev identity; one that founds nothing (a business app's) opens as one.    #[test]    fn cottons_own_manifests_keep_their_build_identity_and_a_business_opens_as_one() {        let root = cotton_store::manifest_dir().join("../..");        let registry: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("apps/registry.json")).unwrap()).unwrap();        let mut checked = 0;        // A retired app (Calendar, into Days) builds nothing and keeps no flavour.json.        for app in registry["apps"].as_array().unwrap().iter().filter(|app| app["kit"].is_string() && app["retired"].is_null()) {            let slug = app["slug"].as_str().unwrap();            // An Android-only app (no `ios`, Contacts) keeps its flavour.json in the Android project's own folder.            let path = if slug == "cotton" {                root.join("apps/cotton/App/CottonManifest/flavour.json")            } else if app["ios"].is_null() {                root.join(format!("apps/android/app/flavours/{slug}/flavour.json"))            } else {                root.join(format!("apps/cotton/App/Flavours/{slug}/flavour.json"))            };            let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))).unwrap();            let config = parse(&serde_json::json!({"containerPath": "/c", "flavor": "dev", "manifest": manifest}).to_string()).expect("phone config");            let expected = if manifest["genesis"] == "personal" { cotton_core::flavor::Flavor::Dev } else { cotton_core::flavor::Flavor::Business };            assert_eq!(config.flavor, expected, "{slug} (genesis {})", manifest["genesis"]);            checked += 1;        }        assert!(checked > 0, "the registry names no app with a kit");        let business = parse(r#"{"containerPath":"/c","flavor":"dev","manifest":{"flavour":"sharmila","genesis":"none","business":{"server":"https://x.example","slug":"sharmila"}}}"#).expect("phone config");        assert_eq!(business.flavor, cotton_core::flavor::Flavor::Business);        let unsaid = parse(r#"{"containerPath":"/c","flavor":"dev","manifest":{"flavour":"a-new-app","business":{"server":"https://x.example"}}}"#).expect("phone config");        assert_eq!(unsaid.flavor, cotton_core::flavor::Flavor::Dev, "a manifest that says no genesis founds Personal, as Swift reads it");    }    /// RULE: A move's bundle build label is separate from app_version, because retirement and standby gates compare the device row's bare marketing version.    #[test]    fn booking_identity_does_not_change_the_device_version() {        let config = parse(r#"{"home":"/Users/x","appVersion":"0.29.42","appBuildLabel":"0.29.42 (117)"}"#).expect("host identity");        assert_eq!(config.app_version.as_deref(), Some("0.29.42"));        let OpenMode::Host { app_build_label, .. } = config.mode else { panic!("host mode") };        assert_eq!(app_build_label.as_deref(), Some("0.29.42 (117)"));    }    #[test]    fn home_names_a_host_and_the_defaults_are_the_mac_s() {        let config = parse(r#"{"home":"/Users/x","appVersion":"0.1.0"}"#).expect("a host");        assert_eq!(            config.mode,            OpenMode::Host {                home: "/Users/x".to_string(),                data_dir_override: None,                prepare_data_dir: true,                hostname: None,                packaged: false,                app_build_label: None,                bind_host: None,            }        );        assert_eq!(config.app_version.as_deref(), Some("0.1.0"));    }    #[test]    fn the_flavor_is_dev_unless_the_config_says_exactly_real() {        use cotton_core::flavor::Flavor;        let flavor = |json: &str| parse(json).expect("a config").flavor;        assert_eq!(flavor(r#"{"home":"/Users/x"}"#), Flavor::Dev);        assert_eq!(flavor(r#"{"home":"/Users/x","flavor":"dev"}"#), Flavor::Dev);        assert_eq!(flavor(r#"{"home":"/Users/x","flavor":"Real"}"#), Flavor::Dev);        assert_eq!(flavor(r#"{"home":"/Users/x","flavor":"real"}"#), Flavor::Real);        assert_eq!(flavor(r#"{"containerPath":"/private/var/x","flavor":"real"}"#), Flavor::Real);    }    // Cotton carries a manifest too. Only a business manifest changes the    // relay namespace; the personal app keeps its real/dev build identity.    #[test]    fn cottons_manifest_does_not_make_it_a_business() {        let config = parse(r#"{"containerPath":"/own","flavor":"real","manifest":{"flavour":"cotton","databases":"single","database":"personal"}}"#).unwrap();        assert_eq!(config.flavor, cotton_core::flavor::Flavor::Real);        // Cotton Development is the owner's own app over the project's database, never a business.        let development = parse(r#"{"containerPath":"/own","flavor":"dev","manifest":{"flavour":"development","databases":"single","database":{"id":"db-cotton","host":"https://unit.example","named":"Cotton"}}}"#).unwrap();        assert_eq!(development.flavor, cotton_core::flavor::Flavor::Dev);    }    /// RULE: a business app's manifest crosses at open whole, and its absence is Cotton — the wire refuses unknown keys, so a phone built with a manifest against a core without this field would not open at all.    #[test]    fn a_business_app_hands_its_manifest_down_whole() {        let config = parse(            r#"{"containerPath":"/own","manifest":{"flavour":"sharmila","name":"Sharmila's Yoga Zone","genesis":"none","databases":"single"}}"#,        )        .expect("a business phone");        // A bundled business must join the business relay namespace, even        // when the shared binary was cut with Cotton's real/dev build stamp.        assert_eq!(config.flavor, cotton_core::flavor::Flavor::Business);        let manifest = config.manifest.expect("the manifest");        assert_eq!(manifest["flavour"], "sharmila");        assert!(parse(r#"{"containerPath":"/own"}"#).expect("Cotton").manifest.is_none());    }    /// RULE: a manifest's Home is a board this build draws, with the id `home` and at least one section, or the app does not open; a manifest naming none draws the shipped Home (Cotton's own, owner 19 Oct 2026). That every business manifest names one is held on its file (`business_home.rs`, `HomeNeverMeTests`).    #[test]    fn a_manifest_home_is_a_drawable_board_or_none() {        let without = serde_json::json!({"flavour":"cotton","name":"Cotton","databases":"single","database":"personal"});        assert_eq!(business_home(&without), Ok(()), "none is the shipped Home — Cotton's own");        let empty = serde_json::json!({"home":{"format_version":1,"id":"home","parts":[]}});        assert!(business_home(&empty).is_err(), "a Home with no sections is refused");        let elsewhere = serde_json::json!({"home":{"format_version":1,"id":"tools","parts":[{"kind":"today"}]}});        assert!(business_home(&elsewhere).unwrap_err().contains("must be \"home\""));        let unknown = serde_json::json!({"home":{"format_version":1,"id":"home","parts":[{"kind":"sections"}]}});        assert!(business_home(&unknown).is_err(), "a part this build does not draw is refused");    }    #[test]    fn a_phone_names_the_app_group_its_data_left_and_a_host_may_not() {        let config = parse(r#"{"containerPath":"/own","previousContainerPath":"/group"}"#)            .expect("a phone");        assert_eq!(            config.mode,            OpenMode::Phone {                container_path: "/own".to_string(),                previous_container_path: Some("/group".to_string()),            }        );        assert!(parse(r#"{"home":"/Users/x","previousContainerPath":"/group"}"#).is_err());    }    #[test]    fn container_path_names_a_phone() {        let config = parse(r#"{"containerPath":"/private/var/x","timeZone":"Asia/Kolkata"}"#)            .expect("a phone");        assert_eq!(            config.mode,            OpenMode::Phone {                container_path: "/private/var/x".to_string(),                previous_container_path: None,            }        );        assert_eq!(config.time_zone.as_deref(), Some("Asia/Kolkata"));    }    #[test]    fn both_or_neither_is_refused_with_the_two_names() {        let both = parse(r#"{"home":"/Users/x","containerPath":"/private/var/x"}"#)            .expect_err("a refusal");        assert!(both.contains("never both"), "{both}");        let neither = parse(r#"{"appVersion":"0.1.0"}"#).expect_err("a refusal");        assert!(neither.contains("neither"), "{neither}");    }    #[test]    fn a_host_s_field_beside_a_container_is_refused_by_name() {        // The whole reason `deny_unknown_fields` is on the wire struct, carried        // into the one struct: a phone that was handed `hostname` and        // `packaged` has been handed a Mac's config, and nothing about it may        // be silently ignored.        let error = parse(r#"{"containerPath":"/private/var/x","hostname":"studio.local","packaged":true}"#)            .expect_err("a refusal");        assert!(error.contains("hostname, packaged are a host's"), "{error}");    }    #[test]    fn an_unknown_field_in_the_config_is_refused_rather_than_ignored() {        let error = parse(r#"{"home":"/Users/x","dataDir":"/tmp"}"#).expect_err("a refusal");        assert!(error.contains("dataDir"), "{error}");    }}/// The phone's half of the same questions, on EVERY build: the container is the/// data directory, and the Keychain is the whole identity story.#[cfg(test)]mod phone_tests {    use super::*;    fn config(container: &std::path::Path) -> OpenConfig {        phone_config(container)    }    #[test]    fn opening_takes_the_container_as_the_data_directory_and_creates_it() {        let root = tempfile::tempdir().expect("a temp container");        let container = root.path().join("AppGroup").join("cotton");        let handle = CottonHandle::open(config(&container)).expect("an open core");        assert_eq!(handle.data_dir(), container);        assert!(container.exists(), "a first launch makes its own folder");    }    #[test]    fn a_phone_with_no_seed_says_so_rather_than_minting_one_on_disk() {        let root = tempfile::tempdir().expect("a temp container");        let handle = CottonHandle::open(config(root.path())).expect("an open core");        assert_eq!(handle.identity().device_id, None);        assert_eq!(handle.identity().source, "none");        assert!(            !handle.identity().minted,            "nothing is minted outside the Keychain"        );        assert!(handle            .identity()            .reason            .as_ref()            .expect("a sentence")            .contains("pairs with a server"));    }    #[test]    fn a_seed_the_keychain_handed_down_becomes_this_device_s_id() {        use base64::engine::general_purpose::URL_SAFE_NO_PAD;        use base64::Engine;        let root = tempfile::tempdir().expect("a temp container");        // Synthetic, and fixed so the assertion is about the seam rather than        // about a generator.        let seed = [7u8; 32];        let handle = CottonHandle::open(OpenConfig {            device_secret: Some(URL_SAFE_NO_PAD.encode(seed)),            vault_secret: None,            ..config(root.path())        })        .expect("an open core");        assert_eq!(handle.identity().source, "keychain");        assert_eq!(            handle.identity().device_id.as_deref(),            Some(                DeviceIdentity::from_secret(&seed)                    .expect("an identity")                    .device_id()            )            .as_deref()        );    }    /// The other build's refusal: a Mac's config on the client build is a    /// host that cannot serve, and it says so at open rather than opening a    /// data directory no method could start a server over.    #[test]    fn a_host_config_on_the_client_build_is_refused_at_open() {        let home = tempfile::tempdir().expect("a temp home");        let error = CottonHandle::open(host_config(home.path())).expect_err("a refusal");        assert_eq!(error.code, "no_server_in_this_build");        assert!(error.message.contains("containerPath"), "{}", error.message);        assert!(            !home.path().join("CottonDB").exists(),            "a refused open prepares nothing"        );    }}