Cotton code
5495 lines · 298.8 KB · RustRaw
//! THE OWNER'S PERSONAL OBJECT AS THIS PHONE'S SYNC PEER.//!//! The owner's personal database lives in one Durable Object on the Cloudflare//! Worker (`apps/business`, kind `personal`). The object holds every row and//! decides every write; this phone keeps a cache of it — its own replica file,//! the typed tables every deck already reads — filled by snapshot sync since a//! cursor, and posts each write it makes to the object. There is no Mac and no//! relay on the way.//!//! **The object stands where the serving Mac stood: behind [`SyncTransport`].**//! The sync loop, the outbox, the fold, the decks and the `data` events are//! exactly the ones a phone always ran; only the far end of one exchange is//! different. One exchange here is://!//! * **The push.** Each op of the request (the outbox, and whatever the pass//!   hands over) becomes one of the object's general acts on the row it names://!   a create receipt is `create` under the row's own id, a change is `update`,//!   a retract is `delete`. A create sends the row as this file holds it now,//!   every column the object keeps ([`ObjectTables`]). A change sends only the//!   columns its ops named ([`own_columns`]), so what another writer laid on the//!   row since this copy read it stands (film-progress-clobber, 18 Nov 2026); a//!   write that named one key of a JSON column still sends the whole column. A//!   change of a sealed column carries the sealed half, one blob, and is kept//!   only while the row is at the version this copy read (the `seal` act)://!   refused, it waits for the pull and goes again over the newest row. The//!   object's refusal of an op is the op's rejection, final unless the object//!   was unreachable or failing, or the row moved.//! * **The pull.** One page of `GET /v1/sync` from the cursor this file holds//!   (`object` in `_cursors`), each row minted into a receipt of//!   [`OBJECT_AUTHOR`] at the row's own `updated_at`, and folded by the same//!   fold as every write — so a later edit on this phone stacks on it, and the//!   object's answer to that edit (stamped when the object took it) wins over//!   it. A tombstone is a retract. The first page carries the windows//!   ([`ObjectTransport::windows`]: the owner's newest days of messages).//!   A row's key that a served definition names on a table this build//!   compiles, and that the build's table lacks, is not dropped: the copy's//!   table gains the column first ([`ObjectTables::with_defined`]).//! * **The object's tables, tools and boards.** They are not rows of//!   `/v1/sync` but the `tables`, `tools` and `boards` of `/v1/definitions`,//!   asked with a launch's first page (and each page after until the copy//!   matches them) and at the end of every pass that moved the object's//!   version (a merge of definitions moves it), with the etag this phone last//!   took ([`HeldDefinitions`]). Each one the copy does not hold as served//!   becomes a create receipt of [`OBJECT_AUTHOR`] on//!   `cotton_table_definitions`, `cotton_tool_definitions` or//!   `cotton_board_definitions`, folded beside the page's rows — over the//!   app's own row at that id — and every non-builtin held row it no longer//!   serves a retract ([`served_definitions`]). One this build cannot read is//!   said and left on the object ([`drawable_tables`], [`drawable_tools`]).//! * **Who the owner is.** The same answer's `business.owner_person_id`, the//!   person the object names as its owner, lands on this copy's own//!   workspace row ([`served_owner`]), the one place every read of "you"//!   looks: the object writes that link, never this phone.//!//! A table this phone holds and the object does not (the store's own//! bookkeeping, this device's preferences) is this phone's alone: an op on it//! is answered taken without an act, because there is nowhere else for it to//! go. A table the object holds and this phone has no table for (the owner's//! MCP tokens, the vault's sealed secrets) never comes down.//!//! **The credential is held in memory, for the loop.** It reaches this file//! from the Keychain through the app, once per launch, and goes on one header.use std::sync::atomic::Ordering;use std::collections::{BTreeMap, HashMap};use std::io::Read;use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex, OnceLock};use std::time::Duration;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_store::canonical::{self, Kind};use cotton_store::mint::{Actor, JobName, ServedRow};use cotton_store::exchange::SyncTransport;use cotton_store::protocol::types::{CottonOp, ExchangeRequest, ExchangeResponse, PushRejection};use cotton_store::schema::codecs::decode_value;use cotton_store::schema::decl::{Codec, TableSpec};use cotton_store::schema::package_shape::{self, ServedColumn};use super::http1::Http1Request;use super::{normalize_server_url, Exchange, Origin, RefusalAware, ServerRefusal};/// The most parked rows one page opens and folds (FIRST SYNC, dev, 26 Nov 2026): a fold of 5,000 mails stands well/// inside a pass; 70,000 parked before the key never did.pub(crate) const REOPEN_AT_ONCE: usize = 2_000;#[cfg(test)]thread_local! {    /// A smaller batch for the tests on this thread, so many batches stay cheap.    pub(crate) static REOPEN_TEST: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };}fn reopen_at_once() -> usize {    #[cfg(test)]    if let Some(n) = REOPEN_TEST.with(std::cell::Cell::get) {        return n;    }    REOPEN_AT_ONCE}/// The object's refusal of a `seal` act: the row is no longer at the version/// this copy read. The write waits for the pull and goes again over what it brings.const VERSION_MOVED: &str = "version_moved";/// Refused as moved, the row the change was to: the object holds it no more (deleted there), so the change has/// nowhere to go. Final: parked and shown, never posted again (UNSENT HEAL 4).const ROW_GONE: &str = "row_gone";/// The wait after `tries` reads or posts that did not go: a minute, doubling, an hour at most.fn wait_minutes(tries: u32) -> i64 {    (1i64 << tries.saturating_sub(1).min(6)).min(60)}/// LET A RETIRED TABLE'S ROWS GO FROM A SIGNED-IN COPY (TABLE DROP 1, owner, 27 Nov 2026): the object holds each/// table `cotton_core::retired` names as retired and never serves or syncs it again, so the rows this copy holds of/// one are only weight. They go, raw, at the copy's open, table by table, and only where nothing of the person's/// waits in them: no change queued for the table (`_outbox`), no receipt held (`_writes.held`). A change still queued/// is parked by the next push first ([`TABLE_GONE`], with its patch), and the rows go at the open after. A copy that/// never pulled from the object ([`PASSED_KEY`] absent: a database made before sign-in) keeps every row: its rows/// are the person's only record, and they go up, and park, at its adoption. No other table is touched and nothing/// is pulled again. Answers each table let go and how many rows went.pub fn drop_gone_rows(db: &cotton_store::driver::Driver) -> Result<Vec<(String, usize)>, String> {    let failed = |error: rusqlite::Error| format!("this phone's copy could not let a retired table's rows go ({error})");    let file = db.connection();    let signed_in = file.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '_cursors'", [], |_| Ok(())).is_ok()        && file.query_row("SELECT 1 FROM _cursors WHERE author_device_id = ?1", [PASSED_KEY], |_| Ok(())).is_ok();    if !signed_in {        return Ok(Vec::new());    }    let map = ObjectTables::personal();    let exists = |name: &str| file.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1", [name], |_| Ok(())).is_ok();    let mut dropped = Vec::new();    for table in cotton_core::retired::GONE_TABLES {        let mut stores = vec![format!("cotton_{table}")];        if let Some(compiled) = map.object(table) {            stores.insert(0, compiled.store.clone());        }        for store in stores.iter().filter(|store| exists(store)) {            let quoted = store.replace('"', "");            let rows: i64 = file.query_row(&format!("SELECT count(*) FROM \"{quoted}\""), [], |row| row.get(0)).map_err(failed)?;            if rows == 0 {                continue;            }            let queued = exists("_outbox") && file.query_row("SELECT 1 FROM _outbox WHERE tbl = ?1 LIMIT 1", [store.as_str()], |_| Ok(())).is_ok();            let held = exists("_writes") && file.query_row("SELECT 1 FROM _writes WHERE tbl = ?1 AND held <> 0 LIMIT 1", [store.as_str()], |_| Ok(())).is_ok();            if queued || held {                eprintln!("[object] {table} is retired: its {rows} rows stay in this copy while a change of it waits to be parked");                continue;            }            file.execute(&format!("DELETE FROM \"{quoted}\""), []).map_err(failed)?;            eprintln!("[object] {table} is retired: the {rows} rows this copy held of it went");            dropped.push((table.to_string(), usize::try_from(rows).unwrap_or(0)));        }    }    Ok(dropped)}/// The refusal of a change to a table the object holds as retired ([`gone_store`]).const TABLE_GONE: &str = "table_gone";/// The object's refusal of a change naming a field its table's definition lacks (UNKNOWN FIELD, coordinator, 28 Nov/// 2026: a kit column on main before the Worker's deploy). Never final: the change waits in the queue, is posted again/// once the object's definitions move ([`HeldDefinitions::waits_for_field`]), and is said after a day.pub const UNKNOWN_FIELD: &str = "unknown_field";/// Whether `store` (this build's table name) keeps the rows of a table the object holds as retired/// (`cotton_core::retired`): by the map, or, for a table made from a definition the object no longer serves, by its/// made name (`cotton_<id>`, `cotton_store::schema::package_tables::from_definition`).pub(crate) fn gone_store(map: &ObjectTables, store: &str) -> bool {    match map.ours(store) {        Some(table) => cotton_core::retired::is_gone_table(&table.table),        None => store.strip_prefix("cotton_").is_some_and(cotton_core::retired::is_gone_table),    }}fn row_gone(table: &StoredTable, id: &str) -> ObjectRefusal {    ObjectRefusal { status: 410, code: ROW_GONE.into(), message: format!("{ROW_GONE}: {} {id}: the object holds this row no more (deleted there), so the change has nowhere to go", table.table) }}fn moved_again(table: &StoredTable, id: &str, tries: u32) -> ObjectRefusal {    ObjectRefusal { status: 409, code: MOVED_AGAIN.into(), message: format!("{} {id} waits: its edit laid over a fresh read was refused as moved {tries} times in a row", table.table) }}fn unread_refusal(table: &StoredTable, id: &str) -> ObjectRefusal {    ObjectRefusal { status: 409, code: HELD_ROW_UNREAD.into(), message: format!("{} {id} waits: the object would not hand back the row to hold the change to", table.table) }}/// The keys of each per-key column (`data.<key>`) the ops of a row wrote, by the object's column name.fn per_key_changes(table: &StoredTable, of_row: &[&CottonOp]) -> Result<std::collections::BTreeMap<String, std::collections::BTreeSet<String>>, String> {    let mut keys: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> = std::collections::BTreeMap::new();    for op in of_row {        let receipt = canonical::decode(op.receipt.as_bytes()).map_err(|error| error.to_string())?;        for field in receipt.fields.keys() {            let Some((column, key)) = field.split_once('.') else { continue };            let object = table.columns.iter().find(|(_, ours, _)| ours == column).map(|(object, _, _)| object.clone()).unwrap_or_else(|| column.to_string());            keys.entry(object).or_default().insert(key.to_string());        }    }    Ok(keys)}/// `keys` of `ours` (this copy's whole map) laid over `theirs` (the object's), the rest of `theirs` kept; a key this/// copy no longer holds is removed. Either side may be a JSON object or its text; the answer takes `theirs`' form.fn lay_keys(theirs: Option<&Value>, ours: &Value, keys: &std::collections::BTreeSet<String>) -> Value {    let as_map = |value: Option<&Value>| -> Map<String, Value> {        match value {            Some(Value::Object(map)) => map.clone(),            Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok().and_then(|value| value.as_object().cloned()).unwrap_or_default(),            _ => Map::new(),        }    };    let mut laid = as_map(theirs);    let ours_map = as_map(Some(ours));    for key in keys {        match ours_map.get(key) {            Some(value) if !value.is_null() => {                laid.insert(key.clone(), value.clone());            }            _ => {                laid.remove(key);            }        }    }    match theirs.or(Some(ours)) {        Some(Value::String(_)) => Value::String(Value::Object(laid).to_string()),        _ => Value::Object(laid),    }}/// A change of a table held to its version whose row the object would not hand back (not live there, or it does/// not open with this copy's key), and which this phone did not make: it waits in the outbox, held by name, and,/// being no passing code, is said to the person after a day (`unsent_heal`). Never sent unheld (HIDDEN 7).const HELD_ROW_UNREAD: &str = "held_row_unread";/// An edit laid over a fresh read of its row and refused as moved again, [`MOVED_AGAIN_AFTER`] times in a row: the/// row is written to faster than this phone reads and posts, so it waits as an unread row does, and is said after a/// day (UNSENT HEAL 7, review 3).const MOVED_AGAIN: &str = "moved_again";/// How many refusals as moved in a row, each straight after a fresh read, before the row waits ([`MOVED_AGAIN`]).const MOVED_AGAIN_AFTER: u32 = 3;/// A row whose edit waits for its app to merge it over the newer text a pull/// brought ([`crate::seal::EDIT_BASE`]): not sent until then.const MERGE_WAITS: &str = "merge_waits";/// The author every row the object hands down is stamped as: the object is the/// one writer of what it serves, and one author stream in this copy.pub const OBJECT_AUTHOR: &str = "object";/// The job the receipts of [`OBJECT_AUTHOR`] name as their actor.pub const OBJECT_JOB: &str = "object-sync";/// `job:`[`OBJECT_JOB`], the actor of every receipt of [`OBJECT_AUTHOR`].fn object_actor() -> Actor {    Actor::job(JobName::named(OBJECT_JOB).expect("object-sync is one word"))}/// The key this file's `_cursors` keeps the object's version under: `v` and the/// version, zero-padded so a later one sorts after, and while a pull is between/// pages, `.` and the object's page token after it. A copy that has pulled/// again from the start ([`PASSED_KEY`]) says how many times before the `v`:/// `w<pulls, 4 digits>v<version>`, which sorts after every cursor of fewer.pub const CURSOR_KEY: &str = "object";/// The key this file's `_cursors` keeps the object tables whose rows its/// cursor went past without keeping them: a table this build places nowhere/// (one it cannot read, one the object keeps for itself), and `table.key` for/// a key of a placed table's rows this copy kept no column for, since the/// copy's last pull from the start. `h<pulls>.<n>:` and the names,/// comma-separated and sorted, `n` counting each time the set grew within the/// same pull so the text only moves forward. A pass that opens placing a/// table or a column it names (a build that keeps a table an earlier one/// passed by: Subscriptions, Work and Machines before 12dbd60b0; a copy that/// gained the balance columns the object's money engine writes), or that/// finds no record it reads (a copy an earlier build pulled, or one whose/// `g` record named tables alone, before 27 Oct 2026), pulls again from the/// start, so the rows the cursor went past come down whole./// A pull from the start this build's [`MINTING`] made says so after the/// count: `h<pulls>.<n>.m<minting>:`; one an earlier minting made (a record/// without it reads as minting 0) is owed again in the same way.pub const PASSED_KEY: &str = "object.passed";/// The account's own switches as the object last said them (`features` on a sync page, MAIL ALL ON PHONE, 24 Nov/// 2026: `mail_all`), held with the cursor: `f<the object's clock>|<names, comma-separated>`. The clock leads so the/// text only moves forward (the cursors' rule) whether a switch goes on or off. Read at a launch/// ([`account_features`]), never an author.pub const FEATURES_KEY: &str = "object.features";/// THE SERVER'S GENERATION (RESTORE 2, RESTORE-CONTRACT.md), held with the cursor: `g<generation>`, the opaque/// string every sync answer carries, compared as a string and never parsed. A copy holding none takes the first one/// answered; one answered otherwise means the server was put back to an earlier time (a restore), and the copy folds/// nothing of that answer and is made again. Written once per copy, so the cursors' only-forward rule never bites.pub const GENERATION_KEY: &str = "object.generation";/// The header every act a copy posts carries its generation in: the server refuses a write made against another/// ([`GENERATION_MOVED`]) and lands nothing of it.pub const GENERATION_HEADER: &str = "x-cotton-generation";/// The server's word, on a 409 to a post, that its generation is not the copy's: nothing landed; the pass stops and/// the copy is set aside and made again, never the change parked, retried or rewritten. Also the code a pull that met/// a new generation fails under.pub const GENERATION_MOVED: &str = "generation_moved";/// The server's word, on a 503, that the account is held still for a moment (a restore under way): a refusal that/// passes, nothing parked; the Sync page says it plainly.pub const ACCOUNT_FROZEN: &str = "account_frozen";/// The switches the copy at `path` last heard from its object ([`FEATURES_KEY`]); none when it never heard any.////// Read through a snapshot reader, never [`cotton_store::driver::Driver::open`]: this runs on every launch's/// connect, before the copy is open, and an open makes the file when it is missing (a first sign-in's copy, which/// connect then finds on disk as if one were there).pub fn account_features(path: &Path) -> Vec<String> {    if !path.exists() {        return Vec::new();    }    let Ok(db) = cotton_store::driver::Driver::open_snapshot_reader(path) else { return Vec::new() };    let held = db        .get("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(FEATURES_KEY.to_string())])        .ok()        .flatten()        .and_then(|row| row.text("hlc_seen").map(str::to_string));    held.as_deref().map(features_of).unwrap_or_default()}/// The generation a [`GENERATION_KEY`] text holds.fn generation_of(text: &str) -> Option<String> {    text.strip_prefix('g').filter(|generation| !generation.is_empty()).map(str::to_string)}fn features_of(text: &str) -> Vec<String> {    text.split_once('|').map(|(_, names)| names.split(',').filter(|name| !name.is_empty()).map(str::to_string).collect()).unwrap_or_default()}/// The [`FEATURES_KEY`] text of a page the object answered, when it said its clock.fn features_text(answer: &Value) -> Option<String> {    let at = answer["server_time"].as_str()?;    let names: Vec<&str> = answer["features"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();    Some(format!("f{at}|{}", names.join(",")))}/// How this build makes the object's rows into receipts/// ([`ObjectTransport::op_of`]), counted from the first, which said nothing/// of it: one more each time a build makes a served row differently, so a/// copy whose rows an earlier way made, some of which its fold refused, pulls/// again from the start once and those rows come down whole.////// 1 (27 Oct 2026): a column the object holds nothing in is the copy's/// declared default where the copy's column cannot hold null. Before it such a/// row named null there, and the fold refused it: a WhatsApp message the Mac/// imported naming no mentions, an agent session naming no prompt, never/// reached the phone, while its thread's last line did.////// 2 (27 Oct 2026): a row given a default is another op than the one an/// earlier minting made of the same version, and stands for the receipt held/// at its stamp — a receipt the fold kept but could not assemble a row from/// (a message held while its chat waited) named null there, and the same op/// id pulled again was the same write, so it never healed.////// 3 (27 Oct 2026): a live row names no revocation mirror it holds nothing in/// (`cotton_store::mint::served`). Before it every code credential the object/// serves named `revoked_at` null, the fold's fence refused it as an/// un-revocation, and none reached the phone.pub const MINTING: u32 = 3;/// What `seen` says of an author the object has taken every write of: after/// every stamp and every origin token, so no pass hands that author's writes/// over again.const SEEN_ALL: &str = "~";/// How long one exchange with the object may take.const CEILING: Duration = Duration::from_secs(30);/// The most an answer may weigh: a sync page of 5,000 rows is large.const ANSWER_LIMIT: u64 = 64 * 1024 * 1024;/// How long one media fetch may take: a film is large.const MEDIA_CEILING: Duration = Duration::from_secs(300);/// Rows per pull page, the object's own default.const PAGE_ROWS: u32 = 5_000;/// Rows per pull page of the kit's late tables while no key is held ([`ObjectTransport::short_pages`]).const KEYLESS_LATE_PAGE_ROWS: u32 = 1_000;/// The kit table a fresh copy's first pull leaves for the next pass: the/// pictures' rows, which name every file of the whole object/// ([`ObjectTransport::first_fill`]).const FIRST_FILL_LATER: &str = "media";/// Named in the record of a first fill's tables gone past ([`PASSED_KEY`]),/// beside the tables it left: its pages carry the record on, and the pass/// after it pulls the tables it left whole (`again=`), the rest since its/// cursor. Pulling the whole kit again from the start, as it did until/// 22 Nov 2026, brought every chat and mail of a new phone's first pull down/// twice (Comms on an emulator: 165 MB for an account of 80 MB, and the/// pass after the key folded a page of mail pulled again with the chats).const FIRST_FILL_MARK: &str = "~first-fill";/// The most rows one pass posts before it pulls ([`ObjectTransport::push`])./// A post is one request, about a third of a second from a phone (owner's/// phone, 17 Nov 2026: 185 a minute), so this is a pass of some fifteen/// seconds: inside a background wake's thirty, and never minutes of a long/// queue before the object's arrivals come down.pub const POSTS_PER_PASS: usize = 50;/// The object's routes, as `apps/business/src/business.ts` answers them.pub mod routes {    pub const DEFINITIONS: &str = "/v1/definitions";    pub const CODE: &str = "/v1/code";    pub const SIGN_IN: &str = "/v1/sign-in";    pub const SIGN_OUT: &str = "/v1/sign-out";    pub const SYNC: &str = "/v1/sync";    /// The ids the object holds of some tables, ids only (`HeldAnswer` in    /// `apps/business/src/protocol.ts`); an object older than it answers 404.    pub const HELD: &str = "/v1/held";    pub const ME: &str = "/v1/me";    pub const ACT: &str = "/v1/act";    pub const PHOTOS: &str = "/v1/photos/";    pub const MEDIA: &str = "/v1/media/";    /// A film's short-lived stream address (`apps/business/src/stream.ts`):    /// `POST {key}` answers `{url, expires_at}`, the film's folder signed for    /// twelve hours under `/v1/stream/<token>/…`, read with no bearer.    pub const MEDIA_STREAM: &str = "/v1/media/stream";    /// Google Calendar on the person's own object (`apps/business/src/google.ts`).    pub const GOOGLE_CONNECT: &str = "/v1/google/connect";    pub const GOOGLE_STATUS: &str = "/v1/google/status";    pub const GOOGLE_DISCONNECT: &str = "/v1/google/disconnect";    /// Spotify on the person's own object (`apps/business/src/spotify.ts`).    pub const SPOTIFY_CONNECT: &str = "/v1/spotify/connect";    pub const SPOTIFY_STATUS: &str = "/v1/spotify/status";    pub const SPOTIFY_DISCONNECT: &str = "/v1/spotify/disconnect";}// ── where an object answers ────────────────────────────────────────────────/// Where one database's object answers: the Worker's address and the/// database's slug — or, on the open host (`cottondb.com`, `open`), the/// Worker's address alone, where the bearer names the database.#[derive(Debug, Clone)]pub struct ObjectAddress {    origin: Origin,    /// Empty on the open host: no slug names the object there.    slug: String,    /// `/b/<slug>` on a host that names no database (workers.dev, a loopback,    /// this network), nothing on a host that names it (`cotton.example.com`,    /// `sharmila.cottondb.com`) — the Worker's own rule.    prefix: String,}/// An object's refusal, `{code, message}`, or a request that never got one.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ObjectRefusal {    /// The HTTP status, `0` when nothing answered.    pub status: u16,    /// The object's word (`duplicate_id`), `offline` when nothing answered.    pub code: String,    pub message: String,}impl ObjectRefusal {    fn offline(message: String) -> ObjectRefusal {        ObjectRefusal { status: 0, code: "offline".into(), message }    }    /// Whether asking again later could be answered otherwise: nothing    /// answered, or the object was failing.    pub fn transient(&self) -> bool {        self.status == 0 || self.status >= 500 || self.status == 429    }    /// Whether the object no longer takes this phone's credential: a 401, or    /// the 410 that says the person deleted the account    /// (apps/business/src/account_delete.ts), which signs every phone of it    /// out as a 401 does and is said under its own code.    pub fn signs_out(&self) -> bool {        self.status == 401 || self.deleted()    }    /// Whether the object says the person deleted this account.    pub fn deleted(&self) -> bool {        self.status == 410 && self.code == ACCOUNT_DELETED    }}/// The object's word that the person deleted the account: every phone of it/// forgets its copy (`account.forget`).pub const ACCOUNT_DELETED: &str = "account_deleted";/// The code a transient refusal that carries no word of its own (a 5xx or a/// 429 whose body is not the object's JSON) is said under, so a screen can/// tell "Cotton did not answer" from a refusal it can act on.pub const UNANSWERED: &str = "unanswered";/// Whether a refusal said by `code` and `words` is the object not answering/// (nothing reached it, it failed with a 5xx, or it was too busy): the core's/// own words (`the business did not answer`, `…, status 503 unavailable`),/// said in the log and never on a screen, where the kit's line says Cotton/// could not be reached just now (incident, 21 Nov 2026). `code` is the/// refusal's own when the caller holds it; words alone are read for the/// status the core writes into a kept copy's reason (`status 500`).pub fn names_an_unanswered_object(code: &str, words: &str) -> bool {    if matches!(code, "offline" | "internal_error" | UNANSWERED) {        return true;    }    words.match_indices("status ").any(|(at, said)| {        let starts_a_word = !words[..at].chars().next_back().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');        let digits: String = words[at + said.len()..].chars().take_while(char::is_ascii_digit).collect();        let ends_a_word = !words[at + said.len() + digits.len()..].chars().next().is_some_and(|c| c.is_ascii_alphanumeric());        starts_a_word && ends_a_word && digits.parse::<u16>().is_ok_and(|status| status == 0 || status == 429 || (500..600).contains(&status))    })}/// The object's word that it no longer takes this phone's credential — a 401/// to a pass (revoked, expired, or never one it knew). Held across passes:/// once said, no pass dials the object with that credential again, and/// `heard` is told once, so the app can sign the phone out. The copy is/// untouched; a fresh sign-in connects it again.pub struct SignedOut {    said: Mutex<Option<ObjectRefusal>>,    heard: Box<dyn Fn(&ObjectRefusal) + Send + Sync>,}impl SignedOut {    pub fn new(heard: impl Fn(&ObjectRefusal) + Send + Sync + 'static) -> Arc<SignedOut> {        Arc::new(SignedOut { said: Mutex::new(None), heard: Box::new(heard) })    }    /// What the object said, once it has.    pub fn said(&self) -> Option<ObjectRefusal> {        self.said.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    fn say(&self, refusal: &ObjectRefusal) {        let first = {            let mut said = self.said.lock().unwrap_or_else(|poisoned| poisoned.into_inner());            let first = said.is_none();            if first {                *said = Some(refusal.clone());            }            first        };        if first {            (self.heard)(refusal);        }    }}impl std::fmt::Debug for SignedOut {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("SignedOut").field("said", &self.said()).finish_non_exhaustive()    }}impl ObjectAddress {    pub fn named(server: &str, slug: &str) -> Result<ObjectAddress, String> {        let server = normalize_server_url(server).ok_or_else(|| "`server` is not an address this phone dials".to_string())?;        let origin = Origin::parse(&server)?;        let slug = slug.trim().to_ascii_lowercase();        if slug.is_empty() || !slug.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') {            return Err("`slug` names the database: letters, digits and dashes".to_string());        }        let host = origin.host.as_str();        let unnamed = host.ends_with(".workers.dev")            || host == "localhost"            || host == "127.0.0.1"            || host.ends_with(".local")            || host.starts_with("192.168.")            || host.starts_with("10.");        let prefix = if unnamed { format!("/b/{slug}") } else { String::new() };        Ok(ObjectAddress { origin, slug, prefix })    }    /// The open host: every person's one address (`https://cottondb.com`).    /// Nothing in the URL names the object; the sign-in finds the database    /// by number, and every later request's bearer (`ctd_<database>_…`)    /// names it.    pub fn open(server: &str) -> Result<ObjectAddress, String> {        let server = normalize_server_url(server).ok_or_else(|| "`server` is not an address this phone dials".to_string())?;        let origin = Origin::parse(&server)?;        Ok(ObjectAddress { origin, slug: String::new(), prefix: String::new() })    }    pub fn slug(&self) -> &str {        &self.slug    }    pub fn origin(&self) -> &Origin {        &self.origin    }    /// The whole address of a route: what a photo is shown from.    pub fn url(&self, path: &str) -> String {        format!("{}{}{}", self.origin.text, self.prefix, path)    }    /// One request, answered as JSON: a 2xx's body, `{"unchanged": true}` for a    /// 304, and anything else the object's refusal.    pub fn send(        &self,        exchange: &dyn Exchange,        method: &str,        path: &str,        headers: Vec<(String, String)>,        body: Option<&Value>,    ) -> Result<Value, ObjectRefusal> {        let (status, bytes) = self.send_bytes(exchange, method, path, headers, body)?;        answer_of(status, &bytes)    }    /// One request, answered as its status and bytes: what a photo is.    pub fn send_bytes(        &self,        exchange: &dyn Exchange,        method: &str,        path: &str,        headers: Vec<(String, String)>,        body: Option<&Value>,    ) -> Result<(u16, Vec<u8>), ObjectRefusal> {        let bytes = body.map(|body| body.to_string().into_bytes());        let mut headers = headers;        if bytes.is_some() {            headers.push(("Content-Type".into(), "application/json".into()));        }        // An answer comes gzipped when the object's front compresses it (FIRST SYNC FAST: a sync page of sealed rows        // is base64 in JSON, about a third smaller gzipped). Only a GET asks: a post's answer is small.        if method == "GET" && !sync_plain() && !headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("accept-encoding")) {            headers.push(("Accept-Encoding".into(), "gzip".into()));        }        let path = format!("{}{}", self.prefix, path);        let authority = self.origin.authority();        let request = Http1Request { method, path: &path, authority: &authority, headers, body: bytes.as_deref() };        let sent_at = std::time::Instant::now();        let mut answer = exchange.send(&self.origin, &request, CEILING).map_err(ObjectRefusal::offline)?;        let head_ms = sent_at.elapsed().as_millis();        let status = answer.status();        let gzipped = super::http1::Inflating::<&[u8]>::is_gzip(answer.header("content-encoding").as_deref());        let mut text = Vec::new();        super::http1::Inflating::new(answer.by_ref(), gzipped)            .take(ANSWER_LIMIT)            .read_to_end(&mut text)            .map_err(|error| ObjectRefusal::offline(format!("the answer did not arrive ({error})")))?;        if sync_times() && path.contains("/sync") {            eprintln!("[sync-times] wire {method} head_ms={head_ms} body_ms={} bytes={} gzipped={gzipped}", sent_at.elapsed().as_millis() - head_ms, text.len());        }        Ok((status, text))    }}impl ObjectAddress {    /// The bytes behind one media key the object keeps, at `width` when asked    /// (the object resizes; nothing on the phone does), streamed into `dest`    /// rather than held: a video is hundreds of megabytes.    pub fn fetch_media_to(        &self,        exchange: &dyn Exchange,        credential: &str,        key: &str,        width: Option<u32>,        dest: &Path,    ) -> Result<(), ObjectRefusal> {        let mut path = format!("{}{}", self.prefix, media_path(key));        if let Some(width) = width {            path.push_str(&format!("?width={width}"));        }        let authority = self.origin.authority();        let request = Http1Request { method: "GET", path: &path, authority: &authority, headers: bearer(credential), body: None };        let mut answer = exchange.send(&self.origin, &request, MEDIA_CEILING).map_err(ObjectRefusal::offline)?;        let status = answer.status();        if !(200..300).contains(&status) {            let mut text = Vec::new();            let _ = answer.by_ref().take(64 * 1024).read_to_end(&mut text);            let value: Value = serde_json::from_slice(&text).unwrap_or(Value::Null);            return Err(ObjectRefusal {                status,                code: value["code"].as_str().unwrap_or("refused").to_string(),                message: value["message"].as_str().unwrap_or("the object did not send that picture").to_string(),            });        }        // not a copy: a picture fetched from the object, into the media folder.        let mut file = std::fs::File::create(dest).map_err(|error| ObjectRefusal::offline(format!("{} could not be written ({error})", dest.display())))?;        std::io::copy(&mut answer, &mut file).map_err(|error| ObjectRefusal::offline(format!("the picture did not arrive ({error})")))?;        Ok(())    }    /// `len` bytes of `key` from `offset` (one `Range` read, R6's seek), and    /// the whole object's length the answer said (`Content-Range`'s total, or    /// its `Content-Length` when the object sent it whole).    pub fn fetch_media_range(&self, exchange: &dyn Exchange, credential: &str, key: &str, offset: u64, len: u64) -> Result<(Vec<u8>, u64), ObjectRefusal> {        let path = format!("{}{}", self.prefix, media_path(key));        let authority = self.origin.authority();        let mut headers = bearer(credential);        headers.push(("Range".into(), format!("bytes={offset}-{}", offset + len.max(1) - 1)));        let request = Http1Request { method: "GET", path: &path, authority: &authority, headers, body: None };        let mut answer = exchange.send(&self.origin, &request, MEDIA_CEILING).map_err(ObjectRefusal::offline)?;        let status = answer.status();        if !(200..300).contains(&status) {            let mut text = Vec::new();            let _ = answer.by_ref().take(64 * 1024).read_to_end(&mut text);            let value: Value = serde_json::from_slice(&text).unwrap_or(Value::Null);            return Err(ObjectRefusal {                status,                code: value["code"].as_str().unwrap_or("refused").to_string(),                message: value["message"].as_str().unwrap_or("the object did not send that range").to_string(),            });        }        let total = match answer.header("content-range").and_then(|range| range.rsplit('/').next().and_then(|t| t.trim().parse::<u64>().ok())) {            Some(total) => total,            None => answer.content_length().ok_or_else(|| ObjectRefusal::offline("the object said no length for this file".to_string()))?,        };        let mut bytes = Vec::new();        answer.read_to_end(&mut bytes).map_err(|error| ObjectRefusal::offline(format!("the range did not arrive ({error})")))?;        if status == 200 {            // Sent whole: the slice asked for.            let from = (offset as usize).min(bytes.len());            let to = (offset.saturating_add(len) as usize).min(bytes.len());            bytes = bytes[from..to].to_vec();        }        Ok((bytes, total))    }    /// One request whose body is `length` bytes STREAMED off `body` — a file    /// going up, never held whole — answered as JSON like [`Self::send`].    #[allow(clippy::too_many_arguments)]    pub fn send_file(        &self,        exchange: &dyn Exchange,        method: &str,        path: &str,        headers: Vec<(String, String)>,        body: &mut dyn Read,        length: u64,    ) -> Result<Value, ObjectRefusal> {        let path = format!("{}{}", self.prefix, path);        let authority = self.origin.authority();        let request = Http1Request { method, path: &path, authority: &authority, headers, body: None };        let mut answer = exchange.send_stream(&self.origin, &request, body, length, MEDIA_CEILING).map_err(ObjectRefusal::offline)?;        let status = answer.status();        let mut text = Vec::new();        answer            .by_ref()            .take(ANSWER_LIMIT)            .read_to_end(&mut text)            .map_err(|error| ObjectRefusal::offline(format!("the answer did not arrive ({error})")))?;        answer_of(status, &text)    }}/// The route of one media key: `/v1/media/<key>`, each segment/// percent-encoded and the key's own `/` kept (the Mac's `media_path`, and/// what the Worker's `decodeURIComponent` reads back).pub fn media_path(key: &str) -> String {    let mut out = String::from(routes::MEDIA);    for (n, segment) in key.split('/').enumerate() {        if n > 0 {            out.push('/');        }        for byte in segment.bytes() {            match byte {                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(byte as char),                _ => out.push_str(&format!("%{byte:02X}")),            }        }    }    out}/// One answer as JSON: a 2xx's body, `{"unchanged": true}` for a 304, and/// anything else the object's refusal.fn answer_of(status: u16, bytes: &[u8]) -> Result<Value, ObjectRefusal> {    let value: Value = serde_json::from_slice(bytes).unwrap_or(Value::Null);    if (200..300).contains(&status) {        return Ok(value);    }    if status == 304 {        return Ok(json!({"unchanged": true}));    }    Err(ObjectRefusal {        status,        code: value["code"].as_str().unwrap_or("refused").to_string(),        message: value["message"].as_str().unwrap_or("the object refused").to_string(),    })}/// The width a `.t256.jpg` thumbnail is drawn at by the object.pub const THUMB_WIDTH: u32 = 256;/// The width a `.d1600.jpg` display rendition is drawn at by the object.pub const DISPLAY_WIDTH: u32 = 1600;/// A rendition key the phone asks for (`…/photos/<sha>.t256.jpg`,/// `…/videos/<sha>.d1600.jpg`, `…/documents/<sha>.t256.jpg` for a document/// that is a picture), as what the object keeps: the original's folder/// (`photos`, `videos` or `documents`), its hash, and the width the rendition/// is drawn at. `None` for a key that is an object's own.pub fn rendition(key: &str) -> Option<(&str, &str, u32)> {    use cotton_core::media::keys::{DISPLAY_SUFFIX, THUMB_SUFFIX};    let (head, file) = key.rsplit_once('/')?;    let folder = head.rsplit_once('/').map_or(head, |(_, folder)| folder);    if !matches!(folder, "photos" | "videos" | "documents") {        return None;    }    if let Some(sha) = file.strip_suffix(THUMB_SUFFIX) {        return Some((folder, sha, THUMB_WIDTH));    }    file.strip_suffix(DISPLAY_SUFFIX).map(|sha| (folder, sha, DISPLAY_WIDTH))}/// The credential as the bearer: the only place it goes.pub fn bearer(credential: &str) -> Vec<(String, String)> {    let mut bearer = String::from("Bearer ");    bearer.push_str(credential);    vec![("Authorization".into(), bearer)]}// ── which object table is which of this phone's ────────────────────────────/// One object table as this phone stores it.#[derive(Debug, Clone)]pub struct StoredTable {    /// The object's table (`todo`).    pub table: String,    /// The table it fills here: one this build compiles (`cotton_todos`), or    /// the one a served definition's columns make (`cotton_quota`).    pub store: String,    /// The key column (`id`, or `workspace_id` for a one-row settings table).    pub key_column: String,    /// Whether the rows carry `workspace_id`.    pub workspace: bool,    /// Each object column, its column here and that column's codec.    pub columns: Vec<(String, String, Codec)>,    /// Each column a served definition names on a table this build compiles    /// that the build's table lacks, kept here under the object's key: the    /// copy's table gains it before a row of the table folds, and the pull    /// writes it — what the object fills is never dropped (owner, 27 Oct    /// 2026: the running balance its money engine writes on every    /// transaction). It is the object's to write — but for one the    /// definition leaves the person (`written`).    pub served: Vec<ServedColumn>,    /// The served columns the definition leaves the person (neither    /// read-only nor computed: an event's kind, chosen on the fan): a write    /// here sends them with the columns above, as the copy holds them.    pub written: Vec<String>,    /// The columns here (by this build's name) the object's definition holds    /// several values in (`multiple`: a mood's emotions) that this build's    /// table keeps as their JSON text: a list the object serves is laid as    /// that text, and the text goes back to the object as the list it is.    pub lists: Vec<String>,    /// The table's `seal` block when it is sealed (sealing plan §2.2), from    /// its definition: the kit's for a table this build compiles, the    /// object's for any other. A sealed table's rows are opened on the way    /// down and sealed on the way up ([`crate::seal`]).    pub seal: Option<cotton_core::definitions::seal::SealSpec>,    /// Whether the table here keeps `created_at` / `updated_at`.    created_at: bool,    /// The table keeps when the object took the row by its own clock (`cotton_emails.landed_at`, schema 157; the    /// row's `landed_at` beside `created_at`, sent for mail only): what a mail cut is bounded by.    landed_at: bool,    updated_at: bool,    /// Whether this build compiles the table here.    compiled: bool,    /// A table this build compiles whose definition it does not carry (an    /// app's build carries its own kit's files: Todos has no `news_settings`    /// file) and the seal rule does not leave open: whether it is sealed is    /// unknown until the object's definition of it is placed, and until then    /// its writes wait, retryable, and nothing goes in the clear (e2e rulings    /// R1: walk todos-sealed sent news_settings clear at sign-in).    awaiting_seal: bool,}/// Every object table this phone stores, both ways: by the object's name and/// by the store's.#[derive(Debug, Clone)]pub struct ObjectTables {    tables: Vec<StoredTable>,    by_object: HashMap<String, usize>,    by_store: HashMap<String, usize>,}#[derive(serde::Deserialize)]struct StorageEntry {    table: String,    from: String,    key: String,    workspace: bool,    columns: BTreeMap<String, String>,}impl StoredTable {    /// Whether this table's writes wait for the object's definition of it to say whether it is sealed (`awaiting_seal`).    pub fn awaits_seal(&self) -> bool {        self.awaiting_seal && self.seal.is_none()    }    /// The refusal a write of a table awaiting its definition is held by: retryable, by name, never sent clear.    fn awaiting_refusal(&self) -> cotton_core::seal::SealError {        cotton_core::seal::SealError::KeyMissing(format!("{}'s definition (this build carries none, and the object's has not been read yet)", self.table))    }    /// Whether a row's `key` lands in a column here.    pub fn places(&self, key: &str) -> bool {        self.columns.iter().any(|(object, _, _)| object == key) || self.served.iter().any(|column| column.name == key)    }    /// `value` of the object's column kept here as `ours`, as this build's    /// column holds it: a list in a column of [`StoredTable::lists`] is its    /// JSON text — what this build writes there itself    /// (`rules::emotions::encode_emotions`) — and anything else is itself.    fn laid(&self, ours: &str, value: &Value) -> Value {        match value {            Value::Array(_) if self.lists.iter().any(|list| list == ours) => Value::String(cotton_store::protocol::js::json_stringify(value)),            _ => value.clone(),        }    }    /// The value of `ours` this copy holds, as the object holds it: the JSON    /// text of a column of [`StoredTable::lists`] is the list it says.    fn sent(&self, ours: &str, value: Value) -> Value {        match &value {            Value::String(text) if self.lists.iter().any(|list| list == ours) => match serde_json::from_str::<Value>(text) {                Ok(list @ Value::Array(_)) => list,                _ => value,            },            _ => value,        }    }}impl ObjectTables {    /// The object tables whose rows this build keeps in tables it compiles,    /// as it ships them (`cotton_core::toolkits::PERSONAL_STORAGE`). Every    /// other table the object serves is kept as its definition's columns make    /// it ([`ObjectTables::with_defined`]).    pub fn personal() -> Arc<ObjectTables> {        static SHIPPED: OnceLock<Arc<ObjectTables>> = OnceLock::new();        Arc::clone(SHIPPED.get_or_init(|| {            Arc::new(ObjectTables::read(cotton_core::toolkits::PERSONAL_STORAGE).expect("the shipped storage map reads against this build's store"))        }))    }    /// A map read against this build's store: a table or column the store    /// does not have is a refusal, never a gap.    pub fn read(text: &str) -> Result<ObjectTables, String> {        let entries: Vec<StorageEntry> = serde_json::from_str(text).map_err(|error| format!("the storage map does not read ({error})"))?;        let mut tables = Vec::with_capacity(entries.len());        for entry in entries {            let spec: &'static TableSpec = cotton_store::schema::specs::spec_for(&entry.from).ok_or_else(|| format!("this build's store has no table {}", entry.from))?;            let codec_of = |column: &str| spec.columns.iter().find(|(name, _)| *name == column).map(|(_, codec)| *codec);            let mut columns = Vec::with_capacity(entry.columns.len());            for (object, ours) in &entry.columns {                let codec = codec_of(ours).ok_or_else(|| format!("{} has no column {ours} for {}.{object}", entry.from, entry.table))?;                columns.push((object.clone(), ours.clone(), codec));            }            if codec_of(&entry.key).is_none() {                return Err(format!("{} has no key column {}", entry.from, entry.key));            }            // The kit's definition says whether the table is sealed, as the            // seal rule makes it (e2e rulings R1): its own block, or the            // default a personal table with none takes, as the object serves it.            let file = cotton_core::kit::table_file(&entry.table);            let seal = match file {                Some(file) => crate::seal::spec_of_definition(&cotton_core::seal::rule::ruled(&serde_json::from_slice::<Value>(file).map_err(|error| format!("the kit's {} table does not read ({error})", entry.table))?))?,                None => None,            };            let awaiting_seal = file.is_none() && cotton_core::seal::rule::open_by_design(&entry.table).is_none() && cotton_core::seal::rule::pending(&entry.table).is_none();            tables.push(StoredTable {                seal,                created_at: codec_of("created_at").is_some(),                landed_at: codec_of("landed_at").is_some(),                updated_at: codec_of("updated_at").is_some(),                table: entry.table,                store: spec.name.to_string(),                key_column: entry.key,                workspace: entry.workspace,                columns,                served: Vec::new(),                written: Vec::new(),                lists: Vec::new(),                compiled: true,                awaiting_seal,            });        }        Ok(ObjectTables::of(tables))    }    /// This map once `served` is known to be the object's whole answer (a    /// sign-in's restore or adopt): a compiled table still awaiting its    /// definition that the answer does not define is not one the object    /// seals, so its writes stop waiting.    pub fn answered(mut self, served: &[Value]) -> ObjectTables {        for table in self.tables.iter_mut().filter(|table| table.awaiting_seal) {            if !served.iter().any(|definition| definition["id"] == json!(table.table)) {                table.awaiting_seal = false;            }        }        self    }    /// This map with `open` unsealed: a fixture for tests that use a table    /// the rule seals now (todos, e2e rulings R3) as a plain open one.    #[cfg(test)]    pub(crate) fn opening(&self, open: &[&str]) -> ObjectTables {        let mut tables = self.tables.clone();        for table in tables.iter_mut().filter(|table| open.contains(&table.table.as_str())) {            table.seal = None;            table.awaiting_seal = false;        }        ObjectTables::of(tables)    }    fn of(tables: Vec<StoredTable>) -> ObjectTables {        let by_object = tables.iter().enumerate().map(|(i, t)| (t.table.clone(), i)).collect();        let by_store = tables.iter().enumerate().map(|(i, t)| (t.store.clone(), i)).collect();        ObjectTables { tables, by_object, by_store }    }    /// This map and every table `definitions` define that it does not hold    /// and whose rows are data: a made table (Quotas' `quota`), a kit's    /// (Books' `book`), a storage-only one with no home here (`oauth_code`),    /// each kept in the table its columns make (`cotton_<id>`, column for    /// column). A table kept by an engine keeps its rows in that engine's    /// tables or none of its own, and a view reads another's: neither is one.    ///    /// A definition of a table this build compiles adds to it every column it    /// names that the build's table lacks ([`served_columns`]), add-only: a    /// column one definition placed stays placed. A column of a type this    /// build does not know refuses the whole map, by name.    pub fn with_defined<'a>(&self, definitions: impl IntoIterator<Item = &'a Value>) -> Result<ObjectTables, String> {        let mut tables = self.tables.clone();        for definition in definitions {            if let Some(held) = definition["id"].as_str().and_then(|id| tables.iter_mut().find(|held| held.compiled && held.table == id)) {                // Sealed once its definition says so; never unsealed by a                // definition that says nothing (fail closed).                if let Some(seal) = crate::seal::spec_of_definition(definition)? {                    held.seal = Some(seal);                }                // The object's definition says it now, sealed or not.                held.awaiting_seal = false;                for column in served_columns(held, definition)? {                    // RULE (owner, 28 Nov 2026): a column a phone keeps on a sealed row that the object cannot rebuild                    // (`PHONE_KEPT_COLUMNS`: a group's log, a guest's answer, a pin) is the phone's own write and goes                    // sealed with the row, though the kit keeps it readonly for people and tools: kept only on the                    // phone, a copy filled from the object again lost every Cotton group.                    let chat_kept = held.seal.is_some() && kept_by_phone(&held.table, &column.name);                    let written = definition["columns"].as_array().into_iter().flatten().any(|defined| {                        defined["key"] == json!(column.name) && (defined["readonly"] != json!(true) || chat_kept) && defined["computed"].is_null()                    });                    if written && !held.written.contains(&column.name) {                        held.written.push(column.name.clone());                    }                    if !held.served.iter().any(|placed| placed.name == column.name) {                        held.served.push(column);                    }                }                // A column the definition holds several values in that this                // build keeps as text holds the list's JSON text here.                for defined in definition["columns"].as_array().into_iter().flatten().filter(|defined| defined["multiple"] == json!(true)) {                    let placed = held.columns.iter().find(|(object, _, codec)| defined["key"] == json!(object) && *codec == Codec::Text).map(|(_, ours, _)| ours.clone());                    if let Some(ours) = placed.filter(|ours| !held.lists.contains(ours)) {                        held.lists.push(ours);                    }                }                continue;            }            // A seal block that does not read refuses the map, by name.            crate::seal::spec_of_definition(definition)?;            let Some(table) = defined(definition) else { continue };            if let Some(held) = tables.iter_mut().find(|held| held.table == table.table || held.store == table.store) {                if table.seal.is_some() && held.table == table.table {                    held.seal = table.seal;                }                continue;            }            tables.push(table);        }        Ok(ObjectTables::of(tables))    }    pub fn object(&self, table: &str) -> Option<&StoredTable> {        self.by_object.get(table).map(|i| &self.tables[*i])    }    pub fn ours(&self, table: &str) -> Option<&StoredTable> {        self.by_store.get(table).map(|i| &self.tables[*i])    }    /// Whether this build keeps `table`'s rows in a table it compiles.    pub fn compiled(&self, table: &str) -> bool {        self.object(table).is_some_and(|t| t.compiled)    }    /// The object tables this phone stores, by the object's name.    pub fn names(&self) -> impl Iterator<Item = &str> {        self.tables.iter().map(|t| t.table.as_str())    }}/// The table a data definition's rows are kept in here, as its columns make/// it (`cotton_store::schema::package_shape::declared`): every column but a/// computed one, under its own key, by its type's codec.fn defined(definition: &Value) -> Option<StoredTable> {    let id = definition["id"].as_str()?;    if !definition["engine"].is_null() || !definition["source"].is_null() {        return None;    }    let store = format!("cotton_{id}");    let declared = cotton_store::schema::package_shape::declared(definition).ok()??;    let held = declared.into_iter().find(|table| table.table.name == store)?;    let columns = definition["columns"]        .as_array()?        .iter()        .filter(|column| column["computed"].is_null())        .filter_map(|column| {            let key = column["key"].as_str()?;            held.codecs.get(key).map(|codec| (key.to_string(), key.to_string(), *codec))        })        .collect();    // A seal block that does not read is no table here: never one kept open.    let seal = crate::seal::spec_of_definition(definition).ok()?;    Some(StoredTable { table: id.to_string(), store, key_column: "id".into(), workspace: true, columns, served: Vec::new(), written: Vec::new(), lists: Vec::new(), seal, created_at: true, landed_at: false, updated_at: true, compiled: false, awaiting_seal: false })}/// The columns `definition` names on `table` — one this build compiles —/// that the build's table lacks, each kept under the object's key by its/// type ([`package_shape::served_column`]). Never one the storage map already/// places, under the object's key or as the column it renames one to (a/// note's `project` kept as `project_id`); never one the build's table holds;/// never a computed one, which no table keeps; never the row's own address/// and times, which a row carries beside its data; and never a person's own/// (`own_<key>`), which the store adds itself when the definition lands/// (`package_shape::step_own`).fn served_columns(table: &StoredTable, definition: &Value) -> Result<Vec<ServedColumn>, String> {    let spec = cotton_store::schema::specs::spec_for(&table.store).ok_or_else(|| format!("this build's store has no table {}", table.store))?;    let mut served = Vec::new();    for column in definition["columns"].as_array().into_iter().flatten() {        let column_name = column["key"].as_str().ok_or_else(|| format!("the object's {} table names a column with no key", table.table))?;        let placed = table.columns.iter().any(|(object, ours, _)| object == column_name || ours == column_name);        let builds = spec.columns.iter().any(|(name, _)| *name == column_name);        if placed            || builds            || !column["computed"].is_null()            || matches!(column_name, "id" | "workspace_id" | "created_at" | "updated_at")            || column_name.starts_with(package_shape::OWN_PREFIX)        {            continue;        }        let kind = column["type"].as_str().ok_or_else(|| format!("the object's {}.{column_name} names no type", table.table))?;        served.push(package_shape::served_column(column_name, kind, column["multiple"] == json!(true)).map_err(|error| format!("the object's {} table: {error}", table.table))?);    }    Ok(served)}/// The kit columns Cotton Chat writes on a copy before any object's/// definitions reach it (owner, 1 Nov 2026: Cotton works before sign-in):/// the message ids pinned in a conversation, kept on its thread row so the/// pinned bar reads one row however long the conversation is, and the/// reactions, edits and deletes waiting to be told to the other side.pub const CHAT_KEPT_COLUMNS: &[(&str, &[&str])] = &[("thread", &["pinned_messages", "changes_waiting", "group_log"])];/// Every column a phone keeps on a copy that the object cannot rebuild: each goes sealed with its row.pub const PHONE_KEPT_COLUMNS: &[&[(&str, &[&str])]] = &[CHAT_KEPT_COLUMNS, DAYS_KEPT_COLUMNS, NOTES_KEPT_COLUMNS];/// Whether `column` of `table` is one a phone keeps (`PHONE_KEPT_COLUMNS`).fn kept_by_phone(table: &str, column: &str) -> bool {    PHONE_KEPT_COLUMNS.iter().flat_map(|list| list.iter()).any(|(kept, columns)| *kept == table && columns.contains(&column))}/// The kit columns Cotton Days writes on a copy before any definition/// reaches it (Cotton works before sign-in): a to-do's and an event's mark,/// and on an event the person's own note and alert, which on a Google event/// are theirs and survive the next pull (assets/design/days/CONTRACT.md)./// People on an event (22 Nov 2026, CONTRACT.md sections 15 to 17): Google's/// guests and answers as the pull brings them, an invitation received, and/// each person's way of hearing of it.pub const DAYS_KEPT_COLUMNS: &[(&str, &[&str])] = &[    ("todo", &["mark"]),    ("event", &["mark", "your_note", "alert", "guest_responses", "invited", "source"]),    ("event_attendee", &["via", "sent", "removed_at", "role"]),];/// The kit columns Cotton Notes writes on a copy before any definition/// reaches it: the tags a note is pinned inside (assets/design/notes/CONTRACT.md).pub const NOTES_KEPT_COLUMNS: &[(&str, &[&str])] = &[("note", &["pinned_in"])];/// Make the copy keep the named kit columns its build's tables lack, as a/// copy does when the object's definitions name them; add-only, a column/// already kept stays. Returns `<table>.<column>` for each column added.pub fn keep_kit_columns(db: &cotton_store::Driver, wanted: &[(&str, &[&str])]) -> Result<Vec<String>, String> {    let mut added = Vec::new();    for (id, names) in wanted {        let file = cotton_core::kit::table_file(id).ok_or_else(|| format!("this build's kit defines no {id} table"))?;        let kit: Value = serde_json::from_slice(file).map_err(|error| format!("the kit's {id} table does not read ({error})"))?;        let map = ObjectTables::personal().with_defined(std::iter::once(&kit))?;        let Some(table) = map.object(id).filter(|table| table.compiled) else { continue };        let served: Vec<_> = table.served.iter().filter(|column| names.contains(&column.name.as_str())).cloned().collect();        if served.is_empty() {            continue;        }        added.extend(            package_shape::add_served(db, &table.store, &served)                .map_err(|error| format!("this copy could not keep the kit's columns of {id} ({error})"))?,        );    }    Ok(added)}/// Make the copy keep the columns this build's kit names on the tables a/// money run is written on (`cotton_core::rules::money::balances::RUN_TABLES`)/// that the build's tables lack — the balances the run fills and the known/// balance a person states — as a copy does when the object's definitions/// name them ([`ObjectTransport::hold_served`]). A local copy holds no/// object's definitions, and works its money run all the same (owner, 1 Nov/// 2026: Cotton works before sign-in). Add-only; a column already kept stays./// Returns `<table>.<column>` for each column added.pub fn keep_run_columns(db: &cotton_store::Driver) -> Result<Vec<String>, String> {    let kit: Vec<Value> = cotton_core::rules::money::balances::RUN_TABLES        .iter()        .map(|id| {            let file = cotton_core::kit::table_file(id).ok_or_else(|| format!("this build's kit defines no {id} table"))?;            serde_json::from_slice(file).map_err(|error| format!("the kit's {id} table does not read ({error})"))        })        .collect::<Result<_, String>>()?;    let map = ObjectTables::personal().with_defined(kit.iter())?;    let mut added = Vec::new();    for id in cotton_core::rules::money::balances::RUN_TABLES {        let Some(table) = map.object(id).filter(|table| table.compiled && !table.served.is_empty()) else { continue };        added.extend(            package_shape::add_served(db, &table.store, &table.served)                .map_err(|error| format!("this copy could not keep the kit's columns of {id} ({error})"))?,        );    }    Ok(added)}// ── the transport ──────────────────────────────────────────────────────────/// One pass's way to the object. Made per pass by the loop's factory; what/// lasts between passes is in the replica (`_cursors`).pub struct ObjectTransport {    address: ObjectAddress,    exchange: Arc<dyn Exchange>,    credential: String,    /// This pass's map of the object's tables to this copy's: the tables this    /// build compiles (as handed in), with every table the copy's definitions    /// define as data ([`ObjectTables::with_defined`]) and those of a    /// definitions answer this pass takes.    tables: Mutex<Arc<ObjectTables>>,    /// The replica file, read for the row an op names.    replica: PathBuf,    /// `table:days` the first page of a pull keeps to.    windows: Vec<(String, u32)>,    last: Mutex<Option<ServerRefusal>>,    signed_out: Option<Arc<SignedOut>>,    progress: Option<Arc<SyncProgress>>,    /// The state this device says of itself, supplied by the running app.    reported_state: Option<Arc<dyn Fn() -> Option<Value> + Send + Sync>>,    /// The pages of a long pull this transport has taken since its checkpoints were held (`hold_checkpoints`).    held_pages: std::sync::atomic::AtomicU32,    /// What this phone is called, said on each pass's first page.    named: Option<DeviceNamed>,    /// The object's definitions as this launch last took them; none, and no    /// pass asks for them.    definitions: Option<Arc<HeldDefinitions>>,    discarded: Option<(crate::layout::Layout, String)>,    /// Whether this launch has posted the rows a backup kept again ([`ObjectTransport::post_kept_rows`]).    kept_tried: std::sync::atomic::AtomicBool,    /// Each table's columns that cannot hold nothing here, with what this    /// copy holds for nothing in them ([`ObjectTransport::nothing_in`]), read    /// off the copy once a pass.    nothing: Mutex<HashMap<String, Arc<BTreeMap<String, Value>>>>,    /// The writes this pass's push handed to the object and it took (or    /// refused for good): still in the outbox until the pass settles them,    /// but no longer waiting to be sent ([`waiting_definitions`]).    taken: Mutex<std::collections::BTreeSet<String>>,    /// The page just pulled opened parked rows and left the kit's late    /// tables' parked for the next pass ([`Self::reopened`]): the pass rests    /// there ([`RefusalAware::rests`]), so what opened is drawn first.    rest: std::sync::atomic::AtomicBool,    /// The rows the page just pulled opened from their parks: their parks go    /// once the page has folded ([`RefusalAware::folded`]), never before, so    /// a fold that fails finds them parked again (a parked row has no other    /// copy). Should the app stop between the two, the next pass finds them    /// standing and lets them go then ([`Self::stands`]).    unparks: Mutex<Vec<(String, String, i64)>>,    /// This pass's pull reached the object's end: every row waiting for a parent is tried once more after its fold    /// (FIRST SYNC 6).    caught_up: std::sync::atomic::AtomicBool,    /// The rows whose post the object refused as moved, whose newer text a    /// pull keeps ([`crate::seal::EDIT_BASE`]).    moved: Mutex<std::collections::BTreeSet<(String, String)>>,    /// Sealed tables whose change never goes up unless held to the version this copy read (HIDDEN 5, review 4 M2):    /// a whole sealed row resealed from a copy that never read the object's version would put this copy's older    /// sealed columns back over another device's, and a list's `hidden` flag lost that way is lost for good. With no    /// version held, the change reads that one row from the object, lays itself over it and goes held to its version    /// ([`Self::object_row`]; HIDDEN 6).    held_to_version: std::collections::BTreeSet<String>,    /// Requests this transport has made (posts and row reads): a write that reads its row and posts again costs what    /// it asked, against [`POSTS_PER_PASS`] (UNSENT HEAL 5, review M3).    requests: std::sync::atomic::AtomicUsize,    /// When this pass's last page came back, for its fold's time ([`crate::first_sync`], PHONE MEASURES).    pulled_at: Mutex<Option<std::time::Instant>>,    /// Whether that page leaves the copy level once folded: its first sync, if under way, ends then.    level_after_fold: std::sync::atomic::AtomicBool,    /// Now, in ms since the epoch, for the waits kept in the copy ([`Self::read_row`]); the system clock unless a test    /// sets its own ([`Self::on_clock`]).    clock: Arc<dyn Fn() -> i64 + Send + Sync>,    /// The copy, lent by the pass that made this transport    /// ([`RefusalAware::lend_file`]): what the columns the object's    /// definitions name are added through ([`ObjectTransport::hold_served`]).    file: Option<Arc<dyn crate::sync::cycle::LendsFile + Send + Sync>>,    /// The kit this app keeps to ([`kept_to`]): none is the whole object.    kit: Option<Arc<cotton_core::kit::AppKit>>,    /// The database's sealing on this device ([`crate::seal::Sealer`]): none,    /// and a sealed table's rows park and its writes wait, by name.    sealer: Option<Arc<crate::seal::Sealer>>,    /// The object answered `seal_many` with `unknown_act` (one from before it): this pass seals one row a round trip.    seal_one_by_one: std::sync::atomic::AtomicBool,    /// Asked before a fill's pull ([`ObjectTransport::stopping_for`]): a reason holds the fill there, the cursor where it    /// stood, nothing dropped, the pass not failed. Cotton Data's room guard (Keep everything leaves 2 GB of the phone free).    stop: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>,    /// The server's generation this copy holds ([`GENERATION_KEY`]): unread (`None`) until first asked, then what the    /// copy holds, or the first one answered when it held none.    generation: Mutex<Option<Option<String>>>,    /// This pass met the server's [`ACCOUNT_FROZEN`].    frozen: std::sync::atomic::AtomicBool,}/// What a phone says of itself on a pass's first page: the object files a/// signed-in device it holds no row for under its credential's device id from/// these (`apps/business/src/sync_status.ts` `fileDevice`).#[derive(Debug, Clone, PartialEq, Eq)]pub struct DeviceNamed {    pub name: String,    pub platform: Option<String>,    pub app_version: Option<String>,}impl std::fmt::Debug for ObjectTransport {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("ObjectTransport").field("address", &self.address).field("replica", &self.replica).finish_non_exhaustive()    }}impl ObjectTransport {    pub fn new(        address: ObjectAddress,        exchange: Arc<dyn Exchange>,        credential: String,        tables: Arc<ObjectTables>,        replica: PathBuf,        windows: Vec<(String, u32)>,    ) -> ObjectTransport {        ObjectTransport {            address,            exchange,            credential,            tables: Mutex::new(tables),            replica,            windows,            last: Mutex::new(None),            signed_out: None,            progress: None,            reported_state: None,            held_pages: std::sync::atomic::AtomicU32::new(0),            named: None,            definitions: None,            discarded: None,            kept_tried: std::sync::atomic::AtomicBool::new(false),            nothing: Mutex::new(HashMap::new()),            taken: Mutex::new(std::collections::BTreeSet::new()),            rest: std::sync::atomic::AtomicBool::new(false),            unparks: Mutex::new(Vec::new()),            caught_up: std::sync::atomic::AtomicBool::new(false),            moved: Mutex::new(std::collections::BTreeSet::new()),            requests: std::sync::atomic::AtomicUsize::new(0),            pulled_at: Mutex::new(None),            level_after_fold: std::sync::atomic::AtomicBool::new(false),            clock: Arc::new(|| chrono::Utc::now().timestamp_millis()),            held_to_version: ["record_group".to_string()].into_iter().collect(),            file: None,            kit: None,            sealer: None,            seal_one_by_one: std::sync::atomic::AtomicBool::new(false),            stop: None,            generation: Mutex::new(None),            frozen: std::sync::atomic::AtomicBool::new(false),        }    }    /// Open and seal the rows of sealed tables with `sealer`'s key.    pub fn sealing_with(mut self, sealer: Arc<crate::seal::Sealer>) -> ObjectTransport {        self.sealer = Some(sealer);        self    }    /// Where permanent definition refusals are filed for Feedback.    pub fn discarding_to(mut self, layout: crate::layout::Layout, database: String) -> Self {        self.discarded = Some((layout, database));        self    }    /// Tell `signed_out` when the object stops taking the credential.    pub fn signing_out_to(mut self, signed_out: Arc<SignedOut>) -> ObjectTransport {        self.signed_out = Some(signed_out);        self    }    /// Keep this phone's passes in `progress`, which outlives the pass, and    /// write what only the phone knows of them on its own device row    /// ([`SyncProgress`]).    pub fn reporting_to(mut self, progress: Arc<SyncProgress>) -> ObjectTransport {        progress.knows(&self.map());        self.progress = Some(progress);        self    }    /// Post this device's runtime state whenever a pass completes. Only the    /// app knows its bundle build and commit, so it supplies the state here.    pub fn reporting_state_to(mut self, state: Arc<dyn Fn() -> Option<Value> + Send + Sync>) -> ObjectTransport {        self.reported_state = Some(state);        self    }    /// Say what this phone is called on each pass's first page ([`DeviceNamed`]).    pub fn naming(mut self, named: DeviceNamed) -> ObjectTransport {        self.named = Some(named);        self    }    /// One row as the object holds it now (`GET /v1/rows`, the owner's own devices), opened with this copy's key.    fn object_row(&self, table: &StoredTable, id: &str) -> Result<Result<ObjectRow, ObjectRefusal>, String> {        // Table names and row ids are plain (as `again=` sends them); one that is not is not asked for.        let plain = |text: &str| !text.is_empty() && text.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');        if !plain(&table.table) || !plain(id) {            return Ok(Ok(ObjectRow::Unopened));        }        let path = format!("/v1/rows?table={}&ids={id}", table.table);        self.requests.fetch_add(1, std::sync::atomic::Ordering::Relaxed);        let answer = match self.address.send(self.exchange.as_ref(), "GET", &path, bearer(&self.credential), None) {            Ok(answer) => answer,            Err(refusal) => return Ok(Err(refusal)),        };        // An answer with no list of rows says nothing of the row (never "gone"); a list without it says the object holds        // no live row of that id (the Worker leaves deleted rows out; a binned row is there, with its bin mark).        let Some(rows) = answer["rows"].as_array() else { return Ok(Ok(ObjectRow::Unopened)) };        let Some(row) = rows.iter().find(|row| row["id"] == id) else { return Ok(Ok(ObjectRow::Absent)) };        let version = row["version"].as_i64().unwrap_or(0);        if row["deleted"] == json!(true) {            return Ok(Ok(ObjectRow::Absent));        }        let mut row = row.clone();        if row.get("table").is_none() {            row["table"] = json!(table.table);        }        // Its version is used for the one post made from this read and NEVER kept on its own: a version in `_seal`        // always describes data this copy holds, so a post that fails leaves the copy's own older version, and the        // next try is refused as moved and reads again (UNSENT HEAL 5, review HIGH: a kept version over stale data        // let the next post put this copy's old sealed columns over another device's change).        let opened = match crate::seal::unseal(self.sealer.as_deref(), table.seal.as_ref(), &row, "") {            None => Some(row),            Some((opened, _note)) => opened,        };        Ok(Ok(match opened.and_then(|opened| opened["data"].as_object().cloned()) {            Some(data) if version > 0 => ObjectRow::Opened(version, data),            _ => ObjectRow::Unopened,        }))    }    /// Keep the waits in the copy on `clock` (ms since the epoch) instead of the system's: tests.    pub fn on_clock(mut self, clock: impl Fn() -> i64 + Send + Sync + 'static) -> ObjectTransport {        self.clock = Arc::new(clock);        self    }    /// Hold `table`'s changes to the version read too ([`Self::held_to_version`]; tests name their own table).    pub fn holding_to_version(mut self, table: &str) -> ObjectTransport {        self.held_to_version.insert(table.to_string());        self    }    /// Keep the copy's tables, tools and boards to the object's ([`HeldDefinitions`]).    pub fn taking_definitions(mut self, held: Arc<HeldDefinitions>) -> ObjectTransport {        self.definitions = Some(held);        self    }    /// Keep this app to its kit: the copy takes only the kit's tools and    /// tables of what the object serves ([`kept_to`]), and a pull asks for    /// the kit's tables alone (`tables=`). None is the whole object.    /// Ask `stop` before a fill's pull (one from the start, or one owing tables whole): while it gives a reason, the pull    /// asks nothing and the pass ends well, its writes sent, its cursor where it stood, so the next pass goes on from    /// there once room is back. A pull since the cursor of a copy that has reached the object's end is never stopped.    pub fn stopping_for(mut self, stop: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>) -> ObjectTransport {        self.stop = stop;        self    }    pub fn keeping_to(mut self, kit: Option<Arc<cotton_core::kit::AppKit>>) -> ObjectTransport {        self.kit = kit;        self    }    fn refused(&self, refusal: &ObjectRefusal) -> String {        self.heard(refusal);        if refusal.signs_out() {            if let Some(signed_out) = &self.signed_out {                signed_out.say(refusal);            }        }        let mut said = ServerRefusal::new(refusal.message.clone(), refusal.status);        if refusal.status != 0 {            said = said.with_code(refusal.code.clone());        }        *self.last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(said);        refusal.message.clone()    }    /// What a refusal says beyond itself (RESTORE 2): an account held still is noted for the Sync page; a post    /// refused as made against another generation tells the passes the server was put back.    fn heard(&self, refusal: &ObjectRefusal) {        if refusal.code == ACCOUNT_FROZEN {            self.frozen.store(true, std::sync::atomic::Ordering::SeqCst);        }        if refusal.status == 409 && refusal.code == GENERATION_MOVED {            if let Some(progress) = &self.progress {                progress.restored(None, None);            }        }    }    /// The server's generation this copy holds ([`GENERATION_KEY`]), read off the copy once; none when it holds none.    pub fn held_generation(&self) -> Option<String> {        let mut held = self.generation.lock().unwrap_or_else(std::sync::PoisonError::into_inner);        if let Some(known) = held.as_ref() {            return known.clone();        }        // Read through a snapshot reader: never an open that would make the file.        let read = if self.replica.exists() {            cotton_store::driver::Driver::open_snapshot_reader(&self.replica).map_err(|error| error.to_string()).and_then(|db| {                db.get("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(GENERATION_KEY.to_string())])                    .map_err(|error| error.to_string())                    .map(|row| row.and_then(|row| row.text("hlc_seen").and_then(generation_of)))            })        } else {            Ok(None)        };        match read {            Ok(found) => {                *held = Some(found.clone());                found            }            // Not known: asked again next time, and nothing is taken as held.            Err(error) => {                eprintln!("[cotton-sync] the generation this copy holds could not be read ({error})");                None            }        }    }    /// An answer's generation weighed against the one this copy holds (RESTORE-CONTRACT.md): none held, the one    /// answered is taken; the same, the pass goes on; another, the server was put back to an earlier time: refused    /// [`GENERATION_MOVED`], so nothing of the answer is folded, and the passes are told ([`SyncProgress::restored`]).    /// An answer that carries none (a server from before it) says nothing.    fn weigh_generation(&self, answer: &Value) -> Result<(), ObjectRefusal> {        let Some(served) = answer.get("generation").and_then(Value::as_str).filter(|served| !served.is_empty()) else { return Ok(()) };        match self.held_generation() {            None => {                *self.generation.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Some(served.to_string()));                Ok(())            }            Some(held) if held == served => Ok(()),            Some(_) => {                let restored_to = answer.get("restored_to").and_then(Value::as_str).map(str::to_string);                if let Some(progress) = &self.progress {                    progress.restored(Some(served.to_string()), restored_to);                }                Err(ObjectRefusal { status: 409, code: GENERATION_MOVED.into(), message: "the server was put back to an earlier time; this phone's copy is made again from it".into() })            }        }    }    /// The headers of an act this copy posts: its credential, and the generation it holds ([`GENERATION_HEADER`]).    pub(crate) fn act_headers(&self) -> Vec<(String, String)> {        let mut headers = bearer(&self.credential);        if let Some(generation) = self.held_generation() {            headers.push((GENERATION_HEADER.to_string(), generation));        }        headers    }    // ── push ───────────────────────────────────────────────────────────────    /// Post each row the ops name as an act. Answers the rows taken by    /// table, and the ops the object refused or this pass did not reach.    ///    /// **One post per row per pass** (film-progress-flood, 17 Nov 2026). The    /// first op of a row posts every column this pass's ops of that row name    /// ([`Self::send_op`]), so every later op of a row already posted in this    /// pass was carried by that post: it is taken without another. Two    /// thousand queued progress writes of one film were two thousand posts of    /// the same row, each sealed again and logged by the object as a change.    /// A retract ends the row's post; a write after it posts again.    ///    /// **At most [`POSTS_PER_PASS`] rows a pass**: each post is its own    /// request, and the pass pulls only after its push, so a long queue of    /// distinct rows held every arrival back for minutes. The ops of rows past    /// the limit are answered [`PushRejection::deferred`]: still queued, sent    /// by the next exchange, which the drain asks for at once.    fn push(&self, ops: &[CottonOp]) -> Result<(BTreeMap<String, usize>, Vec<PushRejection>), String> {        let mut applied: BTreeMap<String, usize> = BTreeMap::new();        let mut rejected = Vec::new();        if ops.is_empty() {            return Ok((applied, rejected));        }        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read for its writes ({error})"))?;        let map = self.map();        let mut taken = self.taken.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        taken.clear();        *self.moved.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = crate::seal::edit_bases_moved(&file)?.into_iter().collect();        // The rows whose row-now this pass posted, and how many it posted.        let mut posted: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();        let mut posts = 0usize;        // The rows whose post this pass the object refused: their later ops        // carry the same refusal, never another post of the same row.        let mut refused: BTreeMap<(String, String), PushRejection> = BTreeMap::new();        for op in ops {            let row = (op.table.clone(), op.row_id.clone());            let retract = canonical::decode(op.receipt.as_bytes()).map(|receipt| receipt.kind == Kind::Retract).map_err(|error| error.to_string())?;            let definition = DEFINITION_TABLES.contains(&op.table.as_str());            if !retract && !definition {                if posted.contains(&row) {                    taken.insert(op.op_id.clone());                    *applied.entry(op.table.clone()).or_default() += 1;                    continue;                }                if let Some(refusal) = refused.get(&row) {                    rejected.push(PushRejection { op_id: op.op_id.clone(), ..refusal.clone() });                    continue;                }                // UNKNOWN FIELD: refused for a field the object's definitions lack, and they have not moved since: it                // waits in the queue unposted (no request), and so do the row's later ops this pass.                if let Some(words) = self.definitions.as_ref().and_then(|held| held.waits_for_field(&op.op_id)) {                    let waiting = PushRejection { op_id: op.op_id.clone(), reason: words, retryable: Some(true), code: Some(UNKNOWN_FIELD.to_string()), server_time: None };                    refused.insert(row, waiting.clone());                    rejected.push(waiting);                    continue;                }            }            // A TABLE THE OBJECT HOLDS AS RETIRED (TABLE DROP 1, owner, 27 Nov 2026): never sent, never lost. Refused here            // for good, so the exchange parks the change with its patch (`cotton_store::rejected::park`) before it leaves            // the queue: the park is one of the places a change waits (`cotton_store::local_places`), so the copy-keeping            // rule keeps any copy that holds it, and the Sync page shows it with Let go. Costs no request.            if !definition && gone_store(&map, &op.table) {                rejected.push(PushRejection {                    op_id: op.op_id.clone(),                    reason: format!("{TABLE_GONE}: {} is retired, so this change stays on this phone and is never sent", op.table),                    retryable: Some(false),                    code: Some(TABLE_GONE.into()),                    server_time: None,                });                continue;            }            // A table this phone keeps for itself costs no request.            let costs = definition || map.ours(&op.table).is_some();            if costs && posts >= POSTS_PER_PASS && !posted.contains(&row) {                rejected.push(PushRejection::deferred(op.op_id.clone()));                continue;            }            let of_row: Vec<&CottonOp> = ops.iter().filter(|other| other.table == op.table && other.row_id == op.row_id).collect();            let asked = self.requests.load(std::sync::atomic::Ordering::Relaxed);            let mut sent = self.send_op(&file, &map, op, &of_row)?;            // RESTORE 2: a write made against another generation landed nothing. The pass stops here, this change and            // every one behind it queued as they are (never parked, retried or rewritten), and the copy is made again.            if let Some(refusal) = sent.as_ref().err().filter(|refusal| refusal.code == GENERATION_MOVED) {                return Err(self.refused(refusal));            }            if costs {                // What it asked: a change refused as moved reads its row and posts again (UNSENT HEAL 5, M3).                posts += self.requests.load(std::sync::atomic::Ordering::Relaxed).saturating_sub(asked).max(1);            }            // THE ROW IT LINKS TO FIRST (seen on the dev server, 22 Nov 2026): the object takes a row only once the row it            // links to is there, and the queue goes up in the order it was written, so a write that made an email before            // its conversation had the email refused, parked for good. A row this copy still has queued is sent now, as            // it stands here, and the refused one is posted again; the linked row's own ops are taken without a post.            if let Err(refusal) = &sent {                if let Some(parent) = (!definition && !retract).then(|| queued_link(&file, &map, &op.table, &op.row_id, refusal)).transpose()?.flatten() {                    if !posted.contains(&parent) {                        // Counted as asked: the parent's post, and the resend, which may read its row and post again.                        let asked = self.requests.load(std::sync::atomic::Ordering::Relaxed);                        match self.send_row(&file, &map, &parent.0, &parent.1)? {                            Ok(()) => {                                posted.insert(parent);                                sent = self.send_op(&file, &map, op, &of_row)?;                            }                            Err(refusal) if refusal.code == GENERATION_MOVED => return Err(self.refused(&refusal)),                            Err(_) => {}                        }                        if let Some(refusal) = sent.as_ref().err().filter(|refusal| refusal.code == GENERATION_MOVED) {                            return Err(self.refused(refusal));                        }                        posts += self.requests.load(std::sync::atomic::Ordering::Relaxed).saturating_sub(asked).max(1);                    }                }            }            if sent.is_ok() && !definition {                if retract {                    refused.remove(&row);                    posted.remove(&row);                } else {                    posted.insert(row);                }            }            match sent {                Ok(()) => {                    taken.insert(op.op_id.clone());                    *applied.entry(op.table.clone()).or_default() += 1                }                // A row of a table this app's kit does not carry that this                // copy cannot seal: no copy of a kit app ever takes such a                // table's definition or its rows, so it would wait for ever                // and the Account card said "Waiting to send 1 row" for good                // (the zone claim on Books, Music, Cinemas and Story, 21 Nov                // 2026). It stays on this phone as it is; only its place in                // the queue goes, said in the log. A table the kit carries                // still waits for its key below.                Err(refusal) if refusal.status == 0 && refusal.code.starts_with("seal_") && self.never_carried(&map, &op.table) => {                    eprintln!(                        "[cotton-sync] a write to {} {} stays on this phone and leaves the queue: this app's kit does not carry the table, so no copy takes it ({})",                        op.table, op.row_id, refusal.message                    );                    // Never dropped silently (UNSENT HEAL 2, review item 7): written down, filed as Feedback, and                    // counted on the Sync page (`unsent_heal::kept_here_only`).                    if let Some((layout, database)) = self.discarded.as_ref() {                        // Counted first (the count migrates what an older build wrote down), and never failing the                        // push: the change is written down below either way.                        if let Err(why) = crate::unsent_heal::note_kept_here(layout, database, 1) {                            eprintln!("[cotton-sync] the count of changes kept on this phone was not written ({why})");                        }                        crate::unsent::record_discarded(                            layout, database, vec![crate::unsent::UnsentChange::of(op, crate::unsent::Waiting::Queued)],                            BTreeMap::from([(op.op_id.clone(), refusal.code.clone())]),                            crate::unsent_heal::NEVER_CARRIED_WHY, &chrono::Utc::now().to_rfc3339(),                        )?;                    }                    taken.insert(op.op_id.clone());                }                // This device cannot seal it yet (no key, or a wrap that does                // not open): held in the outbox, by name, and the pass goes                // on — its pull may be what the person needs to see.                Err(refusal) if refusal.status == 0 && refusal.code.starts_with("seal_") => rejected.push(PushRejection {                    op_id: op.op_id.clone(),                    reason: refusal.message.clone(),                    retryable: Some(true),                    code: Some(refusal.code.clone()),                    server_time: None,                }),                // The row moved since this copy read it: held in the outbox,                // and this pass's pull brings what it holds now — kept as the                // newer text when an edit of a merged column waits on it. A                // row waiting for its app's merge is held the same way.                Err(refusal) if refusal.code == VERSION_MOVED || refusal.code == MERGE_WAITS || refusal.code == HELD_ROW_UNREAD || refusal.code == MOVED_AGAIN => rejected.push(PushRejection {                    op_id: op.op_id.clone(),                    reason: refusal.message.clone(),                    retryable: Some(true),                    code: Some(refusal.code.clone()),                    server_time: None,                }),                // Nothing answered, or the credential is not taken: the pass                // fails and the write stays queued for the next one.                Err(refusal) if refusal.status == 0 || refusal.signs_out() => return Err(self.refused(&refusal)),                // UNKNOWN FIELD: a field this build's kit has that the object's definition does not yet (the Worker                // not deployed): never parked, so never lost or said refused for good. It waits in the queue and goes                // again once the definitions move; the pass goes on with the rest.                Err(refusal) if refusal.code == UNKNOWN_FIELD && !definition => {                    if let Some(held) = &self.definitions {                        held.refused_for_field(&op.op_id, &refusal.message);                    }                    rejected.push(PushRejection { op_id: op.op_id.clone(), reason: refusal.message.clone(), retryable: Some(true), code: Some(UNKNOWN_FIELD.to_string()), server_time: None });                }                // A definition the object cannot take just now is held in the                // outbox like a row (below, retryable) and the pass goes on:                // the rows behind it are sent and pulled. The pass's                // definitions pull leaves its row as this copy holds it                // (`waiting_definitions`), so its whole edit is posted again.                Err(refusal) if DEFINITION_TABLES.contains(&op.table.as_str()) && !refusal.transient() => {                    let (layout, database) = self.discarded.as_ref().ok_or("no place was supplied to write down the refused definition")?;                    let already = crate::unsent::discarded(layout, database).iter().any(|entry| entry.changes.iter().any(|change| change.op_id == op.op_id));                    if !already {                        crate::unsent::record_discarded(                            layout, database, vec![crate::unsent::UnsentChange::of(op, crate::unsent::Waiting::Queued)],                            // The code only, never the object's words, which could quote a value (UNSENT HEAL 2 review).                            BTreeMap::from([(op.op_id.clone(), refusal.code.clone())]),                            "the object refused this definition", &chrono::Utc::now().to_rfc3339(),                        )?;                    }                    // Counted taken: the pass settles it off the outbox with                    // the rest, through the copy it holds. Never a second                    // writable open of the replica beside the pass's own.                    taken.insert(op.op_id.clone());                    *applied.entry(op.table.clone()).or_default() += 1;                }                // A 5xx or a 429 is held under `unanswered` whatever word it carried: a refusal that passes, never                // counted as a wait for good (UNSENT HEAL 2: a change queued a day ago was said "can't be sent" at                // its first 503).                Err(refusal) => rejected.push({                    // An account held still (RESTORE 2) waits like any 5xx; the Sync page says so.                    self.heard(&refusal);                    PushRejection {                    op_id: op.op_id.clone(),                    reason: refusal.message.clone(),                    retryable: refusal.transient().then_some(true),                    code: Some(if refusal.transient() { UNANSWERED.to_string() } else { refusal.code.clone() }),                    server_time: None,                    }                }),            }            if !retract && !definition {                if let Some(refusal) = rejected.last().filter(|refusal| refusal.op_id == op.op_id) {                    refused.insert((op.table.clone(), op.row_id.clone()), refusal.clone());                }            }        }        Ok((applied, rejected))    }    /// `store`'s row `id` as this copy holds it, posted as the object's create (an update when the object holds it    /// already), sealed as any write: what [`Self::push`] sends first when a row it links to is still queued here.    fn send_row(&self, file: &rusqlite::Connection, map: &ObjectTables, store: &str, id: &str) -> Result<Result<(), ObjectRefusal>, String> {        let Some(table) = map.ours(store) else { return Ok(Ok(())) };        let Some(data) = row_now(file, table, id)? else { return Ok(Ok(())) };        let (args, sealed) = match self.sealed_args(file, table, id, data, false)? {            Ok(made) => made,            Err(refusal) => return Ok(Err(refusal)),        };        let posted = self.post("create", args.clone()).or_else(|refusal| if refusal.code == "duplicate_id" { self.post("update", args) } else { Err(refusal) });        if posted.is_ok() {            if let Some(note) = sealed {                self.keep_notes(&[note])?;            }        }        Ok(posted)    }    /// Whether `store` (this build's table name) is a table this app's kit    /// does not carry: neither the kit's own, the shell's, the unlock    /// window's nor the seal keys ([`cotton_core::kit::AppKit::pulled`]).    /// Never for the whole object, which carries every table it serves.    fn never_carried(&self, map: &ObjectTables, store: &str) -> bool {        let (Some(kit), Some(table)) = (self.kit.as_ref(), map.ours(store)) else { return false };        !kit.keeps_table(&table.table) && table.table != cotton_core::seal::SEAL_KEY_TABLE    }    /// One write this copy queued, posted as the act it is: a create as the    /// row the copy holds now, a change as the columns `of_row` (this row's    /// ops going up together) name, a retract as itself. The outer `Err` is    /// the copy not answering for it; the inner, the object's refusal. A write    /// to this phone's own table goes nowhere and is taken.    fn send_op(&self, file: &rusqlite::Connection, map: &ObjectTables, op: &CottonOp, of_row: &[&CottonOp]) -> Result<Result<(), ObjectRefusal>, String> {        if DEFINITION_TABLES.contains(&op.table.as_str()) {            return self.send_definition(file, op, None);        }        let Some(table) = map.ours(&op.table) else {            return Ok(Ok(()));        };        let receipt = canonical::decode(op.receipt.as_bytes()).map_err(|error| error.to_string())?;        let kind = receipt.kind;        Ok(match kind {            // An erase says why, so the object ends the row for good too: its log keeps nothing the row held.            Kind::Retract => self.post("delete", delete_args(&table.table, &op.row_id, receipt.erase.as_deref())).or_else(|refusal| if refusal.code == "no_such_record" { Ok(()) } else { Err(refusal) }),            Kind::Create | Kind::Change => match row_now(file, table, &op.row_id)? {                // Gone since: its retract follows in this queue.                None => Ok(()),                Some(data) => {                    let binned = row_binned(file, table, &op.row_id)?;                    // Taken out of the bin here (Undo, Restore): the object deleted the row when it went in, and an                    // update of a deleted row finds nothing, so the row goes again whole as a create, which the object                    // takes over its tombstone (CINEMAS DEV PROOF, 26 Nov 2026: an undone film stayed deleted there).                    let revived = kind == Kind::Change && !binned && unbins(file, table, of_row)?;                    if kind == Kind::Change && !binned && !revived {                        return self.send_change(file, table, &op.row_id, data, of_row);                    }                    let (args, sealed) = match self.sealed_args(file, table, &op.row_id, data, false)? {                        Ok(made) => made,                        Err(refusal) => return Ok(Err(refusal)),                    };                    let gone = || self.post("delete", json!({"table": table.table, "id": op.row_id})).or_else(|refusal| if refusal.code == "no_such_record" { Ok(()) } else { Err(refusal) });                    match kind {                        _ if revived => self.post("create", args.clone()).or_else(|refusal| if refusal.code == "duplicate_id" { self.post("update", args) } else { Err(refusal) }),                        Kind::Create => self.post("create", args.clone()).or_else(|refusal| {                            // The object holds it already (an op handed over again): the row as it is now replaces it.                            if refusal.code == "duplicate_id" { self.post("update", args) } else { Err(refusal) }                        }).and_then(|()| if binned { gone() } else { Ok(()) }),                        // Put in the bin here: the object's delete.                        _ if binned => gone(),                        _ => self.post("update", args),                    }                    .and_then(|()| {                        // The row's wrap, kept so its next edit reuses the DEK.                        if let Some(note) = sealed {                            self.keep_notes(&[note]).map_err(|message| ObjectRefusal { status: 0, code: "copy_unwritten".into(), message })?;                        }                        Ok(())                    })                }            },        })    }    /// A change of `id` posted as the columns `of_row` name and no others    /// (film-progress-clobber, 18 Nov 2026): a film's place saved during a    /// play put this copy's whole older row back over the master, tracks and    /// state the Mac had laid since.    ///    /// Columns the object holds in the clear are merged by it one by one, so    /// they go alone, with no key needed. The sealed half is one blob the    /// object cannot merge: a change of a sealed column seals the row as this    /// copy holds it with the change laid over it, and goes as the `seal` act    /// at the version this copy read, so a blob never lands over words it has    /// not seen ([`VERSION_MOVED`]). A row whose version this copy never read    /// has nothing to hold it to, and goes as an update.    fn send_change(&self, file: &rusqlite::Connection, table: &StoredTable, id: &str, row: Map<String, Value>, of_row: &[&CottonOp]) -> Result<Result<(), ObjectRefusal>, String> {        let own = own_columns(table, &row, of_row)?;        // Nothing the object keeps: the ops named only the row's address and times, or columns no object table holds        // (the copy's own). Taken without a post and not written down (UNSENT HEAL 7, review 5): there is no value the        // server could have taken, so nothing is lost, and a record of it would show the person a change with nothing        // in it. The row itself stays on this phone as it is.        if own.is_empty() {            return Ok(Ok(()));        }        let kept_open = row.get(crate::seal::KEEP_OPEN) == Some(&Value::Bool(true));        if table.awaits_seal() && !kept_open {            let error = table.awaiting_refusal();            return Ok(Err(ObjectRefusal { status: 0, code: error.code().into(), message: error.to_string() }));        }        let sealed_half = table.seal.as_ref().filter(|spec| !kept_open && own.keys().any(|column| spec.seals(column))).is_some();        if !sealed_half {            let mut data = own;            if kept_open {                data.insert(crate::seal::KEEP_OPEN.into(), Value::Bool(true));            }            return Ok(self.post("update", json!({"table": table.table, "id": id, "data": data})));        }        if crate::seal::merge_waits(file, &table.table, id)? {            return Ok(Err(ObjectRefusal { status: 0, code: MERGE_WAITS.into(), message: format!("{} {id} waits for its edit to be merged over the newer text", table.table) }));        }        let mut whole = row;        whole.extend(own.iter().map(|(column, value)| (column.clone(), value.clone())));        let watched: Map<String, Value> = crate::seal::edit_base_columns(file, &table.table, id)?.into_iter().filter_map(|column| whole.get(&column).cloned().map(|value| (column, value))).collect();        // The fresh-key heal only where the post is held to the version this phone read (`seal` with        // `expect_version`): an old wrap says this copy may be out of date, and there a moved row is refused, never        // overwritten (UNSENT HEAL 2, review item 1).        let read_version = crate::seal::held_version(file, &table.table, id)?.filter(|version| *version > 0);        let mut read_version = read_version;        if read_version.is_none() && self.held_to_version.contains(&table.table) {            // No version held for the row (a list pulled before lists were sealed): read that one row from the object,            // lay this copy's own change over what the object holds, and send it held to that version. A whole row            // resealed from this copy's older words never goes up unheld (HIDDEN 6, review 5 and M2).            match self.read_row(file, table, id)? {                Ok(ObjectRow::Opened(version, held)) => return self.lay_over(file, table, id, &own, of_row, version, held),                // The object holds no live row: only a row this phone made, which nothing from the object has touched,                // goes without a version, as its create (HIDDEN 7). A row the object holds that does not open with                // this copy's key (another device resealed it, review 7) always waits: it is not only this phone's.                Ok(ObjectRow::Absent) if born_here(file, table, id)? => {}                // Made elsewhere and held by the object no more: gone, said at once as the moved heal says it (UNSENT                // HEAL 7, review 1: as unread it was read every pass for ever, since a read that answers clears the wait).                Ok(ObjectRow::Absent) => return Ok(Err(row_gone(table, id))),                Ok(ObjectRow::Unopened) => return Ok(Err(unread_refusal(table, id))),                Err(refusal) => return Ok(Err(refusal)),            }        }        let (mut args, note) = match self.sealed_args(file, table, id, whole, read_version.is_some())? {            Ok(made) => made,            Err(refusal) => return Ok(Err(refusal)),        };        if let Some(data) = args["data"].as_object_mut() {            data.retain(|column, _| cotton_core::seal::row::RESERVED.contains(&column.as_str()) || own.contains_key(column));        }        let act = match read_version {            Some(version) => {                args["expect_version"] = json!(version);                "seal"            }            None => "update",        };        let posted = self.post(act, args);        // REFUSED AS MOVED, READ AGAIN (UNSENT HEAL 4, the owner's Comms build 40: ten mail edits refused as moved on        // every pass for a day). The pull brings a moved row only while the phone carries it (a mail outside its window,        // archived from Post, never comes), so the post went again at the same old version for ever. The row is read        // from the object now, this copy's own change laid over what the object holds, and posted held to that version.        // A row watched for its app to merge (Words' text) keeps its merge, below.        if watched.is_empty() && matches!(&posted, Err(refusal) if refusal.code == VERSION_MOVED) {            return match self.read_row(file, table, id)? {                Ok(ObjectRow::Opened(version, held)) => self.lay_over(file, table, id, &own, of_row, version, held),                Ok(ObjectRow::Absent) => Ok(Err(row_gone(table, id))),                Ok(ObjectRow::Unopened) => Ok(Err(unread_refusal(table, id))),                Err(refusal) => Ok(Err(refusal)),            };        }        if !watched.is_empty() {            let note = match &posted {                Ok(()) => Some(crate::seal::Note::Taken { table: table.table.clone(), id: id.to_string(), values: watched }),                Err(refusal) if refusal.code == VERSION_MOVED => {                    self.moved.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((table.table.clone(), id.to_string()));                    Some(crate::seal::Note::Moved { table: table.table.clone(), id: id.to_string() })                }                Err(_) => None,            };            if let Some(note) = note {                self.keep_notes(&[note])?;            }        }        Ok(posted.and_then(|()| match note {            Some(note) => self.keep_notes(&[note]).map_err(|message| ObjectRefusal { status: 0, code: "copy_unwritten".into(), message }),            None => Ok(()),        }))    }    /// [`Self::object_row`], waiting out a row the object would not hand back readable: asked again after a minute,    /// then two, four… an hour at most, never every pass (UNSENT HEAL 5, review M3). The wait is kept in the copy    /// (`_seal_unread`), since every pass builds its own transport (UNSENT HEAL 6). Waiting, it asks nothing.    ///    /// UNSENT HEAL 7: only a read that answers (opened, or gone) clears the wait; Cotton not answering (a 5xx, a 429,    /// no network) leaves it and fails as it failed. A row whose laid edit keeps being refused as moved waits the same    /// way ([`MOVED_AGAIN`]). No tolerance for an older server (the owner, 27 Nov 2026: builds before launch need none).    fn read_row(&self, file: &rusqlite::Connection, table: &StoredTable, id: &str) -> Result<Result<ObjectRow, ObjectRefusal>, String> {        let now = (self.clock)();        if let Some((until_ms, tries)) = crate::seal::moved_wait(file, &table.table, id)? {            if now < until_ms {                return Ok(Err(moved_again(table, id, tries)));            }        }        let wait = crate::seal::unread_wait(file, &table.table, id)?;        if wait.is_some_and(|(until_ms, _)| now < until_ms) {            return Ok(Err(unread_refusal(table, id)));        }        let read = self.object_row(table, id)?;        let note = match (&read, wait) {            (Ok(ObjectRow::Unopened), _) => {                let tries = wait.map_or(0, |(_, tries)| tries) + 1;                Some(crate::seal::Note::Unread { table: table.table.clone(), id: id.to_string(), until_ms: now + wait_minutes(tries) * 60_000, tries })            }            (Ok(_), Some(_)) => Some(crate::seal::Note::Readable { table: table.table.clone(), id: id.to_string() }),            _ => None,        };        if let Some(note) = note {            self.keep_notes(&[note])?;        }        Ok(read)    }    /// This copy's change (`own`, of the ops `of_row`) laid over `table`'s row `id` as the object holds it (its    /// `version` and columns, `whole`), posted held to that version: the other writer's columns kept, a per-key column    /// (`data.<key>`) laid key by key (review M1). The person's edit is their act and always goes, whenever it was made    /// and whatever changed on the row since: the object gives no time per field, so no time is compared (UNSENT HEAL    /// 6: comparing the row's time dropped an edit for any change of any column, his own first post included), as a    /// pull inside the window lays it. Moved again in between: [`VERSION_MOVED`], and the next try reads again.    #[allow(clippy::too_many_arguments)]    fn lay_over(&self, file: &rusqlite::Connection, table: &StoredTable, id: &str, own: &Map<String, Value>, of_row: &[&CottonOp], version: i64, mut whole: Map<String, Value>) -> Result<Result<(), ObjectRefusal>, String> {        let per_key = per_key_changes(table, of_row)?;        for (column, value) in own {            let laid = match per_key.get(column) {                Some(keys) => lay_keys(whole.get(column), value, keys),                None => value.clone(),            };            whole.insert(column.clone(), laid);        }        let (mut args, note) = match self.sealed_args(file, table, id, whole.clone(), true)? {            Ok(made) => made,            Err(refusal) => return Ok(Err(refusal)),        };        if let Some(data) = args["data"].as_object_mut() {            data.retain(|column, _| cotton_core::seal::row::RESERVED.contains(&column.as_str()) || own.contains_key(column));            for column in per_key.keys() {                if let (Some(sent), Some(laid)) = (data.get_mut(column), whole.get(column)) {                    *sent = laid.clone();                }            }        }        args["expect_version"] = json!(version);        let posted = self.post("seal", args);        // Moved again straight after a fresh read: counted in the copy, and from the [`MOVED_AGAIN_AFTER`]th in a row        // the row waits before it is read again, a minute doubling to an hour (UNSENT HEAL 7, review 3). Taken: the        // count goes.        let moves = crate::seal::moved_wait(file, &table.table, id)?;        let posted = match posted {            Err(refusal) if refusal.code == VERSION_MOVED => {                let tries = moves.map_or(0, |(_, tries)| tries) + 1;                let waits = tries >= MOVED_AGAIN_AFTER;                let until_ms = if waits { (self.clock)() + wait_minutes(tries + 1 - MOVED_AGAIN_AFTER) * 60_000 } else { 0 };                self.keep_notes(&[crate::seal::Note::MovedAgain { table: table.table.clone(), id: id.to_string(), until_ms, tries }])?;                Err(if waits { moved_again(table, id, tries) } else { refusal })            }            Ok(()) if moves.is_some() => {                self.keep_notes(&[crate::seal::Note::Laid { table: table.table.clone(), id: id.to_string() }])?;                Ok(())            }            posted => posted,        };        Ok(posted.and_then(|()| match note {            Some(note) => self.keep_notes(&[note]).map_err(|message| ObjectRefusal { status: 0, code: "copy_unwritten".into(), message }),            None => Ok(()),        }))    }    /// The act's arguments for a write of `id` to `table`: the row as it is,    /// or — a sealed table — sealed under the table's current version with    /// its blind tokens, and the note of the wrap this copy keeps once the    /// object takes it. No key is [`crate::seal::SEAL_KEY_MISSING`]: the    /// write waits, retryable, and nothing goes in the clear. A row marked    /// `keep_open` goes as it is (Q3).    /// `reseal`: the post is held to the version this phone read, so a kept wrap that no longer opens may be replaced    /// by a fresh one (see below). Everywhere else such a row is refused `seal_does_not_open` and shown to the person.    fn sealed_args(&self, file: &rusqlite::Connection, table: &StoredTable, id: &str, data: Map<String, Value>, reseal: bool) -> Result<Result<(Value, Option<crate::seal::Note>), ObjectRefusal>, String> {        let refused = |error: cotton_core::seal::SealError| ObjectRefusal { status: 0, code: error.code().into(), message: error.to_string() };        let kept_open = data.get(crate::seal::KEEP_OPEN) == Some(&Value::Bool(true));        if table.awaits_seal() && !kept_open {            return Ok(Err(refused(table.awaiting_refusal())));        }        let Some(spec) = table.seal.as_ref().filter(|_| !kept_open) else {            return Ok(Ok((json!({"table": table.table, "id": id, "data": data}), None)));        };        let Some(sealer) = &self.sealer else {            return Ok(Err(refused(cotton_core::seal::SealError::KeyMissing(format!("the data key ({} is sealed, and this pass has no sealer)", table.table)))));        };        if let Err(refusal) = self.learn_seal_keys() {            return Ok(Err(refusal));        }        let held = crate::seal::held_wrap(file, &table.table, id)?;        let sealed = match sealer.seal(&table.table, id, spec, &data, held.as_ref().map(|(dek_enc, v)| (dek_enc.as_str(), *v))) {            Ok(sealed) => sealed,            // A KEPT WRAP THAT NO LONGER OPENS (UNSENT HEAL, 26 Nov 2026): the row's wrap is a former database's (a            // copy made again, a key since changed), so every pass refused it the same way and the write waited for            // good. Once another wrap this copy keeps opens with this device's key, that key is this database's: the            // row is sealed whole under a fresh DEK, as an adopt seals a row it brings (`sealed_whole`), and only            // where the post is held to the version read (`reseal`). Unproven or unguarded, it waits, said to the            // person (`unsent_heal`): nothing goes under a key that may be wrong, nor over a row that may be newer.            Err(cotton_core::seal::SealError::DoesNotOpen) if reseal && held.is_some() && self.key_proven(file, sealer, &table.table, id)? => {                eprintln!("[cotton-sync] {} {id}: its kept wrap does not open with this database's key; sealed again under a fresh key", table.table);                match sealer.seal(&table.table, id, spec, &data, None) {                    Ok(sealed) => sealed,                    Err(error) => return Ok(Err(refused(error))),                }            }            Err(error) => return Ok(Err(refused(error))),        };        let note = crate::seal::Note::Sealed { table: table.table.clone(), id: id.into(), dek_enc: sealed.dek_enc.clone(), seal_v: sealed.seal_v, version: 0 };        Ok(Ok((json!({"table": table.table, "id": id, "data": sealed.data, "blind": sealed.blind}), Some(note))))    }    /// Whether this device's key is proven this database's: a wrap this copy keeps of another row opens with it.    fn key_proven(&self, file: &rusqlite::Connection, sealer: &crate::seal::Sealer, table: &str, id: &str) -> Result<bool, String> {        Ok(crate::seal::other_wraps(file, table, id, 16)?.iter().any(|(t, row, dek_enc, v)| sealer.opens(t, row, *v, dek_enc)))    }    /// A row a send brings in whole (adopt, restore, top-up: sealing plan    /// §7) as the object takes it: `data`, already in the object's ids,    /// sealed when `table` is sealed, under the table's current version    /// with a fresh DEK and its blind tokens, the way a connected phone's    /// write is. A wrap this copy holds is not reused: it may be a former    /// database's, whose key opens nothing here. No key, or the object's    /// seal keys not read, is [`crate::seal::SEAL_KEY_MISSING`] with status    /// 0: the send stops with the copy whole and nothing goes in the clear.    /// A row marked `keep_open` goes as it is (Q3).    /// THE ROWS A BACKUP KEPT (`kept-rows.json`, [`crate::unsent::KeptRow`]), posted again as a create (an update    /// where the object holds the row), each leaving the file once the object takes it. One still refused stays for    /// a later pass; one this phone cannot seal yet waits for the key; a line or object that cannot answer now stops    /// them till the next pass, never the pass.    pub(crate) fn post_kept_rows(&self) -> Result<(), String> {        let Some((layout, database)) = self.discarded.as_ref() else { return Ok(()) };        let rows = crate::unsent::kept_rows(layout, database);        if rows.is_empty() {            return Ok(());        }        let map = self.map();        let mut left = Vec::new();        let mut stopped = false;        for row in rows {            // KEPT FOUR 3 B: a founding row (an older build kept a refused founding here) is never posted: posted, it            // would found or re-wrap the account with the local key. Its wrap goes into the local key's own file, and            // it leaves this list; a founding row that cannot be kept there stays here, never posted.            if crate::founding::is_founding(&row.table) {                let wrap = row.data["wrapped_vmk"].as_str().filter(|wrap| !wrap.is_empty());                let secured = match wrap {                    Some(wrap) => crate::vault_keep::secure_wrap(                        layout,                        &format!("kept-row:{}", row.row_id),                        crate::vault_keep::HeldKey {                            id: row.row_id.clone(),                            device_id: row.data["device_id"].as_str().unwrap_or_default().to_string(),                            public_key: row.data["public_key"].as_str().unwrap_or_default().to_string(),                            wrapped_vmk: wrap.to_string(),                            vmk_version: row.data["vmk_version"].as_i64().unwrap_or(0),                        },                    ),                    None => Ok(()),                };                if secured.is_err() {                    left.push(row);                }                continue;            }            // A row the object refused because it already holds its own version stays here as the person wrote it            // and is never posted: posted, the update below would put the phone's version over the object's, which            // the adopt's refusal said stands (adopt_tests a_local_row_the_object_holds_keeps_the_objects_version).            if row.why == OBJECT_STANDS {                left.push(row);                continue;            }            let Some(table) = map.object(&row.table).filter(|_| !stopped) else {                left.push(row);                continue;            };            let (data, blind) = match self.sealed_whole(table, &row.row_id, row.data.clone()) {                Ok(sealed) => sealed,                Err(_) => {                    left.push(row);                    continue;                }            };            let mut args = json!({"table": table.table, "id": row.row_id, "data": data});            if let Some(blind) = blind {                args["blind"] = json!(blind);            }            let posted = self.post("create", args.clone()).or_else(|refusal| if refusal.code == "duplicate_id" { self.post("update", args) } else { Err(refusal) });            match posted {                Ok(()) => eprintln!("[cotton-sync] a row the backup kept, {} {}, is taken by the object", row.table, row.row_id),                Err(refusal) => {                    // The server put back (RESTORE 2) stops it too: the row stays, and the next pass makes the copy again.                    self.heard(&refusal);                    stopped = refusal.transient() || refusal.signs_out() || refusal.code == GENERATION_MOVED;                    left.push(row);                }            }        }        crate::unsent::set_kept_rows(layout, database, &left)    }    pub(crate) fn sealed_whole(&self, table: &StoredTable, id: &str, data: Value) -> Result<(Value, Option<Vec<String>>), ObjectRefusal> {        let refused = |error: cotton_core::seal::SealError| ObjectRefusal { status: 0, code: error.code().into(), message: error.to_string() };        let kept_open = data.get(crate::seal::KEEP_OPEN) == Some(&Value::Bool(true));        if table.awaits_seal() && !kept_open {            return Err(refused(table.awaiting_refusal()));        }        let Some(spec) = table.seal.as_ref().filter(|_| !kept_open) else {            return Ok((data, None));        };        let Some(sealer) = &self.sealer else {            return Err(refused(cotton_core::seal::SealError::KeyMissing(format!("the data key ({} is sealed, and this send has no sealer)", table.table))));        };        self.learn_seal_keys()?;        let Value::Object(row) = data else { return Err(refused(cotton_core::seal::SealError::BadInput(format!("{} {id} is no row", table.table)))) };        let sealed = sealer.seal(&table.table, id, spec, &row, None).map_err(refused)?;        Ok((Value::Object(sealed.data), Some(sealed.blind)))    }    /// A definition's current JSON, with the last object receipt as its    /// precondition. Adopt has no object baseline and rekeys local ids.    fn send_definition(&self, file: &rusqlite::Connection, op: &CottonOp, rekey: Option<&Rekey>) -> Result<Result<(), ObjectRefusal>, String> {        let kind = match op.table.as_str() {            "cotton_tool_definitions" => "tool",            "cotton_board_definitions" => "board",            "cotton_theme_definitions" => "theme",            "cotton_table_definitions" => "table",            _ => return Err("no definition kind for this table".into()),        };        let receipt = canonical::decode(op.receipt.as_bytes()).map_err(|error| error.to_string())?;        let mut args = json!({"kind": kind});        if matches!(receipt.kind, Kind::Retract) {            args["remove"] = json!(op.row_id);        } else {            let mut statement = file.prepare(&format!("SELECT definition FROM {} WHERE id = ?1", op.table)).map_err(|error| error.to_string())?;            let mut rows = statement.query([&op.row_id]).map_err(|error| error.to_string())?;            let Some(row) = rows.next().map_err(|error| error.to_string())? else { return Ok(Ok(())) };            let raw: String = row.get(0).map_err(|error| error.to_string())?;            args["definition"] = serde_json::from_str(&raw).map_err(|error| format!("the definition does not read ({error})"))?;        }        if let Some(rekey) = rekey {            args = rekey.value(args);        } else {            let mut statement = file.prepare("SELECT bytes FROM _writes WHERE tbl = ?1 AND row_id = ?2 AND author = ?3 AND hlc < ?4 ORDER BY hlc DESC LIMIT 1").map_err(|error| error.to_string())?;            let mut rows = statement.query(rusqlite::params![op.table, op.row_id, OBJECT_AUTHOR, op.hlc]).map_err(|error| error.to_string())?;            let base = if let Some(row) = rows.next().map_err(|error| error.to_string())? {                let bytes: Vec<u8> = row.get(0).map_err(|error| error.to_string())?;                let previous = canonical::decode(&bytes).map_err(|error| error.to_string())?;                match previous.fields.get("definition") {                    Some(Value::String(raw)) => serde_json::from_str(raw).map_err(|error| error.to_string())?,                    Some(value) => value.clone(),                    None => Value::Null,                }            } else { Value::Null };            args["base"] = base;        }        if let Some(held) = &self.definitions { held.hold(None); }        Ok(self.post("definition", args))    }    /// A COPY ANOTHER BUILD WROTE GOES, ITS WRITES FIRST (29 Oct 2026). The    /// phone's copy of the object is the object's cache, so a copy stamped    /// with another schema than this build's is not moved in place: it is    /// remade from the object at connect (`personal.connect`). Before it goes,    /// every write it holds that the object does not — queued, parked, held —    /// is posted here as a pass posts it, the row read as the copy holds it.    /// A write the object refuses, or one the copy cannot read back, is    /// written down as discarded with why (filed in Feedback once a copy is    /// open, `crate::unsent::record_discarded`); an object that does not    /// answer, asks again later, or no longer takes the credential, is an    /// `Err` and the copy stays where it is for the next connect.    pub fn send_before_remake(&self, layout: &crate::layout::Layout, workspace_id: &str, at: &str) -> Result<SentBeforeRemake, String> {        let db = cotton_store::Driver::open_snapshot_reader(&self.replica).map_err(|error| format!("this phone's copy could not be opened ({error})"))?;        let receipts = crate::unsent::receipts(&db)?;        // QUEUE BAD OP 4: what does not read here is never in `receipts`; nothing is carried out of the copy. The copy        // leaves its place only through `crate::copy_keep::retire`, which keeps it whole while it holds any change        // beyond the ones answered here ([`SentBeforeRemake::acknowledged`]).        drop(db);        let mut sent = SentBeforeRemake::default();        if receipts.is_empty() {            return Ok(sent);        }        let held = self.copy_definitions()?;        let map = self.map().with_defined(held.iter())?;        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read for its writes ({error})"))?;        let mut lost = Vec::new();        let mut reasons = BTreeMap::new();        for (op, waiting) in &receipts {            // A table the object holds as retired (TABLE DROP 1): never sent; it stays in the copy, which is then kept            // aside whole, as a table no copy takes is.            if gone_store(&map, &op.table) {                eprintln!("[cotton-sync] before this phone's copy is made again, a write to {} {} stays in the kept copy: the table is retired", op.table, op.row_id);                sent.held_back.push(op.op_id.clone());                continue;            }            let why = match self.send_op(&file, &map, op, &[op]) {                Ok(Ok(())) => {                    sent.delivered += 1;                    sent.acknowledged.push(op.op_id.clone());                    continue;                }                // Not answered, asked again later, or the credential not taken:                // the copy stays for the next connect.                // A row of a table this app's kit does not carry that this                // copy cannot seal (the zone claim on Books, Music, Cinemas                // and Story): no copy of the app takes it, so it never holds                // the remake back; it goes with the copy, said in the log.                Ok(Err(refusal)) if refusal.status == 0 && refusal.code.starts_with("seal_") && self.never_carried(&map, &op.table) => {                    eprintln!("[cotton-sync] before this phone's copy is made again, a write to {} {} stays in the kept copy: this app's kit does not carry the table, so no copy takes it ({})", op.table, op.row_id, refusal.message);                    // QUEUE BAD OP 5 (item 5): NOT acknowledged. The server never answered it; it stays in the copy,                    // which is then kept aside, listed, and ended only by the person; recovery never sends it back                    // into a copy that cannot send it either.                    sent.held_back.push(op.op_id.clone());                    continue;                }                Ok(Err(refusal)) if refusal.transient() || refusal.signs_out() => return Err(self.refused(&refusal)),                // The object answered for good: written down, and answered.                Ok(Err(refusal)) => refusal.message,                // QUEUE BAD OP 4: one this copy cannot read back is not the server's answer: it stays in the copy,                // which is then kept whole, and recovery tries it under each later build.                Err(unreadable) => {                    eprintln!("[cotton-sync] before this phone's copy is made again, a write to {} {} could not be read back; it stays in the kept copy ({unreadable})", op.table, op.row_id);                    continue;                }            };            sent.acknowledged.push(op.op_id.clone());            reasons.insert(op.op_id.clone(), why);            lost.push(crate::unsent::UnsentChange::of(op, *waiting));        }        sent.refused = lost.iter().filter(|change| !change.is_bookkeeping()).count();        crate::unsent::record_discarded(layout, workspace_id, lost, reasons, "the object did not take them when this phone's copy from an earlier build was remade", at)?;        Ok(sent)    }    /// Seal a batch: one `seal_many` act, or (an object from before it, `unknown_act`) one `seal` a row for the rest    /// of the pass. Answers each row's outcome in order; the whole call's refusal when nothing answered or the    /// phone is signed out.    fn seal_rows(&self, rows: &[Value]) -> Result<Vec<Result<(), ObjectRefusal>>, ObjectRefusal> {        for args in rows {            self.guard("seal", args)?;        }        if !self.seal_one_by_one.load(std::sync::atomic::Ordering::Relaxed) {            match self.address.send(self.exchange.as_ref(), "POST", routes::ACT, self.act_headers(), Some(&json!({"act": "seal_many", "args": {"rows": rows}}))) {                Ok(answer) => {                    self.note_stale(&answer);                    let results = answer["results"].as_array().cloned().unwrap_or_default();                    return Ok(results                        .iter()                        .map(|r| {                            if r["ok"].as_bool() == Some(true) {                                Ok(())                            } else {                                Err(ObjectRefusal { status: r["status"].as_u64().unwrap_or(400) as u16, code: r["code"].as_str().unwrap_or("refused").to_string(), message: r["code"].as_str().unwrap_or("refused").to_string() })                            }                        })                        .collect());                }                Err(refusal) if refusal.status == 400 && refusal.code == "unknown_act" => self.seal_one_by_one.store(true, std::sync::atomic::Ordering::Relaxed),                Err(refusal) => return Err(refusal),            }        }        let mut out = Vec::with_capacity(rows.len());        for args in rows {            match self.post("seal", args.clone()) {                Ok(()) => out.push(Ok(())),                Err(refusal) if refusal.status == 0 || refusal.signs_out() || refusal.code == GENERATION_MOVED => return Err(refusal),                Err(refusal) => out.push(Err(refusal)),            }        }        Ok(out)    }    fn post(&self, act: &str, args: Value) -> Result<(), ObjectRefusal> {        self.guard(act, &args)?;        self.requests.fetch_add(1, std::sync::atomic::Ordering::Relaxed);        let answer = self.address.send(self.exchange.as_ref(), "POST", routes::ACT, self.act_headers(), Some(&json!({"act": act, "args": args})))?;        self.note_stale(&answer);        Ok(())    }    /// An act's answer saying `definitions_stale` (LOCK TABLES 2, H1: assets/design/shared/SEALING-CONTRACT.md): the    /// object took a write this copy sealed under an older, wider clear list. The held etag goes, so this pass's pull    /// asks for the definitions whole and the copy holds the narrower list before its next write.    fn note_stale(&self, answer: &Value) {        if answer["definitions_stale"] == json!(true) {            if let Some(held) = &self.definitions {                held.hold(None);            }        }    }    /// [`crate::seal::guard_act`] against this pass's map: what every act    /// this transport posts passes first.    pub(crate) fn guard(&self, act: &str, args: &Value) -> Result<(), ObjectRefusal> {        let map = self.map();        crate::seal::guard_act(|table| map.object(table).and_then(|stored| stored.seal.clone()), act, args)            .map_err(|message| ObjectRefusal { status: 400, code: crate::seal::SEAL_CLEAR_REFUSED.into(), message })    }    /// Write what a pass learned of sealed rows through the pass's own    /// handle on the copy. A pass lent none, with something to keep, says so.    /// The object tables this copy keeps that the object seals and the copy has not seen sealed ([`crate::seal::turned_sealed`]).    fn turned_sealed(&self) -> Result<Vec<String>, String> {        let map = self.map();        let sealed: Vec<(String, String, String)> = map.names().filter_map(|table| map.object(table).filter(|stored| stored.seal.is_some()).map(|stored| (table.to_string(), stored.store.clone(), stored.key_column.clone()))).collect();        self.with_copy(|db| crate::seal::turned_sealed(db, &sealed))    }    /// `tables` came again whole: seen sealed from now on.    fn know_sealed(&self, tables: &[String]) -> Result<(), String> {        self.with_copy(|db| crate::seal::know_sealed(db, tables))    }    /// The copy's own connection: the pass's, or the file itself outside one.    fn with_copy<T>(&self, f: impl FnOnce(&rusqlite::Connection) -> Result<T, String>) -> Result<T, String> {        let Some(file) = self.file.as_deref() else {            let db = rusqlite::Connection::open(&self.replica).map_err(|error| format!("this phone's copy could not be opened ({error})"))?;            return f(&db);        };        crate::sync::cycle::borrowed(file, |db| f(db.connection()))    }    /// FIRST SYNC FAST: while a long pull runs, a page's commit does not also copy the log into the file and sync it    /// (SQLite's autocheckpoint, on every commit past 1,000 pages of log: on the box it was most of a keyed page's    /// time). The copy is checkpointed every CHECKPOINT_EVERY_PAGES pages instead, passively, on a connection of its    /// own off the fold's path, so the log stays a few pages long; the pull's last page gives the commit its    /// checkpoint back.    fn hold_checkpoints(&self, more: bool) {        let Some(file) = self.file.as_deref() else { return };        let pages = if more { self.held_pages.fetch_add(1, Ordering::Relaxed) + 1 } else { self.held_pages.swap(0, Ordering::Relaxed) };        let pragma = if more { "PRAGMA wal_autocheckpoint = 0" } else { "PRAGMA wal_autocheckpoint = 1000" };        if pages <= 1 || !more {            if let Err(error) = crate::sync::cycle::borrowed(file, |db| db.exec(pragma)) {                eprintln!("[object] the copy's checkpoint could not be set ({error})");            }        }        if more && pages % CHECKPOINT_EVERY_PAGES == 0 && !CHECKPOINTING.swap(true, Ordering::AcqRel) {            let replica = self.replica.clone();            let spawned = std::thread::Builder::new().name("cotton-checkpoint".into()).spawn(move || {                if let Ok(db) = rusqlite::Connection::open(&replica) {                    let _ = db.busy_timeout(std::time::Duration::from_secs(5));                    let _ = db.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()));                }                CHECKPOINTING.store(false, Ordering::Release);            });            if spawned.is_err() {                CHECKPOINTING.store(false, Ordering::Release);            }        }    }    /// QUEUE BAD OP 4: the changes kept aside for this database (kept copies, a carried file beside this one) that    /// read in this build are sent from this copy at their original time ([`crate::copy_keep::recover`]). What it    /// cannot do now waits for the next pass; nothing here ever removes what it could not send.    fn recover_kept(&self) {        let Some(file) = self.file.as_deref() else { return };        let Some(folder) = self.replica.parent() else { return };        let Some(database) = folder.file_name().map(|name| name.to_string_lossy().into_owned()) else { return };        // `<root>/client/<database>/replica.db`: a copy elsewhere (a waiting copy) recovers nothing.        let Some(root) = folder.parent().filter(|client| client.file_name().is_some_and(|name| name == "client")).and_then(Path::parent) else { return };        let layout = crate::layout::Layout::new(root);        let carried = carried_path(&self.replica);        if !carried.exists() && !crate::copy_keep::kept_dir(&layout, &database).exists() {            return;        }        let wall_ms = chrono::Utc::now().timestamp_millis();        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SystemRandom));        match crate::sync::cycle::borrowed(file, |db| crate::copy_keep::recover(&layout, &database, db, &self.replica, wall_ms, &mut ids)) {            Ok(recovery) if recovery.sent > 0 || recovery.kept_copies_gone > 0 => eprintln!("[copy-keep] {} 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] the kept changes wait for the next pass ({error})"),        }    }    fn keep_notes(&self, notes: &[crate::seal::Note]) -> Result<(), String> {        if notes.is_empty() {            return Ok(());        }        let Some(file) = self.file.as_deref() else {            // Outside a pass (a remake sending the copy's writes before it            // goes): the copy's own file, which nothing else holds open.            let db = rusqlite::Connection::open(&self.replica).map_err(|error| format!("this phone's copy could not be opened to keep its seal state ({error})"))?;            return crate::seal::write_notes(&db, notes);        };        crate::sync::cycle::borrowed(file, |db| crate::seal::write_notes(db.connection(), notes))    }    /// The notes of rows opened from their parks, kept with the parks left    /// in place ([`crate::seal::write_reopened_notes`]).    fn keep_reopened_notes(&self, notes: &[crate::seal::Note]) -> Result<(), String> {        // What opened here waits to let its park go until the page folds.        *self.unparks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = notes            .iter()            .filter_map(|note| match note {                crate::seal::Note::Sealed { table, id, version, .. } | crate::seal::Note::Open { table, id, version } => Some((table.clone(), id.clone(), *version)),                _ => None,            })            .collect();        if notes.is_empty() {            return Ok(());        }        let Some(file) = self.file.as_deref() else {            let db = rusqlite::Connection::open(&self.replica).map_err(|error| format!("this phone's copy could not be opened to keep its seal state ({error})"))?;            return crate::seal::write_reopened_notes(&db, notes);        };        crate::sync::cycle::borrowed(file, |db| crate::seal::write_reopened_notes(db.connection(), notes))    }    /// Does this parked row already stand in the copy, opened and folded by    /// an earlier pass: noted at its version or later, and its row there?    fn stands(&self, parked: &crate::seal::ParkedRow, file: &rusqlite::Connection) -> Result<bool, String> {        self.stands_at(&parked.table, &parked.id, parked.row["version"].as_i64().unwrap_or(0), file)    }    fn stands_at(&self, name: &str, id: &str, version: i64, file: &rusqlite::Connection) -> Result<bool, String> {        let map = self.map();        let Some(table) = map.object(name) else { return Ok(false) };        let failed = |error: rusqlite::Error| format!("this phone's copy could not be read for its parked rows ({error})");        let noted: Option<i64> = file            .query_row("SELECT version FROM _seal WHERE tbl = ?1 AND row_id = ?2", [name, id], |row| row.get(0))            .map(Some)            .or_else(|error| if matches!(error, rusqlite::Error::QueryReturnedNoRows) { Ok(None) } else { Err(error) })            .map_err(failed)?;        if noted.is_none_or(|noted| noted < version) {            return Ok(false);        }        let exists: i64 = file.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [&table.store], |row| row.get(0)).map_err(failed)?;        if exists == 0 {            return Ok(false);        }        file.query_row(&format!("SELECT EXISTS (SELECT 1 FROM \"{}\" WHERE \"{}\" = ?1)", table.store, table.key_column), [id], |row| row.get::<_, i64>(0)).map(|n| n == 1).map_err(failed)    }    /// A row of a sealed table as this pass folds it: opened, or parked by    /// name (`None`). A row of any other table, as it came; a `seal_key` row    /// is the sealer's and folds nowhere.    fn unsealed(&self, row: &Value, notes: &mut Vec<crate::seal::Note>, at: &str) -> Option<Value> {        let name = row["table"].as_str().unwrap_or_default();        if name == crate::seal::SEAL_KEY_TABLE {            if let (Some(id), Some(data)) = (row["id"].as_str(), row["data"].as_object()) {                if let Some(sealer) = &self.sealer {                    sealer.learn(id, data);                }                notes.push(crate::seal::Note::Key { id: id.into(), data: data.clone() });            }            return None;        }        let map = self.map();        let spec = map.object(name).and_then(|table| table.seal.as_ref());        let opened = match crate::seal::unseal(self.sealer.as_deref(), spec, row, at) {            None => Some(row.clone()),            Some((row, note)) => {                notes.push(note);                row            }        };        // A row whose post stood refused as moved: its newer text is kept.        if let Some(opened) = &opened {            let id = opened["id"].as_str().unwrap_or_default();            let watched = self.moved.lock().unwrap_or_else(std::sync::PoisonError::into_inner).contains(&(name.to_string(), id.to_string()));            if watched {                if let Some(data) = opened["data"].as_object() {                    notes.push(crate::seal::Note::Pulled { table: name.to_string(), id: id.to_string(), data: data.clone() });                }            }        }        opened    }    /// The rows parked because they did not open, opened now that a key is    /// held: the ops they fold as, with their notes, and whether rows of the    /// kit's late tables were left parked for the next page. Asked on the    /// first page of every pass, whether it opens a pull or goes on with one.    ///    /// IN THE KIT'S ORDER (seen on an emulator, 22 Nov 2026): a new phone's    /// first pull runs while it waits for the key, so every row it brings    /// parks, and all of them opened in one fold: Comms' chats stood only once    /// its mail had opened with them. While a row of a table the kit does not    /// name late opens, the late tables' rows (mail) wait for the next page, so    /// the chats fold first, and the pass rests there so they are drawn    /// before the mail opens; once nothing else opens they open too.    fn reopened(&self, workspace_id: &str, file: &rusqlite::Connection, notes: &mut Vec<crate::seal::Note>, at: &str) -> Result<(Vec<CottonOp>, bool), String> {        // What an earlier page opened and did not fold (its pass failed) never lets a park go on this one.        self.unparks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();        if !self.sealer.as_ref().is_some_and(|sealer| sealer.has_key()) {            return Ok((Vec::new(), false));        }        let late: &[String] = self.kit.as_deref().map_or(&[], |kit| kit.late.as_slice());        // A park whose row an earlier pass already folded goes; only the rest open again. At most        // REOPEN_AT_ONCE a page: a full batch rests the pass, which comes straight back for the next.        let mut waiting = Vec::new();        // Parents first among the untried: the kit's own order of its tables (a conversation before its mail).        let first: Vec<String> = self.kit.as_deref().map_or_else(Vec::new, |kit| kit.tables.iter().map(|table| table.rsplit('/').next().unwrap_or(table).to_string()).collect());        let batch = crate::seal::parked_next_in(file, late, &first, reopen_at_once())?;        let full = batch.len() >= reopen_at_once();        // Progress, which alone asks the pass back for more: a park let go, or a row not tried before. A row that        // opens and whose fold is then refused is tried, marked and behind the rest; a batch of tried rows alone asks        // nothing more this pass, so no row is read, opened and refused again every second (FIRST SYNC 2 REVIEW).        let mark = crate::seal::try_mark(file)?;        let mut moved = false;        let mut fresh = false;        for parked in batch {            if self.stands(&parked, file)? {                moved = true;                notes.push(crate::seal::Note::Unparked { table: parked.table, id: parked.id });            } else {                waiting.push(parked);            }        }        let (later, now): (Vec<_>, Vec<_>) = waiting.into_iter().partition(|parked| late.contains(&parked.table));        let mut ops = Vec::new();        let mut opened_fresh = false;        // Each row tried is marked, opened or not; a row that still does not open is parked again under the same        // mark, never the phone's clock.        // A tried row that opens counts too, unless it opened before and its fold was refused: it failed to open        // before (another key's), and now it opens.        let mut tried = |parked: &crate::seal::ParkedRow, notes: &mut Vec<crate::seal::Note>| {            fresh |= !parked.tried();            notes.push(crate::seal::Note::Tried { table: parked.table.clone(), id: parked.id.clone(), at: mark.clone() });        };        let mut reopened_tried = false;        // Opened is the seal's own word: a row whose table this copy no longer maps or seals comes back from        // `unsealed` as it was, opens nothing, never stands, and would count as progress every batch (FIRST SYNC 4        // REVIEW). It is tried and marked like any other, and is no progress.        let seals = |parked: &crate::seal::ParkedRow| self.map().object(&parked.table).is_some_and(|table| table.seal.is_some());        for parked in &now {            tried(parked, notes);            if let Some(row) = self.unsealed(&parked.row, notes, &mark).filter(|_| seals(parked)) {                opened_fresh |= !parked.tried();                reopened_tried |= parked.tried() && parked.code != crate::seal::FOLD_REFUSED && parked.code != crate::seal::WAITING_PARENT;                if let Some(op) = self.op_of(&row, workspace_id, file)? {                    ops.push(op);                }            }        }        // The kit's late tables wait one page while rows not tried before opened ahead of them (drawn first); rows        // tried before never hold them back, nor do rows that still do not open (another key's).        if opened_fresh && !later.is_empty() {            return Ok((ops, true));        }        for parked in &later {            tried(parked, notes);            if let Some(row) = self.unsealed(&parked.row, notes, &mark).filter(|_| seals(parked)) {                reopened_tried |= parked.tried() && parked.code != crate::seal::FOLD_REFUSED && parked.code != crate::seal::WAITING_PARENT;                if let Some(op) = self.op_of(&row, workspace_id, file)? {                    ops.push(op);                }            }        }        Ok((ops, full && (moved || fresh || reopened_tried)))    }    /// The `seal_key` rows this copy keeps, taken by the sealer before a    /// pass seals anything.    fn learn_kept_keys(&self) -> Result<(), String> {        let Some(sealer) = &self.sealer else { return Ok(()) };        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read for its seal keys ({error})"))?;        for (id, data) in crate::seal::kept_keys(&file)? {            sealer.learn(&id, &data);        }        drop(file);        // A copy that has pulled the object to its end holds every seal key        // the object held then.        if !sealer.has_learned() && caught_up(&self.replica, 1).unwrap_or(false) {            sealer.learned_all();        }        Ok(())    }    /// Every `seal_key` row the object holds, asked for whole and taught to    /// the sealer, once per sealer, before it seals anything: a copy that    /// has not pulled to the object's end (a brand-new one writing before    /// its first pass, an adopt, a restore) would otherwise seal under    /// version 1 while the object is past it. Not answered is    /// [`crate::seal::SEAL_KEY_MISSING`], retryable: the write waits.    pub(crate) fn learn_seal_keys(&self) -> Result<(), ObjectRefusal> {        let Some(sealer) = &self.sealer else { return Ok(()) };        if sealer.has_learned() {            return Ok(());        }        let waits = |why: String| ObjectRefusal { status: 0, code: crate::seal::SEAL_KEY_MISSING.into(), message: format!("the object's seal keys could not be read, so nothing is sealed yet ({why})") };        let mut notes = Vec::new();        let mut path = format!("{}?since=0&tables={}", routes::SYNC, crate::seal::SEAL_KEY_TABLE);        loop {            let (answer, _) = self.ask_page(&path).map_err(|refusal| waits(format!("{}, status {}", refusal.message, refusal.status)))?;            for row in answer["rows"].as_array().into_iter().flatten() {                if row["table"] != json!(crate::seal::SEAL_KEY_TABLE) || row["deleted"] == json!(true) {                    continue;                }                if let (Some(id), Some(data)) = (row["id"].as_str(), row["data"].as_object()) {                    sealer.learn(id, data);                    notes.push(crate::seal::Note::Key { id: id.into(), data: data.clone() });                }            }            match answer["next"].as_str() {                Some(next) => path = format!("{}?cursor={next}", routes::SYNC),                None => break,            }        }        // Kept beside the copy when a pass lent one (seal.openKey reads it there).        if self.file.is_some() {            self.keep_notes(&notes).map_err(waits)?;        }        sealer.learned_all();        Ok(())    }    /// The sealing sweep over this copy's open rows of sealed tables    /// ([`crate::seal::sweep`]), once a pull has reached the object's end.    fn sweep(&self) -> Result<(), String> {        let Some(sealer) = &self.sealer else { return Ok(()) };        // The arrival key the object seals its own writes to (e2e rulings        // R2), handed over once by a device that holds the DK.        if sealer.has_learned() {            if let Some(args) = sealer.arrival_row() {                if let Err(refusal) = self.post("create", args) {                    eprintln!("[object] the arrival key was not taken: {} ({})", refusal.message, refusal.code);                }            }        }        let map = self.map();        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read for its open sealed rows ({error})"))?;        let open = crate::seal::sweep::open_rows(&file, &map)?;        if open.is_empty() {            return Ok(());        }        if let Err(refusal) = self.learn_seal_keys() {            eprintln!("[object] the sealing sweep waits: {}", refusal.message);            return Ok(());        }        // Bounded per pass (SYNC STUCK, 25 Nov 2026): what is left goes after the next pass's pull.        let swept = crate::seal::sweep::sweep(            sealer,            &map,            &open,            crate::seal::sweep::Budget::pass(),            // A row this copy does not hold (yet) is not the sweep's.            |table, id| match map.object(table) {                Some(stored) if !file_columns(&file, &stored.store)?.is_empty() => row_now(&file, stored, id),                _ => Ok(None),            },            |rows| self.seal_rows(rows),            |notes| self.keep_notes(notes),        )?;        drop(file);        if let Some(why) = &swept.stopped {            eprintln!("[object] the sealing sweep stopped: {why}");        }        // What it left, by table and why, in counts (the memory lock, 24 Nov 2026: 21 of the owner's entries stood open        // an hour with no word of why). "gone from this copy" is a row the copy's rules refused to hold.        let mut left: std::collections::BTreeMap<(&str, &str), usize> = std::collections::BTreeMap::new();        for (table, _, why) in &swept.left {            *left.entry((table.as_str(), why.as_str())).or_default() += 1;        }        for ((table, why), n) in left {            eprintln!("[object] the sealing sweep left {n} {table} row(s): {why}");        }        if swept.more {            eprintln!("[object] the sealing sweep goes on next pass: this pass's share is done");        }        Ok(())    }    // ── pull ───────────────────────────────────────────────────────────────    /// One page from where this file stands. Answers the ops, the cursor to    /// hold once they are folded, whether more waits, the object's clock when    /// it answered — the judge time this phone's writes are stamped by — and    /// the tables whose rows its cursor went past ([`PASSED_KEY`]).    fn pull(&self, request: &ExchangeRequest) -> Result<Pulled, String> {        self.recover_kept();        let held = request.cursors.get(CURSOR_KEY).map(String::as_str).unwrap_or("");        let (mut pulls, mut since, page) = read_cursor(held);        let passed = request.cursors.get(PASSED_KEY).and_then(|text| Passed::read(text));        // THE ROOM GUARD STOPS ONLY THE FILL (ANDROID READY 1 core fault 3, Cotton Data DECISIONS question 3): a pull        // from the start, or one that owes tables whole, is the fill, and waits where it stood while the guard gives a        // reason, the pass ending well (its writes went up above). It failed the pass, so short of room every write        // waited and the app said "Cotton not reached yet" for as long. A pull since the cursor of a copy that has        // reached the object's end is the sync itself, and goes on.        let fill = since == 0 || passed.as_ref().is_none_or(|passed| passed.owed(pulls, &self.map()));        if let Some(why) = self.stop.as_ref().filter(|_| fill).and_then(|stop| stop()) {            eprintln!("[object] the fill waits: {why}");            self.level_after_fold.store(false, std::sync::atomic::Ordering::SeqCst);            return Ok(Pulled { ops: Vec::new(), cursor: held.to_string(), more: false, server_time: None, passed: request.cursors.get(PASSED_KEY).cloned().unwrap_or_default(), features: None, stopped: true });        }        // A pass that opens placing a table whose rows the cursor went past        // (or on a copy that cannot say which those are) pulls again from the        // start: the cursor counts one more pull and its version begins at        // nothing, so it still moves forward. Judged on the map as the pass        // opens and again once its first page has placed what the object        // serves (a table this build reads that an earlier one left on it).        let owed = |pulls: u32| passed.as_ref().is_none_or(|passed| passed.owed(pulls, &self.map()));        let opening = page.is_none();        // What is owed is some tables alone: they come again whole, the rest since the cursor.        let again_of = |pulls: u32| passed.as_ref().and_then(|passed| passed.owed_tables(pulls, &self.map())).unwrap_or_default();        let mut again: Vec<String> = Vec::new();        if opening && since > 0 && owed(pulls) {            again = again_of(pulls);            if again.is_empty() {                (pulls, since) = (pulls + 1, 0);            }        }        // A table the object sealed since this copy last looked (the memory lock): its rows came while it was open        // and carry no seal note, so no sweep would reach them. It comes again whole, once ([`crate::seal::turned_sealed`]).        let mut turned: Vec<String> = Vec::new();        if opening && since > 0 && again.is_empty() && !owed(pulls) {            turned = self.turned_sealed()?;            again = turned.clone();        }        // Whether the first answer said it carried them, and whether the placed map was looked at for them.        let mut turned_checked = false;        let mut turned_looked = !turned.is_empty();        let mut ops = Vec::new();        if !self.knows_its_author()? {            ops.push(object_author_fact(&request.workspace_id)?);        }        // Whether the object's definitions came, once this pull asked.        let mut came: Option<bool> = None;        // A fresh copy — no pull has ended on it and no record of one is        // held — fills with the app's own tables first ([`Self::first_fill`]).        let filling = pulls == 0 && since == 0 && passed.is_none() && self.first_fill().is_some();        let mut path = match page {            Some((_, mark)) => format!("{}?cursor={mark}", routes::SYNC),            None => with_again(self.first_page_of(since, filling, self.short_pages(&again)), &again),        };        // The pages of that first fill carry on its record: the tables it        // leaves for later, which the next pass owes from the start.        let filling = filling || (pulls == 0 && since == 0 && page.is_some() && passed.as_ref().is_some_and(|passed| passed.pulls == 0 && passed.tables.contains(FIRST_FILL_MARK)));        let ordinal = page.map_or(0, |(ordinal, _)| ordinal);        // A copy's very first page: its first sync's times begin (PHONE MEASURES).        if pulls == 0 && since == 0 && page.is_none() && passed.is_none() {            crate::first_sync::begin(&self.replica, chrono::Utc::now().timestamp_millis());        }        // Rows parked because they did not open are tried again on the first        // page every pass asks, not only a pull's opening one: a pull a        // time-boxed background slice stopped mid-way goes on from its page        // on the pass after the vault opened, and the rows it parked for want        // of the key open then. Opened before the        // page is asked: while they leave the kit's late tables parked, this        // pass asks no page at all and rests on what opened, so the first fold        // after the key holds those rows alone (Comms on an emulator, 22 Nov        // 2026: the chats opened with a page of 5,000 mail rows pulled beside        // them and stood 16 s after the key, against 9 s without mail). The        // cursor stays where it was, and the next pass asks from it.        let (mut reopened, mut reopened_notes, mut late_left) = (Vec::new(), Vec::new(), false);        {            let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)                .map_err(|error| format!("this phone's copy could not be read ({error})"))?;            let (opened, left) = self.reopened(&request.workspace_id, &file, &mut reopened_notes, &chrono::Utc::now().to_rfc3339())?;            (reopened, late_left) = (opened, left);            if late_left {                self.rest.store(true, std::sync::atomic::Ordering::SeqCst);                if let (false, Some(passed)) = (held.is_empty(), request.cursors.get(PASSED_KEY)) {                    drop(file);                    self.keep_reopened_notes(&reopened_notes)?;                    ops.extend(reopened);                    return Ok(Pulled { ops, cursor: held.to_string(), more: true, server_time: None, passed: passed.clone(), features: None, stopped: false });                }            }        }        let mut first = true;        loop {            let asked_at = std::time::Instant::now();            let (answer, received, opened) = match self.ask_page(&path) {                Ok((answer, received)) => (answer, received, opening),                // A page token the object no longer reads (it was built again                // since the pass began): the pass begins again from the version                // this copy holds, under the next ordinal, so the cursor still                // moves forward and the phone never asks the same refused page                // for ever.                // Tables the record still owes whole are asked again with it.                Err(refusal) if !opening && refusal.code == "bad_cursor" => match self.ask_page(&with_again(self.first_page_of(since, false, self.short_pages(&again_of(pulls))), &again_of(pulls))) {                    Ok((answer, received)) => (answer, received, true),                    Err(refusal) => return Err(self.refused(&refusal)),                },                Err(refusal) => return Err(self.refused(&refusal)),            };            // The row this phone's passes are written on, known from the            // answer before anything is read of it: a page this copy cannot            // take still says why there ([`SyncProgress::troubled`]).            if let Some(progress) = &self.progress {                progress.named(&answer);            }            let version = answer["version"].as_i64().unwrap_or(since);            let (cursor, more) = match answer["next"].as_str() {                Some(next) => (page_cursor(pulls, since, ordinal + 1, next), true),                None => (version_cursor(pulls, version), false),            };            let rows = answer["rows"].as_array().map(Vec::as_slice).unwrap_or_default();            // The object's tables, tools and boards: on every page until this launch            // holds them (a fresh copy's first pass is the whole catch-up, and            // the fan draws them from its first page), on a pass's last page when            // the object has moved since the pass began, and on any page holding            // rows of a table this pass places nowhere that the object's last            // definitions did not name (one made since). Asked before the rows are            // read, so a table's rows land with the definition that places them.            if let Some(definitions) = self.definitions.as_ref() {                let unplaced = {                    let map = self.map();                    rows.iter().filter_map(|row| row["table"].as_str()).any(|table| map.object(table).is_none() && !definitions.serves(table))                };                // Asked once a pull: a page asked again from the start folds                // with what the first answer brought.                if came.is_none() && (definitions.etag().is_none() || (!more && version != since) || unplaced) {                    came = Some(match self.served_definitions(definitions, &request.workspace_id, answer["server_time"].as_str())? {                        Some(served) => {                            ops.extend(served);                            true                        }                        None => false,                    });                }                // Rows this copy cannot place yet wait for the next pass,                // which asks again, rather than pass by for good.                if unplaced && came == Some(false) {                    return Err("the object's definitions did not come, and this page holds rows only they place: the pass waits for them".into());                }            }            // The tables this pass carries again whole, as the object says it does.            let carried: Vec<String> = answer["again"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();            // A turned table the object did not carry whole (an older Worker) is not seen yet: asked again next pass.            if !turned_checked && !turned.is_empty() {                turned_checked = true;                if !turned.iter().all(|table| carried.contains(table)) {                    turned.clear();                }            }            if opening && since > 0 && owed(pulls) && !(again.is_empty() || again.iter().all(|table| carried.contains(table))) {                // An object that did not carry them (an older Worker): the pull from the start, as before.                (pulls, since, again) = (pulls + 1, 0, Vec::new());                path = self.first_page(since);                continue;            }            // A table turned sealed shows only once this page placed what the object serves: asked again with it.            if opening && since > 0 && again.is_empty() && !turned_looked && !owed(pulls) {                turned_looked = true;                turned = self.turned_sealed()?;                if !turned.is_empty() {                    again = turned.clone();                    path = with_again(self.first_page_of(since, false, self.short_pages(&again)), &again);                    continue;                }            }            if opening && since > 0 && again.is_empty() && owed(pulls) {                // Owed only once this page placed what the object serves.                again = again_of(pulls);                if again.is_empty() {                    (pulls, since) = (pulls + 1, 0);                    path = self.first_page(since);                } else {                    path = with_again(self.first_page_of(since, false, self.short_pages(&again)), &again);                }                continue;            }            // The next page is asked now, while this one's rows are opened, parked and folded (FIRST SYNC FAST: the            // ask was a third of a first sync, waited for between pages).            if let Some(next) = answer["next"].as_str() {                self.ask_ahead(format!("{}?cursor={next}", routes::SYNC));            }            self.hold_checkpoints(answer["next"].is_string());            let map = self.map();            let mut went_past = Vec::new();            if filling {                went_past.push(FIRST_FILL_MARK.to_string());                went_past.extend(self.first_fill().map(|(_, later)| later).unwrap_or_default());            }            let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)                .map_err(|error| format!("this phone's copy could not be read ({error})"))?;            let at = answer["server_time"].as_str().unwrap_or_default().to_string();            // The rows opened before the page was asked fold here, as they always have, after the definitions;            // their notes are kept with their parks left until they stand in the copy.            let mut notes = Vec::new();            if first {                self.keep_reopened_notes(&std::mem::take(&mut reopened_notes))?;                ops.extend(std::mem::take(&mut reopened));            }            first = false;            // Whole tables the object erased for good since this copy's cursor            // (owner, 22 Nov 2026; apps/business src/erase.ts): every row this            // copy holds of one is retracted, stamped at the moment it went,            // before the page's rows fold, so a row written since stands.            ops.extend(self.dropped(&answer["dropped"], &request.workspace_id, &file)?);            let asked_ms = asked_at.elapsed().as_millis();            let (mut unseal_us, mut op_us, rows_at) = (0u128, 0u128, std::time::Instant::now());            for row in rows {                let unsealing = std::time::Instant::now();                let unsealed = self.unsealed(row, &mut notes, &at);                unseal_us += unsealing.elapsed().as_micros();                let Some(row) = unsealed else { continue };                let row = &row;                match row["table"].as_str().map(|name| (name, map.object(name))) {                    Some((name, None)) => went_past.push(name.to_string()),                    // A key this copy keeps nowhere yet: a later map that                    // places it pulls the rows again ([`Passed::owed`]).                    Some((name, Some(table))) => {                        for column_name in row["data"].as_object().into_iter().flat_map(|data| data.keys()) {                            if !table.places(column_name) {                                went_past.push(format!("{name}.{column_name}"));                            }                        }                    }                    None => {}                }                let making = std::time::Instant::now();                if let Some(op) = self.op_of(row, &request.workspace_id, &file)? {                    ops.push(op);                }                op_us += making.elapsed().as_micros();            }            drop(file);            let noting = std::time::Instant::now();            self.keep_notes(&notes)?;            let (page_rows, noted_ms) = (rows.len() as u64, noting.elapsed().as_millis() as u64);            crate::first_sync::add(&self.replica, |times| {                times.waiting_ms += asked_ms as u64;                times.opening_ms += (unseal_us / 1000) as u64;                times.merging_ms += (op_us / 1000) as u64 + noted_ms;                times.pages += 1;                times.rows += page_rows;            });            if sync_times() {                eprintln!("[sync-times] page rows={} bytes={received} ask_ms={asked_ms} unseal_ms={} op_ms={} rows_ms={} notes={} notes_ms={} more={more}", rows.len(), unseal_us / 1000, op_us / 1000, rows_at.elapsed().as_millis(), notes.len(), noting.elapsed().as_millis());            }            if let Some(progress) = &self.progress {                progress.knows(&map);                // Said on a pull's last page, and every REPORT_EVERY_PAGES pages of a long one (FIRST SYNC FAST: during                // a first pull the row stood still, and slow and stuck looked the same).                let due = !more || (progress.state().pages + 1) % REPORT_EVERY_PAGES == 0;                let reported_state = due.then(|| self.reported_state.as_ref().and_then(|state| state())).flatten();                let reports = progress.landed(Landed { held, cursor: &cursor, answer: &answer, received, opened, more, reported_state });                self.report(progress, reports);            }            // The tables whose rows this page went past, with those the record            // of this pull from the start named: held with the cursor, so the            // two always move together.            // A pass that carried tables again whole lets them go from the record once its last page has landed.            let before = passed.clone().filter(|passed| passed.pulls == pulls).map(|passed| if more { passed } else { passed.without(&carried) });            let passed = Passed::after(before, pulls, went_past);            if !more && !turned.is_empty() {                self.know_sealed(&turned)?;            }            // The page's fold is timed until it is folded ([`SyncingTransport::folded`]); the last page of a pull that            // leaves nothing owed ends the first sync once it is folded.            *self.pulled_at.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::time::Instant::now());            self.level_after_fold.store(!more && !late_left && !passed.owed(pulls, &map), std::sync::atomic::Ordering::SeqCst);            return Ok(Pulled { ops, cursor, more: more || late_left, server_time: answer["server_time"].as_str().map(str::to_string), passed: passed.text(), features: features_text(&answer), stopped: false });        }    }    /// The object's tables, tools and boards as receipts this copy folds: each the    /// copy does not hold as the object serves it, and a retract of each row    /// it no longer serves unless builtin, whoever wrote it; and the tables this pass    /// places, those served taken into its map. An answer that changed the    /// copy is asked again by the next pass (the etag is held only once the    /// copy matches it). `None` when no answer came: the next pass asks again.    fn served_definitions(&self, held: &HeldDefinitions, workspace_id: &str, at: Option<&str>) -> Result<Option<Vec<CottonOp>>, String> {        let mut headers = bearer(&self.credential);        if let Some(etag) = held.etag() {            headers.push(("If-None-Match".into(), format!("\"{etag}\"")));        }        let answer = match self.address.send(self.exchange.as_ref(), "GET", routes::DEFINITIONS, headers, None) {            Ok(answer) if answer["unchanged"] == json!(true) => return Ok(Some(Vec::new())),            Ok(answer) => {                held.name(answer["tables"].as_array().into_iter().flatten());                kept_to(&answer, self.kit.as_deref())            }            Err(refusal) => {                held.hold(None);                // AN OBJECT FAILING IS NEVER THIS COPY'S FAULT (incident, 21 Nov                // 2026): the refusal is held as the pass's last, so a pass that                // then stops for want of the definitions reads as the object                // refusing — not as the copy stuck on its page, which three                // passes running would make again from an object that was                // failing, leaving the phone an empty copy for the outage.                if refusal.transient() {                    self.refused(&refusal);                }                eprintln!("[object] the definitions were not had this pass ({}): asked again by the next", refusal.message);                return Ok(None);            }        };        let copy = cotton_store::driver::Driver::open_snapshot_reader(&self.replica).map_err(|error| format!("this phone's copy could not be read ({error})"))?;        let file = copy.connection();        let at_ms = at            .and_then(cotton_store::protocol::js::parse_date_ms)            .unwrap_or_else(|| chrono::Utc::now().timestamp_millis())            .clamp(0, cotton_store::protocol::hlc::MAX_MS);        let tables = drawable_tables(&answer["tables"]);        self.place(tables.iter().map(|(_, definition)| definition))?;        held.serve(answer["tables"].as_array().into_iter().flatten().filter_map(|table| table["id"].as_str()));        let waiting = {            let taken = self.taken.lock().unwrap_or_else(|poisoned| poisoned.into_inner());            waiting_definitions(&copy, &taken)?        };        let left = |table: &ServedTable| waiting.get(table.store).cloned().unwrap_or_default();        let mut ops = served_definitions(file, &SERVED_TABLES, tables, workspace_id, at_ms, &left(&SERVED_TABLES))?;        let tables = ops.len();        ops.extend(served_definitions(file, &SERVED_TOOLS, drawable_tools(&answer["tools"]), workspace_id, at_ms, &left(&SERVED_TOOLS))?);        let tools = ops.len() - tables;        ops.extend(served_definitions(file, &SERVED_BOARDS, served_boards(&answer["boards"]), workspace_id, at_ms, &left(&SERVED_BOARDS))?);        let boards = ops.len() - tables - tools;        ops.extend(served_definitions(file, &SERVED_THEMES, served_boards(&answer["themes"]), workspace_id, at_ms, &left(&SERVED_THEMES))?);        ops.extend(served_owner(&copy, &answer["business"], workspace_id, at_ms)?);        let etag = answer["etag"].as_str().map(str::to_string);        if tools + tables + boards > 0 {            eprintln!("[object] definitions: took {tools} tools, {tables} tables, {boards} boards from the object");        } else if ops.is_empty() && held.etag().is_none() {            eprintln!("[object] definitions: the copy holds the object's as it serves them (etag {})", etag.as_deref().unwrap_or("none"));        }        // A definition still to send is not yet the object's: the answer is        // asked again, whole, until it is.        held.hold(if ops.is_empty() && waiting.is_empty() { etag } else { None });        Ok(Some(ops))    }    /// This pass's map of the object's tables to this copy's.    fn map(&self) -> Arc<ObjectTables> {        Arc::clone(&self.tables.lock().unwrap_or_else(|poisoned| poisoned.into_inner()))    }    /// Take into this pass's map every table `definitions` define as data,    /// and every column they name on a table this build compiles that its    /// table lacks — which this copy's table then holds, before a row of it    /// is folded or sent. A column the copy cannot take refuses the pass,    /// by name.    fn place<'a>(&self, definitions: impl IntoIterator<Item = &'a Value>) -> Result<(), String> {        let mut map = self.tables.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        let placed = map.with_defined(definitions)?;        self.hold_served(&placed)?;        *map = Arc::new(placed);        Ok(())    }    /// Make this copy's tables hold every column `map` places on a table    /// this build compiles that the build's table lacks: add-only and in    /// place, once (a column the copy holds is left as it is). Read first, so    /// a pass that adds nothing never takes the writer.    fn hold_served(&self, map: &ObjectTables) -> Result<(), String> {        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read ({error})"))?;        let mut owed = Vec::new();        for table in map.tables.iter().filter(|table| table.compiled && !table.served.is_empty()) {            let unreadable = |error: rusqlite::Error| format!("{} could not be read ({error})", table.store);            let mut statement = file.prepare("SELECT name FROM pragma_table_info(?1)").map_err(unreadable)?;            let held: Vec<String> = statement.query_map([&table.store], |row| row.get(0)).map_err(unreadable)?.collect::<Result<_, _>>().map_err(unreadable)?;            if table.served.iter().any(|column| !held.contains(&column.name)) {                owed.push(table);            }        }        drop(file);        if owed.is_empty() {            return Ok(());        }        // Through the pass's own handle on the copy, never a second open: a        // pass lent none cannot take them, and says which.        let Some(file) = self.file.as_deref() else {            let tables: Vec<&str> = owed.iter().map(|table| table.table.as_str()).collect();            return Err(format!("this pass was lent no copy to take the object's columns of {} into", tables.join(", ")));        };        crate::sync::cycle::borrowed(file, |db| {            for table in owed {                let added = package_shape::add_served(db, &table.store, &table.served)                    .map_err(|error| format!("this phone's copy could not take the object's columns of {} ({error})", table.table))?;                if !added.is_empty() {                    eprintln!("[object] this phone's copy now keeps {}", added.join(", "));                }            }            Ok(())        })    }    /// The object's table definitions as this copy holds them: the rows the    /// object last wrote, as earlier passes took them. A table this phone    /// defined itself is its own, and goes nowhere.    fn copy_definitions(&self) -> Result<Vec<Value>, String> {        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read ({error})"))?;        let unreadable = |error: rusqlite::Error| format!("cotton_table_definitions could not be read ({error})");        let mut statement = file.prepare("SELECT definition, _hlc FROM cotton_table_definitions").map_err(unreadable)?;        let rows = statement.query_map([], |row| Ok((row.get::<_, Option<String>>(0)?, row.get::<_, Option<String>>(1)?))).map_err(unreadable)?;        let mut out = Vec::new();        for row in rows {            let (definition, stamp) = row.map_err(unreadable)?;            if cotton_store::fold::author_of(stamp.as_deref().unwrap_or_default()) != Some(OBJECT_AUTHOR) {                continue;            }            if let Some(definition) = definition.and_then(|text| serde_json::from_str(&text).ok()) {                out.push(definition);            }        }        Ok(out)    }    /// The tables a fresh copy's first pull asks for, when it keeps to a kit    /// (launch-fast, 20 Nov 2026): the app's own — its kit's tables but the    /// shared pictures' rows (`media`, every file of the whole object), and    /// the seal keys its sealed rows open with. Pulled in version order over    /// every table, Cotton Story's scripts came down among the whole    /// object's pictures, and a signed-in phone stood minutes on an empty    /// screen. The kit's late tables wait too (Comms' mail, on an emulator,    /// 22 Nov 2026: a new phone's first pull of an account of 110,000 emails    /// brought the mail's 90-day window with the chats, 22,000 rows in one    /// pass, and the recovery card, asked once a pass ends, stood at 47 s    /// against 10 s for an account without mail). The rest is owed by the    /// next pass, whole: the record of the tables this pull went past names    /// them ([`PASSED_KEY`], [`FIRST_FILL_MARK`]).    fn first_fill(&self) -> Option<(Vec<String>, Vec<String>)> {        let kit = self.kit.as_ref()?;        let all = kit.pulled();        let own: Vec<String> = all            .iter()            .filter(|table| (kit.tables.contains(table) && table.as_str() != FIRST_FILL_LATER && !kit.late.contains(table)) || table.as_str() == cotton_core::seal::SEAL_KEY_TABLE)            .cloned()            .collect();        let later: Vec<String> = all.into_iter().filter(|table| !own.contains(table)).collect();        (!own.is_empty() && !later.is_empty()).then_some((own, later))    }    /// The first page of a pass from `since`, with the windows it keeps to;    /// `fill` is a fresh copy's first pull, asking for the app's own tables.    fn first_page(&self, since: i64) -> String {        self.first_page_of(since, false, false)    }    /// `short`: a pass whose pages carry the kit's late tables while no key is held ([`Self::short_pages`]).    fn first_page_of(&self, since: i64, fill: bool, short: bool) -> String {        let rows = if short { KEYLESS_LATE_PAGE_ROWS } else { PAGE_ROWS };        let mut path = format!("{}?since={since}&limit={rows}", routes::SYNC);        let windows: Vec<String> = self.windows.iter().map(|(table, days)| format!("{table}:{days}")).collect();        if !windows.is_empty() {            path.push_str("&window=");            path.push_str(&windows.join(","));        }        if let Some(kit) = &self.kit {            let tables = match self.first_fill().filter(|_| fill) {                Some((own, _)) => own,                None => kit.pulled(),            };            path.push_str("&tables=");            path.push_str(&tables.join(","));            if let Some(only) = kit.only_query() {                path.push_str("&only=");                path.push_str(&only);            }        }        if let Some(named) = &self.named {            let said = [("device_name", Some(&named.name)), ("platform", named.platform.as_ref()), ("app_version", named.app_version.as_ref())];            for (key, value) in said {                if let Some(value) = value {                    path.push_str(&format!("&{key}={}", url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()));                }            }            // This core opens a kept chat picture (22 Nov 2026) and a person's picture (AVATAR SEAL, 27 Nov 2026)            // sealed on a device: the plain ones of a kind are resealed only once every device that pulls its table            // says so (business /v1/media-plain `waiting`).            path.push_str("&opens=messages,people");        }        path    }    /// Whether a pass asking `again`'s tables whole asks short pages: it carries    /// a late table of the kit while this phone holds no key, so its rows only    /// park. A key opened meanwhile waits on one short page, never on five    /// thousand rows (Comms on an emulator, 22 Nov 2026: the recovery code    /// typed while the mail's window came, the key was held 10 s later, against    /// 1.3 s with nothing coming, as the object answered and the copy parked a    /// page of 5,000 mails first, and the chats stood 15.3 s after the key    /// against 9.4 s once the mail had come). The Worker keeps a pass's page    /// size in its cursor, so the pass stays short to its end.    fn short_pages(&self, again: &[String]) -> bool {        let late = self.kit.as_deref().is_some_and(|kit| kit.late.iter().any(|table| again.contains(table)));        late && self.sealer.as_ref().is_some_and(|sealer| !sealer.has_key())    }    /// One sync page: the answer and how many bytes of it arrived.    fn ask_page(&self, path: &str) -> Result<(Value, usize), ObjectRefusal> {        let key = self.ahead_key(path);        let ahead = {            let mut held = AHEAD.lock().unwrap_or_else(|poisoned| poisoned.into_inner());            match held.as_ref().map(|ahead| (ahead.key == key, ahead.key.starts_with(&self.ahead_key("")))) {                Some((true, _)) => held.take(),                // Another page of this copy's: what it asked is let go (its thread ends on its own). Another copy's                // stays for that copy's next ask.                Some((false, true)) => {                    held.take();                    None                }                _ => None,            }        };        let answer = match ahead.and_then(|ahead| ahead.answer.recv().ok()) {            Some(answer) => {                if sync_times() {                    eprintln!("[sync-times] page asked ahead");                }                answer            }            None => ask_page_at(&self.address, self.exchange.as_ref(), &self.credential, path),        };        // RESTORE 2: every page is weighed against the generation this copy holds before anything of it is read.        let (answer, received) = answer?;        self.weigh_generation(&answer)?;        Ok((answer, received))    }    /// Ask the page at `path` now, beside this one's parking and fold (FIRST SYNC FAST): the next [`Self::ask_page`]    /// of that page takes its answer, and any other ask lets it go. Only over an exchange that takes two requests at    /// once, and never while the pull is asked to stop.    fn ask_ahead(&self, path: String) {        if !self.exchange.concurrent() || sync_plain() || self.stop.as_ref().is_some_and(|stop| stop().is_some()) {            return;        }        let key = self.ahead_key(&path);        let (address, exchange, credential) = (self.address.clone(), Arc::clone(&self.exchange), self.credential.clone());        let (send, answer) = std::sync::mpsc::channel();        let asked = std::thread::Builder::new().name("cotton-page-ahead".into()).spawn(move || {            let _ = send.send(ask_page_at(&address, exchange.as_ref(), &credential, &path));        });        if asked.is_ok() {            *AHEAD.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(Ahead { key, answer });        }    }    fn ahead_key(&self, path: &str) -> String {        format!("{}\u{1f}{}\u{1f}{path}", self.replica.display(), self.credential)    }    /// A pass that failed says why on this phone's row, before its failure    /// is answered ([`SyncProgress::troubled`]): how far it got is read off    /// the refusal it met, if any — none is the object answering and this    /// copy unable to go on.    fn troubled(&self, request: &ExchangeRequest, why: &str) {        let Some(progress) = &self.progress else { return };        let met = self.last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone();        progress.frozen(self.frozen.load(std::sync::atomic::Ordering::SeqCst));        // The server was put back (RESTORE 2): the copy is made again, and a write on the row would be refused too.        if met.as_ref().is_some_and(|refusal| refusal.code.as_deref() == Some(GENERATION_MOVED)) {            let _ = progress.troubled(why, Reached::Refused);            return;        }        let reached = match met {            Some(refusal) if refusal.status == 0 => Reached::Nothing,            Some(refusal) if matches!(refusal.status, 401 | 403 | 410 | 429) || refusal.status >= 500 => Reached::Refused,            _ => Reached::Answered { mid_pass: request.cursors.get(CURSOR_KEY).is_some_and(|held| read_cursor(held).2.is_some()) },        };        let reports = progress.troubled(why, reached);        self.report(progress, reports);    }    /// Post what [`SyncProgress`] asks to be written on this phone's row. A    /// write that does not land is asked again by the next page; it never    /// fails the pass, which is the rows' and not the report's.    fn report(&self, progress: &SyncProgress, reports: Vec<Report>) {        for report in reports {            let posted = match &report {                Report::Update { device, data } => self.post("update", json!({"table": DEVICE_TABLE, "id": device, "data": data})),            };            if posted.is_ok() {                progress.posted(&report);            }        }    }    /// Whether this copy holds the object's author fact: a copy that has    /// written anything folds no receipt whose author it has no fact of.    fn knows_its_author(&self) -> Result<bool, String> {        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read ({error})"))?;        file.query_row("SELECT 1 FROM cotton_authors WHERE id = ?1", [OBJECT_AUTHOR], |_| Ok(()))            .map(|()| true)            .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(false) } else { Err(format!("this phone's copy could not be read ({error})")) })    }    /// The columns of `table` here that are NOT NULL with a declared    /// default, each with that default as a receipt names it: what this copy    /// holds for a column the object serves nothing in. Read off the copy's    /// own schema once a pass.    fn nothing_in(&self, table: &StoredTable) -> Result<Arc<BTreeMap<String, Value>>, String> {        if let Some(held) = self.nothing.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&table.store) {            return Ok(Arc::clone(held));        }        let unread = |error: rusqlite::Error| format!("{} could not be read here ({error})", table.store);        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX).map_err(unread)?;        let declared: Vec<(String, String)> = file            .prepare("SELECT name, dflt_value FROM pragma_table_info(?1) WHERE \"notnull\" = 1 AND dflt_value IS NOT NULL")            .and_then(|mut statement| statement.query_map([&table.store], |row| Ok((row.get(0)?, row.get(1)?)))?.collect())            .map_err(unread)?;        let mut nothing = BTreeMap::new();        for (column, default) in declared {            let Some((_, _, codec)) = table.columns.iter().find(|(_, ours, _)| *ours == column) else { continue };            let value: SqlValue = file.query_row(&format!("SELECT ({default})"), [], |row| row.get(0)).map_err(unread)?;            let value = decode_value(*codec, &value).and_then(|value| canonical::after_codec(*codec, &value)).map_err(|error| format!("{}.{column}'s default: {error}", table.store))?;            nothing.insert(column, value);        }        let nothing = Arc::new(nothing);        self.nothing.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(table.store.clone(), Arc::clone(&nothing));        Ok(nothing)    }    /// One object row as the receipt this file folds.    /// The ops `rows` (as `/v1/sync` carries them, opened) fold as, minted as a pull mints them    /// ([`Self::op_of`]): for Cotton Dev's invented copy (`developer.inventServedCopy`), never a pass.    pub fn served_ops(&self, rows: &[Value], workspace_id: &str) -> Result<Vec<CottonOp>, String> {        let file = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)            .map_err(|error| format!("this phone's copy could not be read ({error})"))?;        let mut ops = Vec::new();        for row in rows {            if let Some(op) = self.op_of(row, workspace_id, &file)? {                ops.push(op);            }        }        Ok(ops)    }    /// The retracts of every row this copy holds of each table `dropped` names    /// (`{ <table>: <moment it was erased> }`), each stamped at that moment: a    /// table this copy places nowhere holds nothing to drop.    fn dropped(&self, dropped: &Value, workspace_id: &str, file: &rusqlite::Connection) -> Result<Vec<CottonOp>, String> {        let Some(dropped) = dropped.as_object() else { return Ok(Vec::new()) };        let map = self.map();        let mut ops = Vec::new();        for (name, at) in dropped {            let (Some(table), Some(at)) = (map.object(name), at.as_str()) else { continue };            let held = format!("SELECT \"{}\" FROM \"{}\"", table.key_column.replace('"', ""), table.store.replace('"', ""));            let ids: Vec<String> = match file.prepare(&held) {                Ok(mut statement) => statement                    .query_map([], |row| row.get::<_, String>(0))                    .and_then(|rows| rows.collect::<Result<Vec<_>, _>>())                    .map_err(|error| format!("this phone's copy could not be read ({error})"))?,                // A table this copy has not made yet holds nothing.                Err(_) => continue,            };            if !ids.is_empty() {                eprintln!("[object] {name} was erased on the object: {} rows this copy held go", ids.len());            }            for id in ids {                let row = json!({"table": name, "id": id, "version": 0, "deleted": true, "data": {}, "updated_at": at});                if let Some(op) = self.op_of(&row, workspace_id, file)? {                    ops.push(op);                }            }        }        Ok(ops)    }    fn op_of(&self, row: &Value, workspace_id: &str, file: &rusqlite::Connection) -> Result<Option<CottonOp>, String> {        let (Some(name), Some(id)) = (row["table"].as_str(), row["id"].as_str()) else { return Ok(None) };        let map = self.map();        let Some(table) = map.object(name) else { return Ok(None) };        // The object's delete of a row this copy holds in its own Bin is how that Bin reached it ([`row_binned`]):        // folded back, it took the row out of the Bin, so Put back and Empty found nothing (CINEMAS DEV PROOF,        // 26 Nov 2026). The row stays in the Bin here; only an erase ends it.        if row["deleted"] == json!(true) && row["data"].get(ERASED_KEY).is_none() && row_binned(file, table, id)? {            return Ok(None);        }        let version = row["version"].as_i64().unwrap_or(0);        let updated = row["updated_at"].as_str().or_else(|| row["created_at"].as_str()).unwrap_or_default();        let ms = cotton_store::protocol::js::parse_date_ms(updated).unwrap_or(0).clamp(0, cotton_store::protocol::hlc::MAX_MS);        let stamp = format!("{ms:013}:{:04}:{OBJECT_AUTHOR}", version.rem_euclid(10_000));        // The served columns this row carries are part of what the receipt        // says: the same version pulled again by a copy that now keeps one        // more of them is another write, and folds.        let mut carried: Vec<&str> = Vec::new();        // The columns given their default for the object's nothing: a row an        // earlier minting named null there is another write now ([`MINTING`]).        let mut defaulted: Vec<String> = Vec::new();        let served = if row["deleted"] == json!(true) {            // An erased row's tombstone says why (`$erase`): this copy ends it for good too, its receipts and            // history with it, as the device that erased it did (CONTRACT.md "WhatsApp through the Mac").            match row["data"].get(ERASED_KEY).and_then(Value::as_str).filter(|reason| !reason.is_empty()) {                Some(reason) => ServedRow::Erased(reason.to_string()),                None => ServedRow::Retracted,            }        } else {            let mut fields = BTreeMap::new();            let data = row["data"].as_object().cloned().unwrap_or_default();            let nothing = self.nothing_in(table)?;            for (object, ours, codec) in &table.columns {                // The object holds nothing in a column it was never written                // (a create that named fewer keys) or one written null, and                // reads the two alike. Here, a column that cannot hold null                // holds its declared default for nothing.                let value = match (data.get(object).filter(|value| !value.is_null()), nothing.get(ours)) {                    (None, Some(default)) => {                        defaulted.push(format!("={ours}"));                        default.clone()                    }                    (value, _) => as_held(*codec, &table.laid(ours, value.unwrap_or(&Value::Null))),                };                fields.insert(ours.clone(), value);            }            // A column kept for the object's definition is written when the            // row carries it: a row that says nothing of it leaves it as it is.            for column in table.served.iter().filter(|column| data.contains_key(&column.name)) {                fields.insert(column.name.clone(), as_held(column.codec, &data[&column.name]));                carried.push(column.name.as_str());            }            if table.workspace && table.key_column != "workspace_id" {                fields.insert("workspace_id".into(), json!(workspace_id));            }            for (column, held) in [("created_at", table.created_at), ("updated_at", table.updated_at), ("landed_at", table.landed_at)] {                // A table that declares the column (a passkey's MADE) keeps                // the row's own value: the frame's is when the object took it.                let declared = table.columns.iter().any(|(object, ours, _)| ours == column && data.get(object).is_some_and(|value| !value.is_null()));                if declared {                    continue;                }                if let Some(at) = row[column].as_str().filter(|_| held) {                    fields.insert(column.into(), as_held(Codec::Timestamp, &json!(at)));                }            }            ServedRow::Live(fields)        };        // A one-row settings table is keyed by the database it belongs to.        let row_id = if table.key_column == "workspace_id" { workspace_id } else { id };        let named: Vec<&str> = carried.iter().copied().chain(defaulted.iter().map(String::as_str)).collect();        let op_id = op_id_of(ms, name, id, version, &named);        // The receipt of this version the copy holds already, when it kept        // fewer of the row's columns then: this one says all of it and more,        // and stands for it (one receipt per row and stamp).        let replaces = if named.is_empty() {            None        } else {            file.query_row("SELECT op_id FROM _writes WHERE tbl = ?1 AND row_id = ?2 AND hlc = ?3", [table.store.as_str(), row_id, stamp.as_str()], |held| held.get::<_, String>(0))                .map(Some)                .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(None) } else { Err(format!("this phone's copy could not be read ({error})")) })?                .filter(|held| *held != op_id)        };        cotton_store::mint::served(op_id, &table.store, row_id, &stamp, &object_actor(), served, replaces.as_deref()).map(Some).map_err(|error| error.to_string())    }}/// A served value as the receipt carries it: in its column's canonical form,/// or — a value the column cannot hold (a list where it keeps text) — as the/// object sent it, so the fold refuses that one row and parks it with its/// sentence, as it parks a row its table refuses, and the page goes on. A/// row this copy cannot read never stops the pass (dev Worker, 29 Oct 2026:/// one seeded mood held a fresh phone at version 0 for good).fn as_held(codec: Codec, value: &Value) -> Value {    canonical::after_codec(codec, value).unwrap_or_else(|_| value.clone())}/// The fact of [`OBJECT_AUTHOR`], as a copy folds the first fact of any/// author: it names itself, so it never waits, and its stream begins before/// any row the object stamps.fn object_author_fact(workspace_id: &str) -> Result<CottonOp, String> {    let stamp = format!("{:013}:0000:{OBJECT_AUTHOR}", 0);    let mut fields = BTreeMap::new();    fields.insert("workspace_id".into(), json!(workspace_id));    fields.insert("device_id".into(), json!(OBJECT_AUTHOR));    fields.insert("device_name".into(), Value::Null);    fields.insert("minted_at".into(), json!("1970-01-01T00:00:00.000Z"));    fields.insert("reason".into(), json!("first"));    fields.insert("first_stamp".into(), json!(stamp));    cotton_store::mint::served(op_id_of(0, "author", OBJECT_AUTHOR, 0, &[]), "cotton_authors", OBJECT_AUTHOR, &stamp, &object_actor(), ServedRow::Live(fields), None)        .map_err(|error| error.to_string())}/// The row an op names, as this file holds it now, in the object's columns and/// shapes: JSON parsed, a flag a boolean./// The row the object said `store`'s row `id` links to and does not hold (`bad_link`, "email.thread_id names no/// email_thread"), when this copy holds it and still has a write of it queued: its table here and its id. `None` for/// any other refusal, and for a link to a row this copy never meant to send.fn queued_link(file: &rusqlite::Connection, map: &ObjectTables, store: &str, id: &str, refusal: &ObjectRefusal) -> Result<Option<(String, String)>, String> {    if refusal.code != "bad_link" {        return Ok(None);    }    let Some((column, parent)) = refusal.message.split_once(" names no ").and_then(|(named, parent)| Some((named.split_once('.')?.1.trim(), parent.trim()))) else { return Ok(None) };    let (Some(child), Some(parent)) = (map.ours(store), map.object(parent)) else { return Ok(None) };    let Some(row) = row_now(file, child, id)? else { return Ok(None) };    let Some(target) = row.get(column).and_then(Value::as_str).filter(|target| !target.is_empty()) else { return Ok(None) };    let queued = file        .query_row("SELECT 1 FROM _outbox WHERE tbl = ?1 AND row_id = ?2 LIMIT 1", [parent.store.as_str(), target], |_| Ok(()))        .map(|()| true)        .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(false) } else { Err(error.to_string()) })?;    Ok(queued.then(|| (parent.store.clone(), target.to_string())))}/// What an erased row's tombstone holds on the object, and nothing else: why it was erased.pub const ERASED_KEY: &str = "$erase";/// The `delete` act a retract goes up as; an erase names why (`erase`), so the object ends the row for good/// too and its log keeps nothing the row held (CONTRACT.md "WhatsApp through the Mac").fn delete_args(table: &str, id: &str, erase: Option<&str>) -> Value {    let mut args = json!({ "table": table, "id": id });    if let Some(reason) = erase.filter(|reason| !reason.is_empty()) {        args["erase"] = json!(reason);    }    args}#[cfg(test)]#[test]fn an_erase_goes_up_saying_why_and_a_retract_does_not() {    assert_eq!(delete_args("cotton_msg_messages", "m-1", Some("disappeared")), json!({ "table": "cotton_msg_messages", "id": "m-1", "erase": "disappeared" }));    assert_eq!(delete_args("cotton_notes", "n-1", None), json!({ "table": "cotton_notes", "id": "n-1" }));}/// What the object holds of one row ([`ObjectTransport::object_row`]).enum ObjectRow {    /// Live, opened: its version and its columns.    Opened(i64, Map<String, Value>),    /// No live row there.    Absent,    /// A row there this copy cannot open (another key), or one with no version.    Unopened,}/// Whether this phone made the row and nothing of it has come from the object since: its birth (`_born`, the hlc of/// its first receipt) is a device's of this copy, never the object's (a pulled row is born `<ms>:<version>:object`,/// `op_of`), and no receipt of it this copy keeps (`_writes`) is the object's. A row another device changed (resealed/// it under a key this phone lacks, say) has come back through the object, so it is no longer only this phone's/// (HIDDEN 8, review 7).fn born_here(file: &rusqlite::Connection, table: &StoredTable, id: &str) -> Result<bool, String> {    let born: Option<String> = file        .query_row(&format!("SELECT _born FROM \"{}\" WHERE \"{}\" = ?1", table.store, table.key_column), [id], |row| row.get(0))        .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(None) } else { Err(error.to_string()) })?;    let object_stamp = format!(":{OBJECT_AUTHOR}");    if !born.is_some_and(|born| !born.is_empty() && !born.ends_with(&object_stamp)) {        return Ok(false);    }    let seen: i64 = file        .query_row("SELECT count(*) FROM _writes WHERE tbl = ?1 AND row_id = ?2 AND substr(hlc, -length(?3)) = ?3", rusqlite::params![table.store, id, object_stamp], |row| row.get(0))        .map_err(|error| error.to_string())?;    Ok(seen == 0)}fn row_now(file: &rusqlite::Connection, table: &StoredTable, id: &str) -> Result<Option<Map<String, Value>>, String> {    // The storage map's columns, then the served ones the person writes that this copy holds.    let mut sent: Vec<(String, String, Codec)> = table.columns.clone();    if !table.written.is_empty() {        let held = file_columns(file, &table.store)?;        for column in table.served.iter().filter(|column| table.written.contains(&column.name) && held.contains(&column.name)) {            sent.push((column.name.clone(), column.name.clone(), column.codec));        }    }    if sent.is_empty() {        return Ok(Some(Map::new()));    }    let columns: Vec<String> = sent.iter().map(|(_, ours, _)| format!("\"{ours}\"")).collect();    let sql = format!("SELECT {} FROM \"{}\" WHERE \"{}\" = ?1", columns.join(", "), table.store, table.key_column);    let values: Option<Vec<SqlValue>> = file        .query_row(&sql, [id], |row| (0..sent.len()).map(|i| row.get::<_, SqlValue>(i)).collect())        .map(Some)        .or_else(|error| if matches!(error, rusqlite::Error::QueryReturnedNoRows) { Ok(None) } else { Err(error) })        .map_err(|error| format!("{} {id} could not be read ({error})", table.store))?;    let Some(values) = values else { return Ok(None) };    let mut out = Map::new();    for ((object, ours, codec), value) in sent.iter().zip(values) {        out.insert(object.clone(), table.sent(ours, decode_value(*codec, &value).map_err(|error| error.to_string())?));    }    Ok(Some(out))}/// The columns `of_row` (one row's ops, oldest first) name, under the object's/// keys, each as the latest of them said it: the receipt's word and not the/// copy's, since a pull that landed while the change waited may have laid the/// object's older value over it here. A key of a per-key JSON column sends its/// whole column as the copy holds it. The row's own address and times are the/// object's, and a column the object does not keep goes nowhere.fn own_columns(table: &StoredTable, row: &Map<String, Value>, of_row: &[&CottonOp]) -> Result<Map<String, Value>, String> {    let mut own = Map::new();    for op in of_row {        let receipt = canonical::decode(op.receipt.as_bytes()).map_err(|error| error.to_string())?;        if receipt.kind == Kind::Retract {            continue;        }        for (field, said) in &receipt.fields {            if matches!(field.as_str(), "id" | "workspace_id" | "created_at" | "updated_at") {                continue;            }            let (named, per_key) = field.split_once('.').map_or((field.as_str(), false), |(column, _)| (column, true));            let kept = table.columns.iter().find(|(_, ours, _)| ours == named).map(|(object, ours, codec)| (object.clone(), ours.clone(), *codec));            let written = || table.served.iter().find(|column| column.name == named && table.written.contains(&column.name)).map(|column| (column.name.clone(), column.name.clone(), column.codec));            let Some((object, ours, codec)) = kept.or_else(written) else { continue };            if per_key {                if let Some(value) = row.get(&object) {                    own.insert(object, value.clone());                }                continue;            }            let stored = match said {                Value::Null => SqlValue::Null,                Value::Number(number) => number.as_i64().map_or_else(|| SqlValue::Real(number.as_f64().unwrap_or_default()), SqlValue::Integer),                Value::String(text) => SqlValue::Text(text.clone()),                other => SqlValue::Text(other.to_string()),            };            own.insert(object, table.sent(&ours, decode_value(codec, &stored).map_err(|error| error.to_string())?));        }    }    Ok(own)}/// Whether the copy holds this row in its bin: a kit table's delete sets the/// row's `deleted_at` here (`delete_now`), and the object's own delete is the/// act that says so — an update would send the row back live (claude-books-gaps/// walk, 5 Nov 2026: a highlight removed before sign-in came back on the Worker)./// A table whose map carries `deleted_at` keeps its bin at the object too: the/// update sends the mark, and the object's delete would leave a tombstone no/// undo takes back (list-acts walk, 7 Nov 2026: a removed list's Undo found/// nothing once the pull folded the tombstone).fn row_binned(file: &rusqlite::Connection, table: &StoredTable, id: &str) -> Result<bool, String> {    if table.columns.iter().any(|(_, ours, _)| ours == "deleted_at") {        return Ok(false);    }    if !file_columns(file, &table.store)?.iter().any(|column| column == "deleted_at") {        return Ok(false);    }    let sql = format!("SELECT \"deleted_at\" IS NOT NULL FROM \"{}\" WHERE \"{}\" = ?1", table.store, table.key_column);    file.query_row(&sql, [id], |row| row.get::<_, bool>(0))        .or_else(|error| if matches!(error, rusqlite::Error::QueryReturnedNoRows) { Ok(false) } else { Err(error) })        .map_err(|error| format!("{} {id} could not be read ({error})", table.store))}/// Whether these ops take the row out of this copy's own bin: a `deleted_at` set back to nothing on a table whose bin/// lives here only (the object deleted the row when it went in, [`row_binned`]).fn unbins(file: &rusqlite::Connection, table: &StoredTable, of_row: &[&CottonOp]) -> Result<bool, String> {    if table.columns.iter().any(|(_, ours, _)| ours == "deleted_at") || !file_columns(file, &table.store)?.iter().any(|column| column == "deleted_at") {        return Ok(false);    }    for op in of_row {        let receipt = canonical::decode(op.receipt.as_bytes()).map_err(|error| error.to_string())?;        if receipt.kind == Kind::Change && receipt.fields.iter().any(|(field, said)| field.as_str() == "deleted_at" && said.is_null()) {            return Ok(true);        }    }    Ok(false)}/// The columns `table` has in this copy.fn file_columns(file: &rusqlite::Connection, table: &str) -> Result<Vec<String>, String> {    let mut statement = file.prepare("SELECT name FROM pragma_table_info(?1)").map_err(|error| error.to_string())?;    let names = statement.query_map([table], |row| row.get::<_, String>(0)).map_err(|error| error.to_string())?;    names.collect::<Result<Vec<_>, _>>().map_err(|error| error.to_string())}/// `v<version>` and, between pages, `.<page ordinal>.<page token>`; after/// the copy has pulled again from the start, `w<pulls>` before the `v`.////// The ordinal is what makes the cursor move FORWARDS as text: the file's/// cursors only ever advance (`cotton_store::cursors::advance_cursor` compares/// the strings), and the object's page token is opaque, so without the/// ordinal a later page whose token happened to sort below the one before it/// was refused, and the phone pulled that page again for ever. The pulls do/// the same for a pass that begins again from nothing.fn read_cursor(held: &str) -> (u32, i64, Option<(u32, &str)>) {    let (pulls, rest) = match held.strip_prefix('w').and_then(|rest| rest.split_once('v')) {        Some((pulls, rest)) => (pulls.parse().unwrap_or(0), rest),        None => (0, held.strip_prefix('v').unwrap_or("")),    };    let (version, page) = match rest.split_once('.') {        Some((version, page)) => {            let page = page.split_once('.').and_then(|(ordinal, mark)| Some((ordinal.parse().ok()?, mark))).filter(|(_, mark)| !mark.is_empty());            (version, page)        }        None => (rest, None),    };    (pulls, version.parse().unwrap_or(0), page)}/// Whether a copy holding `cursors` is still on its first pull from the/// object (launch-fast, 20 Nov 2026): no pass has ended on it yet, so its/// rows are on their way, never "nothing here". A copy pulling again from/// the start in place (`w<pulls>`) already holds its rows and is not.pub fn first_pull_underway(cursors: &BTreeMap<String, String>) -> bool {    match cursors.get(CURSOR_KEY).map(String::as_str).filter(|held| !held.is_empty()) {        None => true,        Some(held) => {            let (pulls, since, page) = read_cursor(held);            pulls == 0 && since == 0 && page.is_some()        }    }}/// The cursor a pass ends on: `v<version>`, after `w<pulls>` once the copy/// has pulled again from the start./// A first page asking `again`'s tables whole beside the rest since its version.fn with_again(mut path: String, again: &[String]) -> String {    if !again.is_empty() {        path.push_str("&again=");        path.push_str(&again.join(","));    }    path}/// The tables a copy's first fill left for the pass after it and is still owed (FIRST SYNC STATES, 26 Nov 2026: Post/// said "No mail here yet" and "0 mails" while 280,000 mail rows, a late table, were still coming after the first/// pull had ended). `None` once no first fill owes anything: every table this copy keeps has come whole at least once./// Read off the record of tables gone past ([`PASSED_KEY`]), which keeps the first fill's mark until a pass has/// carried what it left.pub fn first_fill_owes(db: &cotton_store::driver::Driver) -> Result<Option<Vec<String>>, String> {    let held = db        .get("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(PASSED_KEY.to_string())])        .map_err(|error| error.to_string())?        .and_then(|row| row.text("hlc_seen").map(str::to_string));    Ok(held        .as_deref()        .and_then(Passed::read)        .filter(|passed| passed.tables.contains(FIRST_FILL_MARK))        .map(|passed| passed.tables.into_iter().filter(|table| table != FIRST_FILL_MARK).map(|table| table.split('.').next().unwrap_or_default().to_string()).collect::<std::collections::BTreeSet<_>>().into_iter().collect()))}/// A sync page asked ahead ([`ObjectTransport::ask_ahead`]): which copy and page it is, and its answer once it comes./// One for the process: each pass makes its own transport, and the page its last one asked ahead is the next pass's/// first.struct Ahead {    key: String,    answer: std::sync::mpsc::Receiver<Result<(Value, usize), ObjectRefusal>>,}static AHEAD: Mutex<Option<Ahead>> = Mutex::new(None);/// One sync page, asked now.fn ask_page_at(address: &ObjectAddress, exchange: &dyn Exchange, credential: &str, path: &str) -> Result<(Value, usize), ObjectRefusal> {    let (status, bytes) = address.send_bytes(exchange, "GET", path, bearer(credential), None)?;    Ok((answer_of(status, &bytes)?, bytes.len()))}/// Whether this run asks pages as before FIRST SYNC FAST, one at a time and not gzipped (`COTTON_SYNC_PLAIN`): the/// measure's own A/B, in one build. Never on a phone.pub fn sync_plain() -> bool {    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();    *ON.get_or_init(|| std::env::var_os("COTTON_SYNC_PLAIN").is_some())}/// How often a long pull checkpoints its copy, in pages (`hold_checkpoints`).pub const CHECKPOINT_EVERY_PAGES: u32 = 10;/// A checkpoint is running on its own connection.static CHECKPOINTING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// How often a long pull says this device's state on its row: every this many pages (FIRST SYNC FAST).pub const REPORT_EVERY_PAGES: u32 = 10;/// Whether this run prints each page's timings (`COTTON_SYNC_TIMES`, FIRST SYNC FAST's measures): never on a phone.pub fn sync_times() -> bool {    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();    *ON.get_or_init(|| std::env::var_os("COTTON_SYNC_TIMES").is_some())}/// Owe the tables of `gained` whole on the copy at `path`'s next pass, beside/// what its record owes already, and nothing else: a kit that gained a table/// pulls that table again, never the whole object. `Ok(false)` when the copy/// holds no record this build reads, and owes a pull from the start.pub fn owe_whole(path: &Path, gained: &[String]) -> Result<bool, String> {    let db = cotton_store::driver::Driver::open(path).map_err(|error| format!("this phone's copy could not be opened ({error})"))?;    owe_whole_on(&db, gained)}fn owe_whole_on(db: &cotton_store::driver::Driver, gained: &[String]) -> Result<bool, String> {    let held = db        .get("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(PASSED_KEY.to_string())])        .map_err(|error| error.to_string())?        .and_then(|row| row.text("hlc_seen").map(str::to_string));    let Some(mut passed) = held.as_deref().and_then(Passed::read).filter(|passed| passed.minting >= MINTING && !passed.tables.contains(FIRST_FILL_MARK)) else { return Ok(false) };    passed.tables.extend(gained.iter().cloned());    passed.changes += 1;    db.run("UPDATE _cursors SET hlc_seen = ? WHERE author_device_id = ?", &[rusqlite::types::Value::Text(passed.text()), rusqlite::types::Value::Text(PASSED_KEY.to_string())])        .map_err(|error| error.to_string())?;    Ok(true)}fn version_cursor(pulls: u32, version: i64) -> String {    match pulls {        0 => format!("v{version:016}"),        pulls => format!("w{pulls:04}v{version:016}"),    }}/// The cursor held between pages: the pass's own `since` as/// [`version_cursor`] says it, then `.<ordinal>.<token>`, the ordinal one/// past the page just folded.fn page_cursor(pulls: u32, since: i64, ordinal: u32, mark: &str) -> String {    format!("{}.{ordinal:08}.{mark}", version_cursor(pulls, since))}/// What one pull answers.struct Pulled {    ops: Vec<CottonOp>,    cursor: String,    more: bool,    server_time: Option<String>,    /// The [`PASSED_KEY`] record to hold with the cursor.    passed: String,    /// The [`FEATURES_KEY`] text to hold with it, when the page said the object's clock.    features: Option<String>,    /// The fill waits for the room guard ([`ObjectTransport::stopping_for`]): nothing was asked, and the cursor stands.    stopped: bool,}/// The object tables whose rows a copy's cursor went past without keeping/// them ([`PASSED_KEY`]), since its `pulls`th pull from the start; `changes`/// counts how often the set grew within that pull, and `minting` is the/// [`MINTING`] that pull from the start was made under.#[derive(Debug, Clone, PartialEq, Eq)]struct Passed {    pulls: u32,    changes: u32,    minting: u32,    tables: std::collections::BTreeSet<String>,}impl Passed {    fn read(text: &str) -> Option<Passed> {        let (head, names) = text.strip_prefix('h')?.split_once(':')?;        let (pulls, rest) = head.split_once('.')?;        let (changes, minting) = match rest.split_once(".m") {            Some((changes, minting)) => (changes, minting.parse().ok()?),            None => (rest, 0),        };        let tables = names.split(',').filter(|name| !name.is_empty()).map(str::to_string).collect();        Some(Passed { pulls: pulls.parse().ok()?, changes: changes.parse().ok()?, minting, tables })    }    fn text(&self) -> String {        let names: Vec<&str> = self.tables.iter().map(String::as_str).collect();        match self.minting {            0 => format!("h{:04}.{:06}:{}", self.pulls, self.changes, names.join(",")),            minting => format!("h{:04}.{:06}.m{minting:02}:{}", self.pulls, self.changes, names.join(",")),        }    }    /// Whether a copy at `pulls` owes a pull: the record is another pull's or    /// an earlier minting's, or a first fill's ([`FIRST_FILL_MARK`]: the    /// tables it left, [`Self::owed_tables`]), or `map` places a table whose    /// rows it went past, or a key of a table's rows it kept no column for.    fn owed(&self, pulls: u32, map: &ObjectTables) -> bool {        self.pulls != pulls            || self.minting < MINTING            || self.tables.contains(FIRST_FILL_MARK)            || self.tables.iter().any(|passed| match passed.split_once('.') {                Some((table, key)) => map.object(table).is_some_and(|table| table.places(key)),                None => map.object(passed).is_some(),            })    }    /// The tables a copy at `pulls` owes whole, when that is all it owes: the    /// record is this pull's and this minting's (a first fill's too: it owes    /// the tables it left, [`FIRST_FILL_MARK`]), and    /// `map` now places tables (or keys of tables) it went past. Those tables    /// alone come again (`again=`, the Worker's `sync`), the rest since the    /// cursor: an update that keeps a table or a column more never pulls the    /// whole object again. `None` when it owes a pull from the start, or nothing.    fn owed_tables(&self, pulls: u32, map: &ObjectTables) -> Option<Vec<String>> {        if self.pulls != pulls || self.minting < MINTING {            return None;        }        // A first fill left its tables whether or not the map places them: the shell's own (settings, the device        // rows, the bin) fold by their own paths, and come whole with the rest it left.        let filled = self.tables.contains(FIRST_FILL_MARK);        let tables: std::collections::BTreeSet<String> = self            .tables            .iter()            .filter(|passed| passed.as_str() != FIRST_FILL_MARK)            .filter_map(|passed| match passed.split_once('.') {                Some((table, key)) => map.object(table).is_some_and(|placed| placed.places(key)).then(|| table.to_string()),                None => (filled || map.object(passed).is_some()).then(|| passed.clone()),            })            .collect();        (!tables.is_empty()).then(|| tables.into_iter().collect())    }    /// This record less what names a table of `again`, which a pass carried whole.    fn without(mut self, again: &[String]) -> Passed {        let before = self.tables.len();        self.tables.retain(|passed| !again.iter().any(|table| passed == table || passed.strip_prefix(table.as_str()).is_some_and(|rest| rest.starts_with('.'))));        // A first fill's mark goes with the tables it left: once a pass has carried them, the copy owes nothing of        // the fill, and a later build's gained tables are owed whole beside it ([`owe_whole`]).        if !again.is_empty() {            self.tables.retain(|passed| passed != FIRST_FILL_MARK);        }        // The text only moves forward (the cursors' rule): a record that let tables go counts a change.        if self.tables.len() != before {            self.changes += 1;        }        self    }    /// The record a page of the `pulls`th pull leaves: `before` (that pull's,    /// when there is one) with the tables it `went_past`, its count of    /// changes one more when a set already named grew.    fn after(before: Option<Passed>, pulls: u32, went_past: Vec<String>) -> Passed {        let mut passed = before.unwrap_or(Passed { pulls, changes: 0, minting: MINTING, tables: Default::default() });        let grown: Vec<String> = went_past.into_iter().filter(|table| !passed.tables.contains(table)).collect();        if !grown.is_empty() && !passed.tables.is_empty() {            passed.changes += 1;        }        passed.tables.extend(grown);        passed    }}/// A ULID-shaped op id for one version of one row: the same row at the same/// version is the same op, wherever and however often it is pulled — unless/// the copy now keeps more of it: `served`, the columns kept for the object's/// definition that the row carries (in the definition's order), make another/// op of it, so a copy that gained a column takes its value on the rows it/// already held; and so do the columns given their default for the object's/// nothing (`=` and the column), which an earlier minting named null.fn op_id_of(ms: i64, table: &str, id: &str, version: i64, served: &[&str]) -> String {    use sha2::{Digest, Sha256};    let mut named = format!("{table}\u{0}{id}\u{0}{version}");    for column in served {        named.push('\u{0}');        named.push_str(column);    }    let digest = Sha256::digest(named.as_bytes());    let mut randomness = [0u8; 16];    randomness.copy_from_slice(&digest[..16]);    cotton_store::protocol::ulid::new_ulid(ms, &randomness).unwrap_or_else(|_| format!("{ms:013}{}", hex(&digest[..8])))}fn hex(bytes: &[u8]) -> String {    bytes.iter().map(|b| format!("{b:02x}")).collect()}impl SyncTransport for ObjectTransport {    fn exchange(&mut self, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {        if let Some(said) = self.signed_out.as_ref().and_then(|signed_out| signed_out.said()) {            return Err(said.message);        }        // A pass that fails says why on this phone's row first: the row is        // the one place a phone's failure can be read from off the phone        // (owner's phone, 2 Nov 2026: the same page asked every 30 s and        // nothing anywhere said why). The write never fails the pass.        self.pass(request).inspect_err(|why| self.troubled(request, why))    }}impl ObjectTransport {    /// One exchange: this phone's writes up, then a page down.    fn pass(&self, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {        // A table the copy's definitions define as data is placed before        // anything is posted or read: its writes go to the object and its rows        // come down.        // The generation the copy holds, as the pass read its cursors (RESTORE 2).        let holds_generation = request.cursors.get(GENERATION_KEY).and_then(|text| generation_of(text));        if holds_generation.is_some() {            *self.generation.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(holds_generation.clone());        }        self.frozen.store(false, std::sync::atomic::Ordering::SeqCst);        let held = self.copy_definitions()?;        self.place(held.iter())?;        self.learn_kept_keys()?;        let (applied_rows, rejected) = self.push(&request.ops)?;        let Pulled { ops, cursor, more: has_more, server_time, passed, features, stopped } = self.pull(request)?;        // The pull reached the object's end: every seal key it holds is read.        if !has_more && !stopped {            self.caught_up.store(true, std::sync::atomic::Ordering::SeqCst);            if let Some(sealer) = &self.sealer {                sealer.learned_all();            }        }        // Every open row of a sealed table that earlier pulls folded into this copy is sealed after this phone's own        // writes have gone, and only once the pull has reached the object's end: the pull never waits behind the        // sweep, and a bounded share is sealed each pass (SYNC STUCK, 25 Nov 2026).        if !has_more && !stopped {            self.sweep()?;        }        // Every author whose writes reached the object is one it has seen to        // the end, and so is the object itself and the file's origin. Kept in        // the file's own cursors, so the next pass, and the next launch, does        // not hand any of them over again.        // A fill waiting for room holds its cursor and record as they stood: nothing is written over them.        let mut cursors = if stopped { BTreeMap::new() } else { BTreeMap::from([(CURSOR_KEY.to_string(), cursor), (PASSED_KEY.to_string(), passed)]) };        if let Some(features) = features {            cursors.insert(FEATURES_KEY.to_string(), features);        }        // The first generation a copy holding none was answered, kept with the cursor (RESTORE 2).        if holds_generation.is_none() {            if let Some(generation) = self.held_generation() {                cursors.insert(GENERATION_KEY.to_string(), format!("g{generation}"));            }        }        let mut seen = BTreeMap::new();        for author in request.cursors.keys().chain(request.ops.iter().map(|op| &op.device_id)) {            if author != CURSOR_KEY && author != PASSED_KEY && author != FEATURES_KEY && author != GENERATION_KEY {                seen.insert(author.clone(), SEEN_ALL.to_string());            }        }        for op in &request.ops {            cursors.insert(op.device_id.clone(), SEEN_ALL.to_string());        }        for author in [OBJECT_AUTHOR, cotton_store::changes::ORIGIN_AUTHOR] {            seen.insert(author.to_string(), SEEN_ALL.to_string());        }        // The rows a backup kept on this phone go up again on a launch's first pass, and after a pass that moved        // anything, when the row each names may have come.        let first = !self.kept_tried.swap(true, std::sync::atomic::Ordering::SeqCst);        if first || !ops.is_empty() || applied_rows.values().any(|n| *n > 0) {            self.post_kept_rows()?;        }        *self.last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = None;        if let Some(progress) = &self.progress {            progress.frozen(self.frozen.load(std::sync::atomic::Ordering::SeqCst));        }        Ok(ExchangeResponse {            wanted: Vec::new(),            workspace_id: request.workspace_id.clone(),            ops,            cursors,            has_more,            schema_version: Some(cotton_store::schema::ddl::SCHEMA_VERSION),            applied_rows,            rejected,            seen,            serving_epoch: None,            server_time,            restored: None,            copy_night: None,            behind_by: None,            owed_at_start: None,            owed_by_table: None,            passed: None,            wake_refusal: None,            copy: None,            answered_by: None,        })    }}impl RefusalAware for ObjectTransport {    fn lend_file(&mut self, file: Arc<dyn crate::sync::cycle::LendsFile + Send + Sync>) {        self.file = Some(file);    }    fn last_refusal(&self) -> Option<ServerRefusal> {        self.last.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    fn rests(&self) -> bool {        self.rest.swap(false, std::sync::atomic::Ordering::SeqCst)    }    fn folded(&self) {        // PHONE MEASURES: the fold just done is merging; what this does after it (opening the rows parked for the key)        // is opening; the copy level after it ends its first sync.        let fold_ms = self.pulled_at.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take().map(|at| at.elapsed().as_millis() as u64);        let opening = std::time::Instant::now();        self.fold_after();        let level = self.level_after_fold.swap(false, std::sync::atomic::Ordering::SeqCst);        crate::first_sync::add(&self.replica, |times| {            times.merging_ms += fold_ms.unwrap_or(0);            times.opening_ms += opening.elapsed().as_millis() as u64;            if level {                times.done_at_ms = Some(chrono::Utc::now().timestamp_millis());            }        });    }}impl ObjectTransport {    /// What [`SyncingTransport::folded`] does with the copy once a page is folded.    fn fold_after(&self) {        let opened: Vec<_> = std::mem::take(&mut *self.unparks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()));        let caught_up = self.caught_up.swap(false, std::sync::atomic::Ordering::SeqCst);        if self.sealer.is_none() {            return;        }        let Ok(file) = rusqlite::Connection::open_with_flags(&self.replica, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX) else { return };        let map = self.map();        let store_of = |name: &str| map.object(name).map(|table| table.store.clone());        let mut notes = Vec::new();        // FIRST SYNC 6 (the coordinator, 26 Nov 2026): rows waiting for a parent are not opened every pass; they go        // back to the batches once a row of a parent table has folded since they waited, or once a pull reaches the        // object's end.        // A parent table that gained a row wakes its waiting rows ahead of the tried. A pull that reaches the end        // wakes the rest at most once a day, BEHIND every tried row (FIRST SYNC 6 REVIEW (2): in steady state every        // pull reaches the end, and 2,000 orphans woken ahead each pass starved every other tried park).        let marks = crate::seal::waiting_marks(&file).unwrap_or_default();        for (table, mark) in &marks {            let now = store_of(table).and_then(|store| crate::seal::parent_mark(&file, &store).ok());            if let Some(woken_at) = crate::seal::wake_mark(now, *mark) {                notes.push(crate::seal::Note::Wake { table: Some(table.clone()), at_ms: 0, mark: woken_at });            }        }        if caught_up && !marks.is_empty() {            let now_ms = chrono::Utc::now().timestamp_millis();            let last = crate::seal::woken_at_end(&file).unwrap_or(None);            if crate::seal::wake_at_end_due(last, now_ms) {                notes.push(crate::seal::Note::Wake { table: None, at_ms: now_ms, mark: 0 });            }        }        // Only a row that stands lets its park go: a fold can land while it refuses one row (a rule of the copy's        // that row breaks), and that row keeps its park, to be opened again on the next pass. A row that folded        // DORMANT (its owning parent, a mail's conversation, not in the copy yet: its receipt kept and no table row)        // waits for that parent, named so and never read as an error; its park stays until the row stands (FIRST        // SYNC 6). Any other row that does not stand was refused by the fold: its opening again on the next batch is        // no progress (FIRST SYNC 3 REVIEW).        for (table, id, version) in opened {            if self.stands_at(&table, &id, version, &file).unwrap_or(false) {                notes.push(crate::seal::Note::Unparked { table, id });                continue;            }            // Dormant only when a receipt of the row is kept AND an owning parent it names is absent (FIRST SYNC 6            // REVIEW (3)): a row whose parents are all here and still does not stand was refused.            let dormant = store_of(&table)                .filter(|store| crate::seal::has_owning_parent(store) && crate::seal::parent_absent(&file, store, &id).unwrap_or(false))                .and_then(|store| crate::seal::parent_mark(&file, &store).ok());            notes.push(match dormant {                Some(mark) => crate::seal::Note::Waiting { table, id, mark },                None => crate::seal::Note::Refused { table, id },            });        }        drop(file);        // Not kept now (the copy busy, say): the next pass finds these rows standing and lets their parks go.        let _ = self.keep_notes(&notes);    }}// ── the object's tables, tools and boards ───────────────────────────────────/// The `/v1/definitions` etag this copy's tables, tools and boards match, held for a/// launch across its passes (the loop makes a transport per pass). None at/// launch, so a launch's first page asks for the definitions whole.#[derive(Debug, Default)]pub struct HeldDefinitions {    etag: Mutex<Option<String>>,    /// Every table the object's last answer served, placed here or not: a    /// row of one this copy keeps nowhere (a sealed secret) asks nothing more.    served: Mutex<std::collections::BTreeSet<String>>,    /// Each served table's plural (`Sealed diaries`), placed here or not: a    /// sentence about a table this copy keeps nowhere still names it (the    /// unlock card asking for a table the owner made, on a Keys copy).    plurals: Mutex<std::collections::BTreeMap<String, String>>,    /// Every table the object's last answer served sealed, placed here or not (HANDING STUCK, 25 Nov 2026): a    /// grant is handed every sealed table's key by any app holding the data key, not only the tables its kit keeps    /// (Words keeps no session table, yet must hand the session tables' keys when the object seals them).    sealed: Mutex<std::collections::BTreeSet<String>>,    /// UNKNOWN FIELD (coordinator, 28 Nov 2026): each change the object refused as naming a field its definition lacks,    /// by op id, with the etag held when it was refused and the object's words. It is not posted again until the etag    /// moves (a deploy that brings the column moves the definitions); a launch posts it once more.    unknown_fields: Mutex<BTreeMap<String, (Option<String>, String)>>,}impl HeldDefinitions {    pub fn new() -> Arc<HeldDefinitions> {        Arc::new(HeldDefinitions::default())    }    /// The etag the copy matches, once a pass has seen it match.    pub fn etag(&self) -> Option<String> {        self.etag.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    /// Hold nothing: the copy was made again, and the next page asks for the    /// object's tables, tools and boards whole.    pub fn forget(&self) {        self.hold(None);        self.served.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();        self.plurals.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();        self.sealed.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();    }    fn hold(&self, etag: Option<String>) {        *self.etag.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = etag;    }    fn serve<'a>(&self, tables: impl Iterator<Item = &'a str>) {        *self.served.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = tables.map(str::to_string).collect();    }    /// Take each table's plural from the object's WHOLE answer, before a kit    /// copy keeps only its own (`kept_to`): a Keys copy's sentence about a    /// table the owner made still names it.    pub fn name<'a>(&self, tables: impl Iterator<Item = &'a Value>) {        let tables: Vec<&Value> = tables.collect();        *self.sealed.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) =            tables.iter().filter(|table| table.get("seal").is_some_and(Value::is_object)).filter_map(|table| table["id"].as_str().map(str::to_string)).collect();        *self.plurals.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = tables            .into_iter()            .filter_map(|table| Some((table["id"].as_str()?.to_string(), table["plural"].as_str().map(str::trim).filter(|plural| !plural.is_empty())?.to_string())))            .collect();    }    /// Every table the object's last answer served sealed, placed here or not, from its WHOLE answer.    pub fn sealed(&self) -> Vec<String> {        self.sealed.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).iter().cloned().collect()    }    /// The plural the object's last answer gave `table`, placed here or not.    pub fn plural(&self, table: &str) -> Option<String> {        self.plurals.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(table).cloned()    }    /// Whether the object's last answer served `table`.    fn serves(&self, table: &str) -> bool {        self.served.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).contains(table)    }    /// The object's words for change `op_id`, refused as naming an unknown field while the definitions stand as they    /// did then: it waits, unposted. None once they moved, or for a change never so refused.    fn waits_for_field(&self, op_id: &str) -> Option<String> {        let etag = self.etag();        let held = self.unknown_fields.lock().unwrap_or_else(|poisoned| poisoned.into_inner());        held.get(op_id).filter(|(at, _)| *at == etag).map(|(_, words)| words.clone())    }    /// Note that the object refused change `op_id` as naming an unknown field, under the etag held now.    fn refused_for_field(&self, op_id: &str, words: &str) {        let etag = self.etag();        self.unknown_fields.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(op_id.to_string(), (etag, words.to_string()));    }}/// The personal package's own tool (`kits/personal/kit.json`):/// the object's map of its tables, served beside the person's tools but no/// tool a phone draws — the import leaves the Mac's row of it behind too.pub const PACKAGE_TOOL: &str = "personal";/// One definitions table as the object's definitions fill it: the columns a/// served row writes beside `workspace_id`, `definition` and its times.struct ServedTable {    store: &'static str,    /// The object's word for one, for a sentence.    kind: &'static str,    /// Each column a served row writes, as a person's row holds it: never the    /// build's seed (`builtin`), so the build's own default does not draw over it.    columns: &'static [(&'static str, Codec, ServedValue)],}#[derive(Clone, Copy)]enum ServedValue {    False,    Null,}const SERVED_TABLES: ServedTable = ServedTable {    store: "cotton_table_definitions",    kind: "table",    columns: &[        ("builtin", Codec::Bool, ServedValue::False),        ("instructions_edited", Codec::Bool, ServedValue::False),        ("builtin_revision", Codec::Int, ServedValue::Null),        ("builtin_hash", Codec::Text, ServedValue::Null),        ("builtin_stamp", Codec::Int, ServedValue::Null),    ],};const SERVED_TOOLS: ServedTable = ServedTable {    store: "cotton_tool_definitions",    kind: "tool",    columns: &[("builtin", Codec::Bool, ServedValue::False), ("instructions_edited", Codec::Bool, ServedValue::False)],};const SERVED_THEMES: ServedTable = ServedTable {    store: "cotton_theme_definitions",    kind: "theme",    columns: &[("builtin", Codec::Bool, ServedValue::False)],};const SERVED_BOARDS: ServedTable = ServedTable {    store: "cotton_board_definitions",    kind: "board",    columns: &[        ("builtin", Codec::Bool, ServedValue::False),        ("builtin_revision", Codec::Int, ServedValue::Null),        ("builtin_hash", Codec::Text, ServedValue::Null),        ("builtin_stamp", Codec::Int, ServedValue::Null),    ],};/// The served tools this build draws, by id: the package's own left out, and/// any the phone's read of tools would refuse — one unreadable row there/// refuses every tool, so it is said and left on the object, never written.fn drawable_tools(tools: &Value) -> Vec<(String, Value)> {    let mut drawable = Vec::new();    for tool in tools.as_array().into_iter().flatten() {        let Some(id) = tool["id"].as_str().filter(|id| !id.is_empty()) else {            eprintln!("[object] a served tool names no id: left out of this phone's copy");            continue;        };        if id == PACKAGE_TOOL {            continue;        }        let read = cotton_core::definitions::ToolDefinition::from_json(&tool.to_string())            .and_then(|parsed| parsed.validate().map(|()| parsed))            .map_err(|error| error.to_string())            .and_then(|parsed| if parsed.id == id { Ok(()) } else { Err(format!("it names itself {:?}", parsed.id)) });        match read {            Ok(()) => drawable.push((id.to_string(), tool.clone())),            Err(why) => eprintln!("[object] the object's tool {id:?} is not one this build draws ({why}): left out of this phone's copy"),        }    }    drawable}/// The served tables this build draws, by id: any the phone's read of tables/// would refuse is said and left on the object, never written — and so is/// one at an id whose storage this build compiles under an engine, unless it/// names that engine: a built-in's schema is code, and a row naming none/// would make a second, empty table beside the one the object's rows fill./// A table with no face is written as any other: a link into it (a chat's/// contact, kept in `cotton_msg_contacts`) is titled by its definition, and a/// link into a table the copy has no definition of refuses the read.fn drawable_tables(tables: &Value) -> Vec<(String, Value)> {    let mut drawable = Vec::new();    for table in tables.as_array().into_iter().flatten() {        let Some(id) = table["id"].as_str().filter(|id| !id.is_empty()) else {            eprintln!("[object] a served table names no id: left out of this phone's copy");            continue;        };        let read = cotton_core::definitions::TableDefinition::from_json(&table.to_string())            .and_then(|parsed| parsed.validate().map(|()| parsed))            .map_err(|error| error.to_string())            .and_then(|parsed| if parsed.id == id { Ok(parsed) } else { Err(format!("it names itself {:?}", parsed.id)) })            .and_then(|parsed| match cotton_store::schema::package_tables::compiled_engine(id) {                Some(engine) if parsed.engine.as_deref() != Some(engine) => {                    Err(format!("this build keeps it under the {engine} engine and the object's names {:?}", parsed.engine))                }                _ => Ok(parsed),            });        match read {            Ok(_) => drawable.push((id.to_string(), table.clone())),            Err(why) => eprintln!("[object] the object's table {id:?} is not one this build draws ({why}): left out of this phone's copy"),        }    }    drawable}/// A definitions answer as an app on `kit` takes it: only the tools the kit/// names and the tables it keeps (its own and the shell's); the boards, the/// themes and the business stand. None is the whole answer: Cotton keeps the/// whole object, a tool the person made included (coordinator, 5 Nov 2026).pub fn kept_to(served: &Value, kit: Option<&cotton_core::kit::AppKit>) -> Value {    let Some(kit) = kit else { return served.clone() };    let mut kept = served.clone();    let keep = |key: &str, kept: &mut Value, keeps: &dyn Fn(&str) -> bool| {        if let Some(list) = kept[key].as_array_mut() {            list.retain(|definition| definition["id"].as_str().is_some_and(keeps));        }    };    keep("tools", &mut kept, &|id| kit.keeps_tool(id));    keep("tables", &mut kept, &|id| kit.keeps_table(id));    kept}/// What a copy is marked with beside it: the kit it was pulled for and that/// kit's tables ([`cotton_core::kit::AppKit::copy_mark`]). A copy with no mark/// was pulled for the whole object.pub const COPY_KIT_SUFFIX: &str = ".kit";/// The kit the copy at `path` was pulled for: `whole` when it says none.pub fn copy_kit(path: &Path) -> String {    std::fs::read_to_string(format!("{}{COPY_KIT_SUFFIX}", path.display())).map(|mark| mark.trim().to_string()).unwrap_or_else(|_| "whole".to_string())}/// Mark the copy at `path` as pulled for `kit`.pub fn mark_copy_kit(path: &Path, kit: Option<&cotton_core::kit::AppKit>) -> Result<(), String> {    // not a copy: the copy's kit mark beside it.    std::fs::write(format!("{}{COPY_KIT_SUFFIX}", path.display()), cotton_core::kit::AppKit::copy_mark(kit)).map_err(|error| format!("this phone's copy could not be marked with its kit ({error})"))}/// The served boards, by id, each as the object keeps it: a board stored as/// changes against the shipped one (Home) lands as those changes, and the/// board read lays them over this build's.fn served_boards(boards: &Value) -> Vec<(String, Value)> {    boards        .as_array()        .into_iter()        .flatten()        .filter_map(|board| board["id"].as_str().filter(|id| !id.is_empty()).map(|id| (id.to_string(), board.clone())))        .collect()}/// A definitions row as this copy holds it.struct HeldRow {    definition: Option<Value>,    builtin: bool,    created_at: Option<String>,    /// The row's newest stamp (`_hlc`): its time and its author.    stamp: String,}impl HeldRow {    /// The object wrote it last.    fn objects(&self) -> bool {        cotton_store::fold::author_of(&self.stamp) == Some(OBJECT_AUTHOR)    }}/// The receipts that make `table` in this copy what the object serves:/// a create of each served definition the copy does not hold as the object's/// with that content, and a retract of every held definition it no longer/// serves unless builtin (the build's shell), whoever wrote it. Compiled/// engine storage keeps its columns; only the drawn definition leaves. Each receipt is stamped after the row's/// newest, so it wins the fold whatever this phone's clock said when it wrote/// the row./// Each definition table's rows (by store) that hold a write this copy has/// still to send — queued, or held for the Mac's time, and not `taken` by/// the object in this pass: the copy's edit, which the object's answer does/// not replace or retract until it is sent. One the object took (or/// answered with its own, a conflict) is the object's to lay again.fn waiting_definitions(copy: &cotton_store::driver::Driver, taken: &std::collections::BTreeSet<String>) -> Result<BTreeMap<String, std::collections::BTreeSet<String>>, String> {    let mut waiting: BTreeMap<String, std::collections::BTreeSet<String>> = BTreeMap::new();    for (op, how) in crate::unsent::receipts(copy)? {        if how != crate::unsent::Waiting::Parked && DEFINITION_TABLES.contains(&op.table.as_str()) && !taken.contains(&op.op_id) {            waiting.entry(op.table.clone()).or_default().insert(op.row_id.clone());        }    }    Ok(waiting)}fn served_definitions(file: &rusqlite::Connection, table: &ServedTable, served: Vec<(String, Value)>, workspace_id: &str, at_ms: i64, waiting: &std::collections::BTreeSet<String>) -> Result<Vec<CottonOp>, String> {    let unreadable = |error: rusqlite::Error| format!("{} could not be read ({error})", table.store);    let mut held: BTreeMap<String, HeldRow> = BTreeMap::new();    let mut statement = file        .prepare(&format!("SELECT id, definition, builtin, created_at, _hlc FROM \"{}\" WHERE workspace_id = ?1", table.store))        .map_err(unreadable)?;    let rows = statement        .query_map([workspace_id], |row| {            Ok((                row.get::<_, String>(0)?,                HeldRow {                    definition: row.get::<_, Option<String>>(1)?.and_then(|text| serde_json::from_str(&text).ok()),                    builtin: row.get::<_, Option<i64>>(2)? == Some(1),                    created_at: row.get(3)?,                    stamp: row.get::<_, Option<String>>(4)?.unwrap_or_default(),                },            ))        })        .map_err(unreadable)?;    for row in rows {        let (id, row) = row.map_err(unreadable)?;        held.insert(id, row);    }    let after = |row: Option<&HeldRow>| row.and_then(|row| row.stamp.get(..13)).and_then(|ms| ms.parse::<i64>().ok()).map_or(at_ms, |newest| at_ms.max(newest + 1));    let iso = |ms: i64| chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let mut ops = Vec::new();    let mut serving = std::collections::BTreeSet::new();    for (id, definition) in served {        let row = held.get(&id);        if waiting.contains(&id) {            serving.insert(id);            continue;        }        if row.is_some_and(|row| row.objects() && !row.builtin && row.definition.as_ref() == Some(&definition)) {            serving.insert(id);            continue;        }        let codec = |codec: Codec, value: &Value| canonical::after_codec(codec, value).map_err(|error| format!("the object's {} {id}: {error}", table.kind));        let mut fields = BTreeMap::new();        fields.insert("workspace_id".to_string(), json!(workspace_id));        fields.insert("definition".to_string(), codec(Codec::Json, &definition)?);        for (column, column_codec, value) in table.columns {            let value = match value {                ServedValue::False => json!(false),                ServedValue::Null => Value::Null,            };            fields.insert((*column).to_string(), codec(*column_codec, &value)?);        }        let created = row.and_then(|row| row.created_at.clone()).unwrap_or_else(|| iso(at_ms));        fields.insert("created_at".to_string(), codec(Codec::Timestamp, &json!(created))?);        fields.insert("updated_at".to_string(), codec(Codec::Timestamp, &json!(iso(at_ms)))?);        ops.push(definition_op(table, &id, after(row), ServedRow::Live(fields))?);        serving.insert(id);    }    for (id, row) in &held {        if !row.builtin && !serving.contains(id) && !waiting.contains(id) {            ops.push(definition_op(table, id, after(Some(row)), ServedRow::Retracted)?);        }    }    Ok(ops)}/// WHO THE OWNER IS, AS THE OBJECT SAYS: the `owner_person_id` the object/// serves with the database's meta (`apps/business/src/owner.ts` — the person/// whose phone is the sign-in number), laid on this copy's own workspace row,/// where every read of "you" finds it. A change receipt of [`OBJECT_AUTHOR`]/// stamped after the row's newest, while the copy says otherwise; nothing/// when it already says the same, or when the meta names no link at all (an/// object that has not linked one yet). The object is the link's one writer./// Minted as `mint` says a change ([`cotton_store::mint::served_change`]): a/// workspace row written into the copy before its receipts were takes it as/// its create, and stays.fn served_owner(copy: &cotton_store::driver::Driver, business: &Value, workspace_id: &str, at_ms: i64) -> Result<Vec<CottonOp>, String> {    let Some(served) = business.get("owner_person_id") else {        return Ok(Vec::new());    };    let served = served.as_str().filter(|id| !id.is_empty());    let Some(row) = copy        .get("SELECT owner_person_id, _hlc FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(workspace_id.to_string())])        .map_err(|error| format!("cotton_workspaces could not be read ({error})"))?    else {        return Ok(Vec::new());    };    if row.text("owner_person_id").filter(|id| !id.is_empty()) == served {        return Ok(Vec::new());    }    let ms = row.text("_hlc").and_then(|stamp| stamp.get(..13)).and_then(|ms| ms.parse::<i64>().ok()).map_or(at_ms, |newest| at_ms.max(newest + 1));    let mut patch = Map::new();    patch.insert("owner_person_id".to_string(), served.map_or(Value::Null, Value::from));    let stamp = format!("{ms:013}:0000:{OBJECT_AUTHOR}");    let op = cotton_store::mint::served_change(copy, op_id_of(ms, "cotton_workspaces", workspace_id, ms, &["owner_person_id"]), "cotton_workspaces", workspace_id, &stamp, &object_actor(), patch)        .map_err(|error| error.to_string())?;    Ok(vec![op])}/// One receipt of [`OBJECT_AUTHOR`] on a definitions row, its op id one per/// row and stamp.fn definition_op(table: &ServedTable, id: &str, ms: i64, row: ServedRow) -> Result<CottonOp, String> {    let stamp = format!("{ms:013}:0000:{OBJECT_AUTHOR}");    cotton_store::mint::served(op_id_of(ms, table.store, id, ms, &[]), table.store, id, &stamp, &object_actor(), row, None).map_err(|error| error.to_string())}// ── what only the phone knows of its passes ────────────────────────────────/// The object's table a device's own row lives in (`apps/business`'s/// personal `device`, src/sync_status.ts).pub const DEVICE_TABLE: &str = "device";/// A pass that has had no page land for this long, while the object/// answers, is stalled.pub const STALL_AFTER_MS: i64 = 120_000;/// While a pass is under way, the bytes it has received are written on the/// phone's row at most this often.pub const BYTES_EVERY_MS: i64 = 5_000;/// The longest reason a failed pass writes on the phone's row (`stalled_why`).pub const STALLED_WHY_CHARS: usize = 500;/// Passes running that fail on one page, for one reason, while the object/// answers, before the copy is made again ([`SyncProgress::stuck`]).pub const STUCK_PASSES: u32 = 3;/// HOW FAR THIS PHONE'S PASSES HAVE GOT, AS ONLY THE PHONE KNOWS (owner,/// 26 Oct 2026: sync status is the phone's own device record).////// The object writes on the phone's row how many rows it holds of how many,/// at which version, and whether it is caught up — every page, itself. Two/// things it cannot know, the phone writes there through `/v1/act`:////// * `sync_bytes`, the bytes of sync answers the current pass has received —///   for a pass of more than one page, after a page at most every///   [`BYTES_EVERY_MS`] and once at its end (a pass of one page, a poll,///   writes none, so a caught-up phone's polls do not keep writing);/// * `stalled_at` and `stalled_why`, when a pass fails while the object///   answers — a page this copy cannot take, a refused page, an object///   failing — the moment it first failed and the pass's own sentence (to///   [`STALLED_WHY_CHARS`]); `stalled_at` too when a pass has had no page land///   for [`STALL_AFTER_MS`] (a cursor that does not move). Both `null` again///   with the next page that lands. A phone that reaches nothing (status 0)///   is offline, not stalled;/// * `copy_remade_at`, when `personal.connect` made this phone's copy again///   from the object (another build's copy, or one made under another///   address), so the device card says the copy was made again — written///   with the first page this launch whose answer names the row;/// * `media_waiting_bytes`, `media_waiting` and `media_failed`, the media///   drain's queue as it last stood ([`MediaBacklog`]): what this phone has///   still to back up and what the object refused — written with a pass's///   last page whenever they differ from what the row was last told.////// A page LANDS when the copy took it: the next request holds the cursor/// this one returned. Held across passes (the loop makes a transport per/// pass), in memory for this launch.////// The row is the one the object names in each answer (`device`): the row/// of the device id the credential was granted to, which the object files/// from the first page's [`DeviceNamed`] when it holds none.pub struct SyncProgress {    /// Milliseconds since the epoch, now.    clock: Box<dyn Fn() -> i64 + Send + Sync>,    held: Mutex<PassState>,}/// How full the object's database is, as a pass's last page said (`room`).#[derive(Debug, Clone, Copy, PartialEq)]pub struct Room {    pub bytes: u64,    pub cap: u64,    /// The fraction of `cap` used, 0.8 and up.    pub used: f64,}impl Eq for Room {}/// How full the space for photos and files is, as a pass's last page said (`space`, SPACE.md): from 80% of the/// allowance, once the rules hold for the account.#[derive(Debug, Clone, Copy, PartialEq)]pub struct Space {    pub bytes: u64,    pub allowance: u64,    /// The fraction of `allowance` used, 0.8 and up.    pub used: f64,}impl Eq for Space {}impl Space {    /// The answer's `space`, when it carries one whole.    pub fn of(value: &Value) -> Option<Space> {        Some(Space { bytes: value["bytes"].as_u64()?, allowance: value["allowance"].as_u64()?, used: value["used"].as_f64()? })    }}impl Room {    /// The answer's `room`, when it carries one whole.    pub fn of(value: &Value) -> Option<Room> {        Some(Room { bytes: value["bytes"].as_u64()?, cap: value["cap"].as_u64()?, used: value["used"].as_f64()? })    }}/// Where this phone's passes stand.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct PassState {    /// The object's row for this phone, as its last answer named it.    pub device: Option<String>,    /// Bytes of sync answers the current pass has received.    pub pass_bytes: u64,    /// Pages the current pass has received.    pub pages: u32,    /// The last answer carried no `next`.    pub caught_up: bool,    /// The live rows the phone holds once the pass has landed, as the object counts them.    pub total: Option<i64>,    /// The rows the pass still carries after the last page.    pub remaining: Option<i64>,    /// Of `total`, the live rows this phone holds once the last page landed.    pub done: Option<i64>,    /// The object's clock when it answered the last page: when this phone last synced.    pub synced_at: Option<String>,    /// How full the object's database file stood at the last pass's end, once    /// it is at 80% of its cap or past it (the answer's `room`, owner 22 Nov    /// 2026): its bytes, the cap and the fraction used. None below that.    pub room: Option<Room>,    /// How full the space for photos and files stood at the last pass's end, from 80% of the allowance (`space`,    /// SPACE.md). None below that, or where the rules do not hold.    pub space: Option<Space>,    /// When a page last landed, or the first try of this launch.    pub landed_at: Option<i64>,    /// The `stalled_at` this phone wrote on its row, until a page clears it.    pub stalled_at: Option<String>,    /// The `stalled_why` this phone wrote on its row, until a page clears it.    pub stalled_why: Option<String>,    /// The passes running that failed on one page for one reason while the    /// object answered: the reason and how many ([`SyncProgress::stuck`]).    troubles: Option<(String, u32)>,    /// When this launch made the copy again, until its row says so.    pub copy_remade_at: Option<String>,    /// The last pass failed and no page has landed since (a 5xx, nothing    /// reached, any refusal): a copy still on its first pull says Cotton    /// could not be reached rather than that its things are coming.    pub failing: bool,    /// The media drain's queue as it last stood.    pub media: Option<MediaBacklog>,    /// The server was put back to an earlier time (RESTORE 2) and this copy has not yet been made again from it.    pub restored: Option<ServerRestored>,    /// This copy is being made again after a restore, until the new copy's first sync reaches the server's end: the    /// time the server was put back to (empty when it did not say). What the Sync page says meanwhile.    pub restoring: Option<String>,    /// The last pass met the account held still (`account_frozen`, RESTORE 2): changes wait and go by themselves.    pub frozen: bool,    /// Each object table the pass under way or just ended carries rows of,    /// as its last page said: its rows in the pass and how many have come.    pub tables: BTreeMap<String, TablePass>,    /// The object's name for each table this phone keeps (`cotton_todos` →    /// `todo`), as the transport last held its map: what this phone's queue    /// of writes is told by.    names: BTreeMap<String, String>,    /// The queue as the row was last told it.    posted_media: Option<MediaBacklog>,    /// The cursor the last page returned, and so the one the next request holds when it landed.    returned: Option<String>,    posted_bytes: Option<u64>,    posted_at: Option<i64>,}/// What a pass learned of a restore of the server (RESTORE 2): its new generation and the time it was put back to,/// when the answer said them (a refused post says neither).#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct ServerRestored {    pub generation: Option<String>,    pub restored_to: Option<String>,}/// One table's rows in a pass, as the object's answers say them.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct TablePass {    /// The rows the pass carries of it (tombstones too).    pub rows: i64,    /// How many of them have come.    pub done: i64,}impl PassState {    /// What each table is doing now, by the object's name for it (owner, 2    /// Nov 2026: the deck's counter says "347 of 950 todos arriving", "25    /// todos sending" while a tool's rows move, the plain count once it is    /// settled): `arriving` and `arrived` while the pass has rows of it still    /// to come, `sending` while `queued` — this phone's unsent writes, by its    /// own table — holds writes of it. A table doing neither is not named.    pub fn moving(&self, queued: &[(String, i64)]) -> Map<String, Value> {        let mut out: BTreeMap<String, Map<String, Value>> = BTreeMap::new();        for (table, pass) in self.tables.iter().filter(|(_, pass)| pass.done < pass.rows) {            let entry = out.entry(table.clone()).or_default();            entry.insert("arriving".into(), json!(pass.rows));            entry.insert("arrived".into(), json!(pass.done));        }        for (ours, n) in queued.iter().filter(|(_, n)| *n > 0) {            let Some(table) = self.names.get(ours) else { continue };            let entry = out.entry(table.clone()).or_default();            let held = entry.get("sending").and_then(Value::as_i64).unwrap_or(0);            entry.insert("sending".into(), json!(held + n));        }        out.into_iter().map(|(table, entry)| (table, Value::Object(entry))).collect()    }    /// Rows of `table` (this phone's name for it, `cotton_notes`, or the    /// object's, `note`) the pass under way still has to bring, as its last    /// page said: a newer copy of a row there may be on its way (SYNC SEEN,    /// `sync.row`). `None` when none of it is still to come.    pub fn arriving(&self, table: &str) -> Option<TablePass> {        let name = self.names.get(table).map_or(table, String::as_str);        self.tables.get(name).copied().filter(|pass| pass.done < pass.rows)    }    /// Behind: a pass this launch has begun has not reached its end, or the    /// phone has written its row stalled. Before any page has come this    /// launch the phone does not know, and says nothing.    pub fn behind(&self) -> bool {        (self.returned.is_some() && !self.caught_up) || self.stalled_at.is_some()    }    /// The device record's sync columns as this phone holds them — the same    /// figures the object writes on its row (src/sync_status.ts), from its    /// answers, and the two only the phone knows.    pub fn columns(&self) -> Map<String, Value> {        let mut out = Map::new();        out.insert("synced_at".into(), self.synced_at.clone().map_or(Value::Null, Value::String));        out.insert("sync_rows_total".into(), self.total.map_or(Value::Null, Value::from));        out.insert("sync_rows_done".into(), self.done.map_or(Value::Null, Value::from));        // The row's own figure: the pass under way or just ended, when it ran        // to more than one page, else the last one posted (a poll of one page        // posts none, and says none).        let long = self.pages > 1 || (self.returned.is_some() && !self.caught_up);        let bytes = if long { Some(self.pass_bytes) } else { self.posted_bytes };        out.insert("sync_bytes".into(), bytes.map_or(Value::Null, Value::from));        out.insert("caught_up".into(), Value::Bool(self.caught_up));        out.insert("stalled_at".into(), self.stalled_at.clone().map_or(Value::Null, Value::String));        out.insert("stalled_why".into(), self.stalled_why.clone().map_or(Value::Null, Value::String));        out    }}/// WHAT THIS PHONE HAS STILL TO BACK UP: its `_media` queue, counted by the/// drain after every tick (`cotton_client::media::drain`), so the device card/// can say "1.2 GB to back up" from the row alone.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct MediaBacklog {    /// The bytes of the rows waiting to go up.    pub waiting_bytes: i64,    /// The rows waiting to go up.    pub waiting: i64,    /// The rows the object refused for good (`object_full`, `too_big`).    pub failed: i64,}impl MediaBacklog {    fn columns(&self) -> Map<String, Value> {        Map::from_iter([            ("media_waiting_bytes".to_string(), json!(self.waiting_bytes)),            ("media_waiting".to_string(), json!(self.waiting)),            ("media_failed".to_string(), json!(self.failed)),        ])    }}/// One write on this phone's row.#[derive(Debug, Clone, PartialEq)]enum Report {    Update { device: String, data: Map<String, Value> },}/// How far a pass that failed got with the object.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Reached {    /// Nothing answered (status 0): offline, not stalled.    Nothing,    /// The object refused the credential, the pace or itself (401, 403, 429,    /// 5xx): said on the row, and never the copy's fault.    Refused,    /// The object answered and the pass could not go on; `mid_pass` when the    /// request held a page cursor.    Answered { mid_pass: bool },}/// One page as it arrived.struct Landed<'a> {    /// The cursor the request held.    held: &'a str,    /// The cursor this page returns.    cursor: &'a str,    answer: &'a Value,    received: usize,    /// The page is a pass's first.    opened: bool,    more: bool,    /// The runtime state supplied by the app after this page landed.    reported_state: Option<Value>,}impl std::fmt::Debug for SyncProgress {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("SyncProgress").field("state", &self.state()).finish_non_exhaustive()    }}impl SyncProgress {    /// `clock` says now in milliseconds since the epoch.    pub fn new(clock: impl Fn() -> i64 + Send + Sync + 'static) -> Arc<SyncProgress> {        Arc::new(SyncProgress { clock: Box::new(clock), held: Mutex::new(PassState::default()) })    }    /// On the system clock.    pub fn system() -> Arc<SyncProgress> {        SyncProgress::new(|| chrono::Utc::now().timestamp_millis())    }    /// This launch made the copy again from the object at `at` (an ISO    /// time): the next page that names the row writes it there.    pub fn remade(&self, at: String) {        let mut state = self.lock();        state.copy_remade_at = Some(at);        // A copy made again begins its passes with no troubles of its own,        // and from no cursor: its first page is one that moved.        state.troubles = None;        state.returned = None;    }    /// The server was put back to an earlier time (RESTORE 2): this copy is made again ([`Self::restore_seen`]). What    /// an earlier answer said stands where this one says nothing.    pub fn restored(&self, generation: Option<String>, restored_to: Option<String>) {        let mut state = self.lock();        let held = state.restored.take().unwrap_or_default();        state.restored = Some(ServerRestored { generation: generation.or(held.generation), restored_to: restored_to.or(held.restored_to) });    }    /// A restore seen and not yet acted on.    pub fn restore_seen(&self) -> Option<ServerRestored> {        self.lock().restored.clone()    }    /// The copy is being made again after a restore (`Some`, the time it was put back to), or that ended without a    /// copy made (`None`): a restore seen again makes it again.    pub fn restoring(&self, restored_to: Option<String>) {        let mut state = self.lock();        state.restored = None;        state.restoring = restored_to;    }    /// The last pass met the account held still, or did not.    pub fn frozen(&self, frozen: bool) {        self.lock().frozen = frozen;    }    /// Why the copy is stuck, when the last [`STUCK_PASSES`] passes running    /// failed on one page for one reason while the object answered — not    /// offline, and not a 401, 403, 429 or 5xx refusal: the copy's own state    /// holds the pass, and only a copy made again from the object gets past.    pub fn stuck(&self) -> Option<String> {        self.lock().troubles.clone().filter(|(_, passes)| *passes >= STUCK_PASSES).map(|(why, _)| why)    }    /// A page answered: the row it names is this phone's.    fn named(&self, answer: &Value) {        match answer.get("device") {            Some(Value::String(id)) => self.lock().device = Some(id.clone()),            Some(Value::Null) => self.lock().device = None,            _ => {}        }    }    /// The media drain's queue now: written on the row with the next pass's    /// last page when the row was told otherwise.    pub fn media(&self, backlog: MediaBacklog) {        self.lock().media = Some(backlog);    }    /// The transport's map of tables now: this phone's queue is told by it.    fn knows(&self, tables: &ObjectTables) {        let names = tables.tables.iter().map(|t| (t.store.clone(), t.table.clone())).collect();        self.lock().names = names;    }    /// Where the passes stand now.    pub fn state(&self) -> PassState {        self.lock().clone()    }    fn lock(&self) -> std::sync::MutexGuard<'_, PassState> {        self.held.lock().unwrap_or_else(|poisoned| poisoned.into_inner())    }    /// A page arrived: what to write on the row.    fn landed(&self, page: Landed<'_>) -> Vec<Report> {        let now = (self.clock)();        let mut state = self.lock();        state.failing = false;        // The page before this one landed when the copy holds what it returned.        let moved = state.returned.as_deref().is_none_or(|returned| page.held >= returned);        if page.opened {            state.pass_bytes = 0;            state.pages = 0;        }        state.pass_bytes += page.received as u64;        state.pages += 1;        state.caught_up = !page.more;        state.total = page.answer["total"].as_i64();        state.remaining = page.answer["remaining"].as_i64();        state.done = page.answer["done"].as_i64();        state.tables = page.answer["tables"]            .as_object()            .into_iter()            .flatten()            .filter_map(|(table, pass)| Some((table.clone(), TablePass { rows: pass["rows"].as_i64()?, done: pass["done"].as_i64()? })))            .collect();        state.synced_at = page.answer["server_time"].as_str().map(str::to_string);        // The object says how full it is on a pass's last page, and only from 80%: a last page without it is room enough.        if !page.more {            state.room = Room::of(&page.answer["room"]);            state.space = Space::of(&page.answer["space"]);            // The copy made again after a restore has reached the server's end.            state.restoring = None;        }        state.frozen = false;        state.returned = Some(page.cursor.to_string());        match page.answer.get("device") {            Some(Value::String(id)) => state.device = Some(id.clone()),            Some(Value::Null) => state.device = None,            _ => {}        }        if moved {            state.landed_at = Some(now);            state.troubles = None;        }        let mut reports = Vec::new();        let Some(device) = state.device.clone() else {            return reports;        };        let mut data = Map::new();        if moved && state.stalled_at.is_some() {            data.insert("stalled_at".into(), Value::Null);        }        if moved && state.stalled_why.is_some() {            data.insert("stalled_why".into(), Value::Null);        }        if let Some(remade) = &state.copy_remade_at {            data.insert("copy_remade_at".into(), json!(remade));        }        // A completed pass is the device's heartbeat. Report its runtime        // build, commit and schema even when it was a one-page poll.        // Carried on a pull's last page, and on every REPORT_EVERY_PAGES-th of a long one (the pull decides which).        // The page carrying it is itself an answer: the report says this page's time and "ok", never the last pass's        // answer, which the first pass after a launch does not have yet (REPORT FIELDS, 26 Nov 2026: Days and Books        // reported with neither while a slow server never let a second pass end).        if let Some(mut reported_state) = page.reported_state.and_then(|state| cotton_core::device::reported_state::ReportedState::accept(&state)) {            reported_state.last_exchange_at = state.synced_at.clone().or_else(|| chrono::DateTime::from_timestamp_millis(now).map(crate::seams::iso));            reported_state.last_answer = Some("ok".to_string());            data.insert("reported_state".into(), reported_state.to_value());        }        if !page.more {            if let Some(media) = state.media.filter(|media| state.posted_media != Some(*media)) {                data.extend(media.columns());            }        }        let long = page.more || state.pages > 1;        let due = !page.more || state.posted_at.is_none_or(|at| now - at >= BYTES_EVERY_MS);        if long && due && state.posted_bytes != Some(state.pass_bytes) {            data.insert("sync_bytes".into(), json!(state.pass_bytes));        }        if !moved {            if let Some(stalled) = stall(&state, now) {                data.insert("stalled_at".into(), json!(stalled));            }        }        if !data.is_empty() {            reports.push(Report::Update { device, data });        }        reports    }    /// A pass failed for `why`: what to write on the row. A pass the object    /// answered or refused says why — `stalled_why`, the sentence cut to    /// [`STALLED_WHY_CHARS`], whenever the row says otherwise, and    /// `stalled_at`, now, when the row holds none (the moment it first    /// stalled stands until a page lands). A phone that reached nothing is    /// offline, and writes nothing. Each pass that fails mid-pass while the    /// object answered counts towards [`Self::stuck`] while its reason is the    /// last one's; any other failure ends the run.    fn troubled(&self, why: &str, reached: Reached) -> Vec<Report> {        let now = (self.clock)();        let mut state = self.lock();        state.landed_at.get_or_insert(now);        state.failing = true;        let why: String = why.chars().take(STALLED_WHY_CHARS).collect();        state.troubles = match (reached, state.troubles.take()) {            (Reached::Answered { mid_pass: true }, Some((held, passes))) if held == why => Some((held, passes + 1)),            (Reached::Answered { mid_pass: true }, _) => Some((why.clone(), 1)),            _ => None,        };        if reached == Reached::Nothing {            return Vec::new();        }        let Some(device) = state.device.clone() else { return Vec::new() };        let mut data = Map::new();        if state.stalled_at.is_none() {            if let Some(at) = chrono::DateTime::from_timestamp_millis(now) {                data.insert("stalled_at".into(), json!(at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)));            }        }        if state.stalled_why.as_deref() != Some(why.as_str()) {            data.insert("stalled_why".into(), json!(why));        }        if data.is_empty() {            return Vec::new();        }        vec![Report::Update { device, data }]    }    /// A write on the row landed.    fn posted(&self, report: &Report) {        let now = (self.clock)();        let mut state = self.lock();        match report {            Report::Update { data, .. } => {                if let Some(bytes) = data.get("sync_bytes").and_then(Value::as_u64) {                    state.posted_bytes = Some(bytes);                    state.posted_at = Some(now);                }                match data.get("stalled_at") {                    Some(Value::String(at)) => state.stalled_at = Some(at.clone()),                    Some(Value::Null) => state.stalled_at = None,                    _ => {}                }                match data.get("stalled_why") {                    Some(Value::String(why)) => state.stalled_why = Some(why.clone()),                    Some(Value::Null) => state.stalled_why = None,                    _ => {}                }                let told = |key: &str| data.get(key).and_then(Value::as_i64);                if let (Some(waiting_bytes), Some(waiting), Some(failed)) = (told("media_waiting_bytes"), told("media_waiting"), told("media_failed")) {                    state.posted_media = Some(MediaBacklog { waiting_bytes, waiting, failed });                }                // Written: the row says it now, unless a later remake waits.                if data.get("copy_remade_at").and_then(Value::as_str).is_some_and(|at| state.copy_remade_at.as_deref() == Some(at)) {                    state.copy_remade_at = None;                }            }        }    }}/// The `stalled_at` to write now, when a pass under way has had no page land/// for [`STALL_AFTER_MS`] while the object answers, and none is written yet.fn stall(state: &PassState, now: i64) -> Option<String> {    let since = state.landed_at?;    if state.stalled_at.is_some() || now - since < STALL_AFTER_MS {        return None;    }    chrono::DateTime::from_timestamp_millis(now).map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))}// ── the first copy ─────────────────────────────────────────────────────────/// Make this phone's copy of the object's database where the loop opens it: a/// file of this build's schema, of `workspace_id` (the object's/// `database_id`), that the first pull fills. It is born as a database a phone/// starts is born (`start::make_file`): the shell — Home's board, the themes —/// and the app's genesis set installed as ordinary data, so every deck draws/// its tables from definitions this file holds. They are this phone's alone/// (written as served, so nothing queues for the object, which keeps its own)./// `signer` is this device's key, which signs the file's first author. A file/// already there is kept.pub fn make_copy(    path: &Path,    workspace_id: &str,    owner_id: &str,    device_id: &str,    now: &str,    tools: &cotton_core::genesis::GenesisTools,    signer: cotton_store::signed::SignerSlot,) -> Result<(), String> {    // ONE MAKER AT A TIME. A first sign-in can ask for the copy twice at once    // (the sign-in's own connect and the app's start racing it): both saw no    // copy, the second removed the first's side file, and one of them failed    // its move with "replica.db (No such file or directory)" while the other's    // copy stood (Pat's You page). The second now waits, and    // finds the copy made.    static MAKING: std::sync::Mutex<()> = std::sync::Mutex::new(());    let _one = MAKING.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    if path.exists() {        return Ok(());    }    if let Some(dir) = path.parent() {        std::fs::create_dir_all(dir).map_err(|error| format!("{} ({error})", dir.display()))?;    }    let at = chrono::DateTime::parse_from_rfc3339(now).map_err(|error| format!("{now} is not an instant ({error})"))?.with_timezone(&chrono::Utc);    // BORN BESIDE ITS PATH AND MOVED IN WHOLE: the copy is made under a side    // name and renamed to `path` only once it is complete, so a process killed    // part way leaves no half-made copy at `path` (which this keeps for good)    // — only a side file the next make removes. That is what lets the birth    // write with no fsync at all (`synchronous = OFF`): on a busy disk the    // syncs of a fresh copy's commits and checkpoints were most of its time    // (copy-installer-store, 8 Nov 2026). The file is synced once, whole,    // before it is moved in.    let making = making_path(path);    remove_with_sidecars(&making);    let made = (|| -> Result<(), String> {        let db = cotton_store::driver::Driver::open(&making).map_err(|error| error.to_string())?.sharing_signer(signer);        db.exec("PRAGMA synchronous = OFF").map_err(|error| error.to_string())?;        cotton_store::create::create_workspace(            &db,            &cotton_store::meta::Meta {                workspace_id: workspace_id.to_string(),                owner_id: owner_id.to_string(),                device_id: device_id.to_string(),                last_server_seq: 0,                last_hlc: None,            },        )        .map_err(|error| error.to_string())?;        let held = cotton_store::mint::Held::Served;        // The database's own row, minted as every row is: the object keeps        // its own and never serves it, so this copy's is this phone's alone.        let seed = cotton_store::birth::WorkspaceSeed { workspace_id, owner_id, name: None, kind: "personal", relay: None };        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SystemRandom));        cotton_store::birth::seed_workspace_row(&db, now, at.timestamp_millis(), &seed, &mut ids, held).map_err(|error| error.to_string())?;        cotton_tools::presentation::write_shell_for_a_copy(&db, at, Arc::new(cotton_tools::random::SystemRandom), held).map_err(|failure| failure.0)?;        cotton_tools::kit::install_genesis_tools(&db, at, Arc::new(cotton_tools::random::SystemRandom), held, tools).map_err(|failure| failure.0)?;        seal_birth(&db)?;        drop(db);        // The new copy moves into a free place only: one standing there is never replaced (QUEUE BAD OP 4).        crate::copy_keep::place_new(&making, path)    })();    made.map_err(|error| {        remove_with_sidecars(&making);        format!("this phone's copy could not be made ({error})")    })}/// Where [`make_copy`] makes a copy before it is moved to `path`.fn making_path(path: &Path) -> std::path::PathBuf {    let mut name = path.file_name().unwrap_or_default().to_os_string();    name.push(".making");    path.with_file_name(name)}/// A file and its write-ahead log and shared memory, gone.fn remove_with_sidecars(path: &Path) {    for suffix in ["", "-wal", "-shm"] {        let mut name = path.as_os_str().to_os_string();        name.push(suffix);        // not a copy: a copy being made (`.making`), never opened by anything but its maker.        let _ = std::fs::remove_file(std::path::PathBuf::from(name));    }}/// The end of a birth written with no syncs: the handle's own durability/// back, and the whole log folded into the file and synced, so the file/// moved in holds everything by itself.pub fn seal_birth(db: &cotton_store::driver::Driver) -> Result<(), String> {    db.exec("PRAGMA synchronous = NORMAL").map_err(|error| error.to_string())?;    match db.checkpoint_truncate().map_err(|error| error.to_string())? {        cotton_store::driver::Folded::Truncated => Ok(()),        cotton_store::driver::Folded::Busy => Err("the new copy's log could not be folded in".into()),    }}/// What a copy another build wrote sent before it was remade/// ([`ObjectTransport::send_before_remake`]): the writes the object took, and/// how many it did not (written down as discarded).#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct SentBeforeRemake {    pub delivered: usize,    pub refused: usize,    /// The op ids the object took or answered for good: what `crate::copy_keep::retire` leaves out of its question.    pub acknowledged: Vec<String>,    /// The op ids the object never took that no copy of this app can send (a table its kit does not carry): kept with    /// the copy, listed, never sent by recovery.    pub held_back: Vec<String>,}/// Where the set-aside changes of the copy at `replica` wait while it is made again: beside it, a name no removal/// of the copy touches.pub fn carried_path(replica: &Path) -> PathBuf {    PathBuf::from(format!("{}.set-aside.json", replica.display()))}/// Rewrite the carried file at `path` (QUEUE BAD OP 3) to hold exactly `left`: what recovery could not send yet.pub fn carry_set_aside_to(path: &Path, left: &[cotton_store::rejected::SetAside]) -> Result<(), String> {    use base64::Engine as _;    let set_aside = left;    let mut kept: Vec<Value> = Vec::new();    let b64 = base64::engine::general_purpose::STANDARD;    for change in set_aside {        if kept.iter().any(|kept| kept["op_id"] == json!(change.op_id)) {            continue;        }        kept.push(json!({            "op_id": change.op_id, "reason": change.reason, "first_at": change.first_at, "table": change.table, "row_id": change.row_id,            "bytes": b64.encode(&change.bytes), "sig": change.sig.as_ref().map(|sig| b64.encode(sig)),        }));    }    let bytes = serde_json::to_vec(&kept).map_err(|error| error.to_string())?;    // not a copy: the carried file beside the copy, rewritten to what is left to send.    crate::whole_file::replace(path, &bytes).map_err(|error| format!("this phone's set-aside changes could not be written ({error})"))}/// The set-aside changes carried beside the copy at `replica`, as the store parks them.pub fn carried(replica: &Path) -> Vec<cotton_store::rejected::SetAside> {    carried_file(&carried_path(replica))}/// The set-aside changes a carried file at `path` holds.pub fn carried_file(path: &Path) -> Vec<cotton_store::rejected::SetAside> {    carried_file_read(path).unwrap_or_default()}/// The carried file at `path`, whole or not at all (QUEUE BAD OP 7): a file that does not read, does not parse, or/// holds an entry missing a field is an error, so whatever reads it leaves it untouched.pub fn carried_file_read(path: &Path) -> Result<Vec<cotton_store::rejected::SetAside>, String> {    use base64::Engine as _;    let b64 = base64::engine::general_purpose::STANDARD;    let bytes = std::fs::read(path).map_err(|error| format!("the carried file does not read ({error})"))?;    let kept: Vec<Value> = serde_json::from_slice(&bytes).map_err(|error| format!("the carried file does not parse ({error})"))?;    kept.iter()        .enumerate()        .map(|(n, kept)| {            let field = |name: &str| kept[name].as_str().map(str::to_string).ok_or_else(|| format!("the carried file's entry {n} has no {name}"));            Ok(cotton_store::rejected::SetAside {                op_id: field("op_id")?,                reason: field("reason")?,                first_at: kept["first_at"].as_str().unwrap_or_default().to_string(),                bytes: b64.decode(field("bytes")?).map_err(|error| format!("the carried file's entry {n} has bytes that do not decode ({error})"))?,                sig: match kept["sig"].as_str() {                    Some(sig) => Some(b64.decode(sig).map_err(|error| format!("the carried file's entry {n} has a signature that does not decode ({error})"))?),                    None => None,                },                table: field("table")?,                row_id: field("row_id")?,            })        })        .collect()}// ── the first paint ────────────────────────────────────────────────────────/// What [`lay_served_definitions`] wrote into a fresh copy: how many of the/// object's tools, tables and boards, and the receipts the fold refused/// (parked, as a pass parks one).#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Laid {    pub tools: usize,    pub tables: usize,    pub boards: usize,    pub refused: Vec<String>,}/// Each column `definitions` name on a table this build compiles that the/// build's table lacks (an event's `kind`), added to the file in place,/// add-only: what the object's definitions bring a fresh copy, and what the/// kit's bring a phone's own database, which no object fills. Answers the/// columns added.pub fn hold_defined_columns<'a>(db: &cotton_store::driver::Driver, definitions: impl IntoIterator<Item = &'a Value>) -> Result<Vec<String>, String> {    let map = ObjectTables::personal().with_defined(definitions)?;    let mut added = Vec::new();    for table in map.tables.iter().filter(|table| table.compiled && !table.served.is_empty()) {        added.extend(            package_shape::add_served(db, &table.store, &table.served)                .map_err(|error| format!("this phone's copy could not take the columns of {} ({error})", table.table))?,        );    }    Ok(added)}/// THE FIRST PAINT IS THE OBJECT'S OWN (28 Oct 2026). `personal.connect`/// asks the object's `/v1/definitions` before it makes a fresh copy (to learn/// which database, and whose); this lays that very answer into the copy it/// just made, as the receipts of [`OBJECT_AUTHOR`] a pass folds from it/// ([`served_definitions`], [`served_owner`]), so the fan, the decks and the/// boards draw whole the moment the copy opens — before the first page of/// `/v1/sync` answers, which on a catch-up is thousands of rows away. No/// bundled copy stands in: the object stays the one source, and what is laid/// is what it serves, its edits, its made tables and Home's empty tools/// with it. The first pass asks the definitions again and finds the copy/// holding them; anything the object moved in between is taken then, as on/// any pass.////// A copy that already holds any of the object's definitions is never laid/// over: the passes keep it. A table the answer defines that this build/// compiles takes the columns it names first, as a pass's map does/// ([`ObjectTables::with_defined`]). A receipt the fold refuses is parked,/// as a pass parks it, and named in the answer.pub fn lay_served_definitions(path: &Path, workspace_id: &str, served: &Value, now_ms: i64) -> Result<Laid, String> {    let db = cotton_store::driver::Driver::open(path).map_err(|error| format!("this phone's copy could not be opened ({error})"))?;    let unreadable = |error: rusqlite::Error| format!("this phone's copy could not be read ({error})");    for store in [SERVED_TABLES.store, SERVED_TOOLS.store, SERVED_BOARDS.store, SERVED_THEMES.store] {        let mut statement = db.connection().prepare(&format!("SELECT _hlc FROM \"{store}\"")).map_err(unreadable)?;        let stamps: Vec<Option<String>> = statement.query_map([], |row| row.get(0)).map_err(unreadable)?.collect::<Result<_, _>>().map_err(unreadable)?;        if stamps.iter().any(|stamp| cotton_store::fold::author_of(stamp.as_deref().unwrap_or_default()) == Some(OBJECT_AUTHOR)) {            return Ok(Laid::default());        }    }    let at_ms = now_ms.clamp(0, cotton_store::protocol::hlc::MAX_MS);    let tables = drawable_tables(&served["tables"]);    hold_defined_columns(&db, tables.iter().map(|(_, definition)| definition))?;    let file = db.connection();    let mut ops = Vec::new();    let known = file        .query_row("SELECT 1 FROM cotton_authors WHERE id = ?1", [OBJECT_AUTHOR], |_| Ok(()))        .map(|()| true)        .or_else(|error| if error == rusqlite::Error::QueryReturnedNoRows { Ok(false) } else { Err(unreadable(error)) })?;    if !known {        ops.push(object_author_fact(workspace_id)?);    }    let none = std::collections::BTreeSet::new();    let laid_tables = served_definitions(file, &SERVED_TABLES, tables, workspace_id, at_ms, &none)?;    let laid_tools = served_definitions(file, &SERVED_TOOLS, drawable_tools(&served["tools"]), workspace_id, at_ms, &none)?;    let laid_boards = served_definitions(file, &SERVED_BOARDS, served_boards(&served["boards"]), workspace_id, at_ms, &none)?;    let mut laid = Laid { tools: laid_tools.len(), tables: laid_tables.len(), boards: laid_boards.len(), refused: Vec::new() };    ops.extend(laid_tables);    ops.extend(laid_tools);    ops.extend(laid_boards);    ops.extend(served_definitions(file, &SERVED_THEMES, served_boards(&served["themes"]), workspace_id, at_ms, &none)?);    ops.extend(served_owner(&db, &served["business"], workspace_id, at_ms)?);    let now = chrono::DateTime::from_timestamp_millis(at_ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    db.transaction(|db| {        let result = cotton_store::fold::fold_pulled(db, &ops)?;        cotton_store::rejected::park_waiting(db, &ops, &result.waiting, cotton_store::rejected::Direction::Pull, &now)?;        for rejection in &result.rejected {            if let Some(op) = ops.iter().find(|op| op.op_id == rejection.op_id) {                cotton_store::rejected::park(db, op, cotton_store::rejected::Direction::Pull, cotton_store::rejected::Class::of_refusal(&rejection.reason), &rejection.reason, &now)?;                laid.refused.push(format!("{} {}: {}", op.table, op.row_id, rejection.reason));            }        }        Ok(())    })    .map_err(|error| format!("the object's definitions could not be laid into this phone's copy ({error})"))?;    eprintln!("[object] definitions: laid {} tools, {} tables, {} boards from the object's answer at sign-in", laid.tools, laid.tables, laid.boards);    for refused in &laid.refused {        eprintln!("[object] definitions: the copy refused {refused}: parked, as a pass parks it");    }    Ok(laid)}#[cfg(test)]#[path = "object_tests.rs"]mod tests;#[path = "object_adopt.rs"]mod adopt;#[path = "object_restore.rs"]mod restore;pub use restore::{caught_up, object_definitions, unnamed_tables, whole_rows, restore_order, RestoreInto, RestoreLanded, RestoreMemory, Restored, WholeRow, Written, RESTORE_BATCH, RESTORE_PATIENCE};pub use adopt::{mark_delivered, AdoptInto, AdoptLog, AdoptMemory, Adopted, AdoptLanded, Landing, Rekey, ADOPT_DISCARDED_WHY, ADOPT_STOPPED, DEFINITION_TABLES, OBJECT_STANDS};#[cfg(test)]#[path = "object_sealed_tests.rs"]mod sealed_tests;