3303 lines · 198.0 KB · RustRaw
//! Backup is adopt, against a personal object that keeps its rows: a used//! local database's writes reach the object once each, its media move to the//! copy and go up, and the local database goes only once the copy is//! connected. Synthetic rows and ids only.use std::collections::BTreeMap;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_client::transport::Exchange;use serde_json::{json, Value};use super::*;use crate::phone::personal_object::call_with;// Its own id, not the fixture's: run beside `personal_object`'s cases under// the same id, `a_copy_an_earlier_build_wrote_is_made_again_from_the_object`// took this fake object's definitions and failed (state the process keeps by// database id), and passed alone.const DATABASE: &str = "a0a0a0a0-0000-4000-8000-00000000ad09";const OWNER: &str = "owner-person";fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")), }) .expect("an open core"); holds_the_data_keys(&handle); (dir, handle)}/// This phone holds each test object's data key, as a phone does once it/// founds the key or is approved for it: todos are sealed (e2e rulings R1),/// and a sealed row goes up only under the object's key.fn holds_the_data_keys(handle: &CottonHandle) { for database in [DATABASE, FORMER, PERSON_B] { handle.client().data_keys().hold(database, &cotton_core::seal::DataKey::from_bytes([9; 32])); }}fn ask() -> Value { json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "credential": "synthetic-credential", "windows": {"message": 90}, "deviceName": "An invented phone"})}/// This phone starts its own database, as a fresh install does before anyone/// signs in; answers its id.fn started_here(handle: &CottonHandle) -> String { crate::methods::dispatch(handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); connection_of(handle).and_then(|mine| mine.workspace_id).expect("a database")}fn connection_of(handle: &CottonHandle) -> Option<cotton_client::connection::StoredConnection> { cotton_client::connection::ConnectionFile::at(handle.client().layout().connection_json()).read()}fn todo(handle: &CottonHandle, title: &str) -> String { let made = crate::methods::dispatch(handle, "records.create", &json!({"table": "todo", "data": {"title": title}})).expect("a todo"); made["change"]["record_id"].as_str().or(made["id"].as_str()).or(made["record"]["id"].as_str()).map(str::to_string).unwrap_or_else(|| panic!("a record id: {made}"))}fn note(handle: &CottonHandle, title: &str) { crate::methods::dispatch(handle, "records.create", &json!({"table": "note", "data": {"title": title, "body": "Invented."}})).expect("a note");}/// A picture filed from the picker; answers its key.fn picture(handle: &CottonHandle, dir: &std::path::Path) -> String { let picked = dir.join("picked.jpg"); std::fs::write(&picked, b"an invented picture").expect("a synthetic file"); let filed = crate::methods::dispatch(handle, "capture.media", &json!({"path": picked.to_string_lossy(), "mime": "image/jpeg", "filename": "picked.jpg", "kind": "photo"})).expect("filed"); filed["key"].as_str().map(str::to_string).expect("a key")}/// How the line behaves once the object has taken `budget` more acts.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Drop { /// Nothing answers before the act lands. Before, /// The act lands and the answer never comes: the app killed mid-post. After,}/// Something done on the phone while the adopt runs, once it answers true (QUEUE BAD OP 6: a photo filed while the/// copy is made).struct MidCopy(Option<Box<dyn FnMut() -> bool + Send>>);impl std::fmt::Debug for MidCopy { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(if self.0.is_some() { "MidCopy(armed)" } else { "MidCopy(none)" }) }}/// A personal object that keeps its rows: acts land in them (a create of an/// id it holds is `duplicate_id`), a sync page serves them all, and media/// PUTs are kept.#[derive(Debug)]struct Door { /// Run on each call until it answers true. mid_copy: Mutex<MidCopy>, rows: Mutex<BTreeMap<(String, String), Value>>, version: Mutex<i64>, /// Every act the object took. taken: Mutex<Vec<Value>>, /// Acts it will still take before the line drops; `None`, every one. budget: Mutex<Option<(usize, Drop)>>, /// Tables whose writes it refuses for good. refuses: Mutex<Vec<String>>, media: Mutex<Vec<(String, Vec<u8>)>>, pages: AtomicBool, /// Whether a delete leaves a tombstone a pull serves (`deleted: true`), as /// the Worker's does, rather than the row going without a word. keeps_tombstones: AtomicBool, tombstones: Mutex<BTreeMap<(String, String), String>>, /// The database this object is. database: String, /// Each row's `updated_at`, as a restore said it. stamps: Mutex<BTreeMap<(String, String), String>>, /// Rows a `restore` made, by id: each should be once. restored: Mutex<BTreeMap<String, usize>>, /// A file that must stand while any act lands, and whether it ever did not. watched: Mutex<Option<std::path::PathBuf>>, went_early: AtomicBool, /// Every media path asked for (a fetch), by GET. fetched: Mutex<Vec<String>>, /// Whether it answers `GET /v1/held` (the ids it holds), as a Worker from /// 11 Nov 2026 does; otherwise 404, as an older one does. serves_held: AtomicBool, /// Every path asked, in order. asked: Mutex<Vec<String>>, /// A `restore` call carrying more rows than this is never answered (the /// line gives no word, nothing lands): an object too slow for a big call. answers_at_most: Mutex<Option<usize>>, /// How many calls went unanswered. unanswered: Mutex<usize>, /// The number of the person this object is (`GET /v1/me`). phone: Mutex<String>, /// Each row's version once a write moved it from the 2 every row starts at. row_versions: Mutex<BTreeMap<(String, String), i64>>, /// Kit packages it serves beside the ones every object here serves. also_serves: Mutex<Vec<&'static str>>, /// Every act answered this refusal `(status, code, message)`. faults: Mutex<Option<(u16, String, String)>>,}impl Door { fn new() -> Arc<Door> { Door::of(DATABASE) } fn of(database: &str) -> Arc<Door> { Arc::new(Door { mid_copy: Mutex::new(MidCopy(None)), database: database.to_string(), stamps: Mutex::new(BTreeMap::new()), restored: Mutex::new(BTreeMap::new()), watched: Mutex::new(None), went_early: AtomicBool::new(false), fetched: Mutex::new(Vec::new()), serves_held: AtomicBool::new(false), asked: Mutex::new(Vec::new()), answers_at_most: Mutex::new(None), unanswered: Mutex::new(0), phone: Mutex::new("+919000000009".to_string()), row_versions: Mutex::new(BTreeMap::new()), also_serves: Mutex::new(Vec::new()), faults: Mutex::new(None), rows: Mutex::new(BTreeMap::new()), version: Mutex::new(3), taken: Mutex::new(Vec::new()), budget: Mutex::new(None), refuses: Mutex::new(Vec::new()), media: Mutex::new(Vec::new()), pages: AtomicBool::new(true), keeps_tombstones: AtomicBool::new(false), tombstones: Mutex::new(BTreeMap::new()), }) } fn holding(self: Arc<Door>, table: &str, id: &str, data: Value) -> Arc<Door> { self.rows.lock().unwrap().insert((table.to_string(), id.to_string()), data); self } /// The object of another person: another number answers `GET /v1/me`. fn of_person(self: Arc<Door>, phone: &str) -> Arc<Door> { *self.phone.lock().unwrap() = phone.to_string(); self } fn count(&self, table: &str) -> usize { self.rows.lock().unwrap().keys().filter(|(held, _)| held == table).count() } fn creates(&self) -> BTreeMap<String, usize> { let mut seen = BTreeMap::new(); for act in self.taken.lock().unwrap().iter().filter(|act| act["act"] == "create") { *seen.entry(act["args"]["id"].as_str().unwrap_or_default().to_string()).or_insert(0) += 1; } seen } fn refusal(status: u16, code: &str, message: &str) -> Reply { Reply::new(status, json!({"code": code, "message": message}).to_string().into_bytes()) } /// One act, as the object decides it; `Err` is the line dropped. fn act(&self, body: Value) -> Result<Reply, String> { if let Some(most) = *self.answers_at_most.lock().unwrap() { if body["act"] == "restore" && body["args"]["rows"].as_array().map_or(0, Vec::len) > most { *self.unanswered.lock().unwrap() += 1; return Err("https://object.example did not answer (the time this call waits ran out)".into()); } } let mut budget = self.budget.lock().unwrap(); let mut drop_after = false; if let Some((left, how)) = budget.as_mut() { if *left == 0 { if *how == Drop::Before { return Err("the line dropped".into()); } drop_after = true; } else { *left -= 1; } } drop(budget); if self.watched.lock().unwrap().as_ref().is_some_and(|path| !path.exists()) { self.went_early.store(true, Ordering::SeqCst); } let args = &body["args"]; if body["act"] == "restore" { return self.restore(body.clone(), drop_after); } let table = args["table"].as_str().unwrap_or_default().to_string(); let id = args["id"].as_str().unwrap_or_default().to_string(); if let Some((status, code, message)) = self.faults.lock().unwrap().clone() { return Ok(Door::refusal(status, &code, &message)); } if self.refuses.lock().unwrap().contains(&table) { return Ok(Door::refusal(400, "bad_column", &format!("{table} takes nothing from this phone"))); } let mut rows = self.rows.lock().unwrap(); let key = (table.clone(), id.clone()); let reply = match body["act"].as_str() { Some("definition") => return Ok(Door::refusal(400, "definition_refused", "the kit keeps this tool")), Some("create") if rows.contains_key(&key) => return Ok(Door::refusal(409, "duplicate_id", &format!("{table} {id} exists"))), Some("create") => { // A tombstone's id made again lives again, as the Worker's insert does. self.tombstones.lock().unwrap().remove(&key); rows.insert(key, args["data"].clone()); Reply::ok("{}") } Some("update") if !rows.contains_key(&key) => return Ok(Door::refusal(404, "no_such_record", &format!("no {table} {id}"))), Some("update") => { let row = rows.get_mut(&key).expect("held"); // A sealing write drops what the row held in the clear outside it, as the object does (engine.update): a device sends every clear column beside sealed_enc. if args["data"]["sealed_enc"].is_string() { if let (Some(held), Some(sent)) = (row.as_object_mut(), args["data"].as_object()) { held.retain(|column, _| sent.contains_key(column)); } } for (column, value) in args["data"].as_object().into_iter().flatten() { row[column] = value.clone(); } *self.row_versions.lock().unwrap().entry(key).or_insert(2) += 1; Reply::ok("{}") } // The owner's device seals a row only at the version it read, and what it sends merges over the row (sealAct, engine.update). Some("seal") if !rows.contains_key(&key) => return Ok(Door::refusal(404, "no_such_record", &format!("no {table} {id}"))), Some("seal") => { let mut versions = self.row_versions.lock().unwrap(); let at = versions.get(&key).copied().unwrap_or(2); if args["expect_version"].as_i64() != Some(at) { return Ok(Door::refusal(409, "version_moved", &format!("{table} {id} is at version {at}"))); } let row = rows.get_mut(&key).expect("held"); for (column, value) in args["data"].as_object().into_iter().flatten() { row[column] = value.clone(); } versions.insert(key, at + 1); Reply::ok("{}") } Some("delete") if rows.remove(&key).is_none() => return Ok(Door::refusal(404, "no_such_record", &format!("no {table} {id}"))), Some("delete") if self.keeps_tombstones.load(Ordering::SeqCst) => { let at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); self.tombstones.lock().unwrap().insert(key, at); Reply::ok("{}") } _ => Reply::ok("{}"), }; *self.version.lock().unwrap() += 1; self.taken.lock().unwrap().push(body); if drop_after { return Err("the line dropped after the act landed".into()); } Ok(reply) }}impl Door { /// `restore { rows }`, as the Worker's: made when absent, the phone's /// version when not older, the object's otherwise; a refused table /// refuses the whole call and keeps nothing. fn restore(&self, body: Value, drop_after: bool) -> Result<Reply, String> { let rows = body["args"]["rows"].as_array().cloned().unwrap_or_default(); let refuses = self.refuses.lock().unwrap().clone(); if let Some(row) = rows.iter().find(|row| refuses.iter().any(|table| row["table"] == json!(table))) { return Ok(Door::refusal(400, "bad_column", &format!("{} takes nothing from this phone", row["table"].as_str().unwrap_or_default()))); } let mut held = self.rows.lock().unwrap(); let mut stamps = self.stamps.lock().unwrap(); let mut answered = Vec::new(); for row in &rows { let key = (row["table"].as_str().unwrap_or_default().to_string(), row["id"].as_str().unwrap_or_default().to_string()); let at = row["updated_at"].as_str().unwrap_or_default().to_string(); let landed = match held.get(&key) { None => { held.insert(key.clone(), row["data"].clone()); *self.restored.lock().unwrap().entry(key.1.clone()).or_insert(0) += 1; "made" } Some(_) if stamps.get(&key).is_some_and(|theirs| at < *theirs) => "standing", Some(data) if *data == row["data"] => "unchanged", Some(_) => { held.insert(key.clone(), row["data"].clone()); "written" } }; stamps.insert(key.clone(), at); answered.push(json!({"table": key.0, "id": key.1, "landed": landed})); } let mut version = self.version.lock().unwrap(); *version += 1; let said = json!({"version": *version, "changed": [], "restored": answered}); self.taken.lock().unwrap().push(body); if drop_after { return Err("the line dropped after the act landed".into()); } Ok(Reply::ok(&said.to_string())) }}impl Exchange for Door { fn send( &self, origin: &cotton_client::transport::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, ceiling: std::time::Duration, ) -> Result<Box<dyn cotton_client::transport::Answer>, String> { self.asked.lock().unwrap().push(request.path.to_string()); { let mut mid = self.mid_copy.lock().unwrap(); if mid.0.as_mut().is_some_and(|run| run()) { mid.0 = None; } } let reply = if request.path.starts_with("/v1/held") && !self.serves_held.load(Ordering::SeqCst) { Door::refusal(404, "not_found", "nothing answers GET /v1/held") } else if request.path.starts_with("/v1/held") { // One page per table asked, the next page's cursor naming the table after it: paged as the Worker pages. let query = request.path.split_once('?').map(|(_, query)| query).unwrap_or_default(); let named: Vec<String> = query.strip_prefix("tables=").or_else(|| query.strip_prefix("cursor=")).unwrap_or_default().split(',').map(str::to_string).collect(); let (table, rest) = named.split_first().expect("a table"); let live: Vec<String> = self.rows.lock().unwrap().keys().filter(|(held, _)| held == table).map(|(_, id)| id.clone()).collect(); let binned: Vec<String> = self.tombstones.lock().unwrap().keys().filter(|(held, _)| held == table).map(|(_, id)| id.clone()).collect(); let mut said = json!({"held": {table.as_str(): {"live": live, "binned": binned}}}); if !rest.is_empty() { said["next"] = json!(rest.join(",")); } Reply::ok(&said.to_string()) } else if request.path.starts_with("/v1/definitions") { // The kit's Todos, Books, Music, Cinemas and Money, as every object serves them: a copy draws only the tables its object serves. let todos = cotton_core::kit::package("todos").expect("the kit has Todos").expect("the package reads").package; let books = cotton_core::kit::package("books").expect("the kit has Books").expect("the package reads").package; let music = cotton_core::kit::package("music").expect("the kit has Music").expect("the package reads").package; let cinemas = cotton_core::kit::package("cinemas").expect("the kit has Cinemas").expect("the package reads").package; let money = cotton_core::kit::package("money").expect("the kit has Money").expect("the package reads").package; // Lists (record_group, group_member) are every personal object's own tables, served beside the apps'. let lists = [include_str!("../../../cotton-core/kits/personal/tables/record_group.json"), include_str!("../../../cotton-core/kits/personal/tables/group_member.json"), include_str!("../../../cotton-core/kits/personal/tables/site.json")].map(|file| serde_json::from_str::<Value>(file).expect("the kit's list tables")); let mut tables: Vec<Value> = todos.tables.iter().map(|table| json!(table)).chain(books.tables.iter().chain(&music.tables).chain(&cinemas.tables).chain(&money.tables).map(|table| json!(table))).chain(lists).collect(); let mut tools = vec![json!(todos.tool), json!(books.tool), json!(music.tool), json!(cinemas.tool), json!(money.tool)]; for id in self.also_serves.lock().unwrap().iter() { let package = cotton_core::kit::package(id).expect("the kit has the package").expect("the package reads").package; tables.extend(package.tables.iter().map(|table| json!(table))); tools.push(json!(package.tool)); } Reply::ok(&json!({"business": {"kind": "personal", "database_id": self.database, "timezone": "Asia/Kolkata"}, "tools": tools, "tables": tables, "boards": [], "flavour": {}, "etag": "e1"}).to_string()) } else if request.path.starts_with("/v1/sync") && request.path.contains("tables=seal_key") { // The seal keys (e2e rulings R1: todos are sealed), learned before a sealed row goes: this object's table key versions. let rows: Vec<Value> = ["todo", "todo_recurrence", "transaction", "evidence", "book", "highlight", "record_group", "group_member", "film", "film_season", "film_episode", "song", "music_album", "person", "person_handle", "person_note", "person_suggestion", "photo", "video", "face", "sighting", "event_attendee"].iter().map(|table| json!({"table": "seal_key", "id": format!("v:{table}"), "version": 1, "owner": null, "data": {"v": 1}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"})).collect(); Reply::ok(&json!({"version": *self.version.lock().unwrap(), "rows": rows, "server_time": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), "device": null}).to_string()) } else if request.path.starts_with("/v1/sync") && request.path.contains("tables=vault_key,vault_state") { // KEPT FOUR 2: whether the account has a vault, asked before an adopt sends anything: its vault rows. let rows: Vec<Value> = self .rows .lock() .unwrap() .iter() .filter(|((table, _), _)| table == "vault_key" || table == "vault_state") .map(|((table, id), data)| json!({"table": table, "id": id, "version": 2, "owner": null, "data": data, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"})) .collect(); Reply::ok(&json!({"version": *self.version.lock().unwrap(), "rows": rows, "server_time": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), "device": null}).to_string()) } else if request.path.starts_with("/v1/sync") && !self.pages.load(Ordering::SeqCst) { Door::refusal(503, "unavailable", "no page for this test") } else if request.path.starts_with("/v1/sync") { let rows: Vec<Value> = self .rows .lock() .unwrap() .iter() .map(|((table, id), data)| { let version = self.row_versions.lock().unwrap().get(&(table.clone(), id.clone())).copied().unwrap_or(2); json!({"table": table, "id": id, "version": version, "owner": null, "data": data, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"}) }) .chain(self.tombstones.lock().unwrap().iter().map(|((table, id), at)| { json!({"table": table, "id": id, "version": 2, "owner": null, "data": {}, "deleted": true, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": at}) })) .collect(); Reply::ok(&json!({"version": *self.version.lock().unwrap(), "rows": rows, "server_time": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), "device": null}).to_string()) } else if request.path.starts_with("/v1/rows?") { // `GET /v1/rows?table=&ids=`, as the Worker's rowsById: the live rows of those ids, deleted ones left out. let query = request.path.split_once('?').map(|(_, query)| query).unwrap_or_default(); let param = |name: &str| query.split('&').find_map(|pair| pair.strip_prefix(&format!("{name}="))).unwrap_or_default().to_string(); let (table, ids) = (param("table"), param("ids")); let rows: Vec<Value> = ids .split(',') .filter_map(|id| { let key = (table.clone(), id.to_string()); let data = self.rows.lock().unwrap().get(&key).cloned()?; let version = self.row_versions.lock().unwrap().get(&key).copied().unwrap_or(2); Some(json!({"table": table, "id": id, "version": version, "owner": null, "data": data, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"})) }) .collect(); Reply::ok(&json!({ "table": table, "rows": rows }).to_string()) } else if request.path.starts_with("/v1/act") { let body: Value = serde_json::from_slice(request.body.unwrap_or_default()).expect("an act's JSON"); self.act(body)? } else if request.path.starts_with("/v1/media/") && request.method == "GET" { self.fetched.lock().unwrap().push(request.path.to_string()); Door::refusal(404, "not_found", "no such media") } else if request.path.starts_with("/v1/media/") && request.method == "PUT" { self.media.lock().unwrap().push((request.path.to_string(), request.body.unwrap_or_default().to_vec())); Reply::json(201, r#"{"stored":true}"#) } else if request.path.starts_with("/v1/me") { Reply::ok(&json!({"person": {"id": OWNER, "phone": *self.phone.lock().unwrap(), "role": "owner"}, "version": *self.version.lock().unwrap()}).to_string()) } else { Reply::ok("{}") }; ScriptedExchange::new([reply]).send(origin, request, ceiling) } fn send_stream( &self, origin: &cotton_client::transport::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, body: &mut dyn std::io::Read, length: u64, ceiling: std::time::Duration, ) -> Result<Box<dyn cotton_client::transport::Answer>, String> { let mut bytes = Vec::new(); std::io::Read::read_to_end(&mut std::io::Read::take(body, length), &mut bytes).map_err(|error| error.to_string())?; let whole = cotton_client::transport::http1::Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request }; self.send(origin, &whole, ceiling) }}/// Back up: `personal.connect` over the used local database starts the/// adopt and answers at once; this waits for it to end and answers its status.fn back_up(handle: &CottonHandle, door: &Arc<Door>) -> (Value, Value) { let started = call_with(handle, "personal.connect", &ask(), Arc::clone(door) as Arc<dyn Exchange>).expect("answered"); if let Some(adopting) = handle.client().adopting() { adopting.join(); } (started, status(handle))}fn copy_count(handle: &CottonHandle, sql: &str) -> i64 { let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); copy.query_row(sql, [], |row| row.get(0)).expect("a count")}fn local_todos(handle: &CottonHandle) -> usize { let listed = crate::methods::dispatch(handle, "records.list", &json!({"table": "todo"})).expect("the todos"); listed["records"].as_array().map_or(0, Vec::len)}/// RULE (QUEUE BAD OP 6, H1): a photo filed after the adopt took its list of media and before the copy is made is an/// upload not done: the local database is kept aside, filed under the signed-in database, and the photo's only bytes/// go WITH it into its kept folder, never deleted with the local media folder.#[test]fn a_photo_filed_while_the_adopt_makes_the_copy_goes_with_the_kept_copy() { let (dir, handle) = phone(); let local = started_here(&handle); note(&handle, "An invented note"); picture(&handle, dir.path()); let door = Door::new(); let layout = handle.client().layout().clone(); let late_key = format!("{local}/late-invented.jpg"); let late_bytes = b"an invented picture filed while the copy was made".to_vec(); { let (layout, local, late_key, late_bytes) = (layout.clone(), local.clone(), late_key.clone(), late_bytes.clone()); door.mid_copy.lock().unwrap().0 = Some(Box::new(move || { // Once the adopt moved its media (the object's folder exists), and before the copy is made. if !layout.client_media_dir().join(DATABASE).exists() { return false; } let file = layout.client_media_dir().join(&local).join("late-invented.jpg"); std::fs::write(&file, &late_bytes).expect("the late photo's bytes"); let copy = rusqlite::Connection::open(layout.replica(&local)).expect("the local database"); copy.execute( "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, state, created_at, updated_at) VALUES (?1, ?2, 'abc', 'image/jpeg', 3, ?3, 'pending', '2026-11-27T09:00:00.000Z', '2026-11-27T09:00:00.000Z')", rusqlite::params![late_key, local, file.to_string_lossy()], ) .expect("its ledger row, pending"); true })); } let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert!(door.mid_copy.lock().unwrap().0.is_none(), "the photo was filed while the copy was made"); let kept = cotton_client::copy_keep::kept(&layout, Some(DATABASE)); assert_eq!(kept.len(), 1, "the local database is kept, under the signed-in database: {:?}", kept.iter().map(|kept| kept.state.why.clone()).collect::<Vec<_>>()); let listed = cotton_client::copy_keep::kept_changes(&layout, DATABASE); assert!(listed.iter().any(|change| change.op_id == format!("media:{late_key}")), "the upload not done is listed: {listed:?}"); let in_kept = kept[0].dir.join("media").join("late-invented.jpg"); assert_eq!(std::fs::read(&in_kept).ok(), Some(late_bytes), "its only bytes went with the kept copy"); assert!(!layout.client_media_dir().join(&local).exists(), "nothing of it is left where it stood"); // KEPT FOUR: what the account counts as waiting, the Sync page offers an act for; KEPT FOUR 2 (M4): only what is // true. A change kept from an adopt is never sent by recovery, so Send again is not offered for it. let said = crate::methods::shell_account::sync_said(&handle.client()); let acts: Vec<&str> = said["stuck"]["acts"].as_array().into_iter().flatten().filter_map(|act| act["id"].as_str()).collect(); assert_eq!(acts, ["let_go"], "what waits has its act, and only a true one: {said}"); // And the words offer only that act (Android, 28 Nov 2026): no "Send again" where it is not there. let detail = said["stuck"]["detail"].as_str().unwrap_or_default(); assert!(!detail.contains("Send") && detail.contains("let it go"), "{detail}");}/// RULE (owner, 1 Nov 2026): backup is adopt — a local database holding rows a person made in three tables and a picture is brought into a fresh object: every row lands once, under the object's media key; the picture's file moves to the copy's media folder and the drain puts it up; the copy is the object's (`connection.json` Remote), and the local database's folder is gone once it is connected.#[test]fn a_used_local_database_is_adopted_into_a_fresh_object() { let (dir, handle) = phone(); let local = started_here(&handle); for title in ["An invented errand", "Another invented errand", "A third invented errand"] { todo(&handle, title); } note(&handle, "An invented note"); let key = picture(&handle, dir.path()); assert!(key.starts_with(&format!("{local}/")), "a local picture is keyed by the local database: {key}"); let door = Door::new(); let (started, ended) = back_up(&handle, &door); assert_eq!(started, json!({"adopt": {"status": STARTED, "rows": 5}}), "connect answers at once with the rows it counted"); assert_eq!(ended, json!({"adopt": {"status": DONE, "sent": 5, "rows": 5, "refused": 0}})); assert_eq!((door.count("todo"), door.count("note"), door.count("photo")), (3, 1, 1), "every row lands: {:?}", door.taken.lock().unwrap()); assert!(door.creates().values().all(|n| *n == 1), "each row is created once: {:?}", door.creates()); let object_key = key.replacen(&local, DATABASE, 1); let photo = door.rows.lock().unwrap().iter().find(|((table, _), _)| table == "photo").map(|(_, data)| data.clone()).expect("the photo"); assert_eq!(photo["key"], json!(object_key), "the photo names the object's key"); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Remote, Some(DATABASE))); let layout = handle.client().layout().clone(); // QUEUE BAD OP 4: the local database leaves its place through the one function; what the adopt did not send (its // history receipts held for the clock) is kept aside whole, for recovery, never deleted. assert!(!layout.replica(&local).exists(), "the local database's place is free"); // QUEUE BAD OP 5 (item 1): what the adopt carried, and what its rule leaves (rows that are not the person's), do not // count: a local database it carried whole goes, and nothing is filed under the local id nobody reads. assert!(cotton_client::copy_keep::kept(&layout, Some(&local)).is_empty(), "nothing filed under the local id"); assert!(cotton_client::copy_keep::kept(&layout, Some(DATABASE)).is_empty(), "carried whole: nothing kept: {:?} {:?}", cotton_client::copy_keep::kept(&layout, Some(DATABASE)).iter().map(|kept| kept.state.why.clone()).collect::<Vec<_>>(), cotton_client::copy_keep::kept_changes(&layout, DATABASE)); assert!(!layout.client_media_dir().join(&local).exists(), "and its media folder"); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); // The file is in the copy's media folder, its ledger row the copy's, and the drain puts it up. let copy = cotton_store::driver::Driver::open(layout.replica(DATABASE)).expect("the copy"); let row = cotton_store::media_ledger::media_by_key(©, &object_key).expect("a read").expect("the ledger row is the copy's"); drop(copy); let file = std::path::PathBuf::from(row.local_path.expect("a path")); assert!(file.starts_with(layout.client_media_dir().join(DATABASE)) && file.is_file(), "the bytes stay on the phone, in the copy's folder: {}", file.display()); handle.client().wake_media_drain(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); while !door.media.lock().unwrap().iter().any(|(path, _)| path == &format!("/v1/media/{object_key}")) { assert!(std::time::Instant::now() < deadline, "the picture never went up: {:?}", door.media.lock().unwrap()); std::thread::sleep(std::time::Duration::from_millis(20)); } // A person's file goes up sealed (e2e rulings R6): an f1 file, never its plain bytes. let sent = door.media.lock().unwrap().iter().find(|(path, _)| path == &format!("/v1/media/{object_key}")).expect("the picture's upload").1.clone(); assert!(sent.starts_with(b"CTF1") && !sent.windows(b"an invented picture".len()).any(|w| w == b"an invented picture"), "the picture goes sealed"); // The copy is the object's: a pass brings the adopted rows down into it. handle.client().sync_now().expect("a pass"); assert_eq!(copy_count(&handle, "SELECT COUNT(*) FROM cotton_todos"), 3); assert_eq!(copy_count(&handle, "SELECT COUNT(*) FROM cotton_notes"), 1);}/// RULE: a kit table's rows (Books' book and highlight, kept in/// `cotton_<id>`) are a person's rows: a local database holding only books/// is adopted, never given way (the Books gaps walk, 5 Nov 2026: a book and/// a Goodreads shelf made before sign-in were left behind).#[test]fn books_made_before_sign_in_are_adopted() { let (dir, handle) = phone(); let local = started_here(&handle); // An EPUB brought in here is kept here, and stays kept under the object's key. let file = dir.path().join("an-invented-book.epub"); std::fs::write(&file, b"PK\x03\x04 an invented book").expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "capture.media", &json!({ "path": file.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "an-invented-book.epub", "book": {"format": "epub", "title": "An invented EPUB"}, })) .expect("the book captured"); let key = captured["key"].as_str().or(captured["answer"]["key"].as_str()).expect("its key").to_string(); let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": "book", "data": {"title": "An invented book", "status": "want_to_read"}})).expect("a book"); let book = made["record"]["id"].as_str().or(made["id"].as_str()).map(str::to_string).unwrap_or_else(|| panic!("a book id: {made}")); let kept = crate::methods::dispatch(&handle, "records.create", &json!({"table": "highlight", "data": {"book": book, "text": "An invented passage", "locator": "{}"}})).expect("a highlight"); let kept = kept["record"]["id"].as_str().or(kept["id"].as_str()).map(str::to_string).expect("its id"); // A highlight removed before sign-in stays removed (the walk's Remove came back live, 5 Nov 2026). let removed = crate::methods::dispatch(&handle, "records.create", &json!({"table": "highlight", "data": {"book": book, "text": "A passage taken back", "locator": "{}"}})).expect("a second highlight"); let removed = removed["record"]["id"].as_str().or(removed["id"].as_str()).map(str::to_string).expect("its id"); crate::methods::dispatch(&handle, "records.delete", &json!({"table": "highlight", "id": removed})).expect("removed"); let door = Door::new(); let (started, ended) = back_up(&handle, &door); assert_eq!(started, json!({"adopt": {"status": STARTED, "rows": 4}}), "the two books and both highlights are counted: the removed one goes, and its removal after it"); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); assert_eq!((door.count("book"), door.count("highlight")), (2, 1), "all land: {:?}", door.taken.lock().unwrap()); let object_key = key.replacen(&local, DATABASE, 1); let here = crate::methods::dispatch(&handle, "books.here.read", &json!({"key": object_key})).expect("what this phone keeps"); assert_eq!(here["state"], json!("kept"), "the EPUB stays kept on this phone: {here}"); // Signed in, a Remove reaches the object as its delete, never an update. handle.client().sync_now().expect("the copy takes the object's rows"); crate::methods::dispatch(&handle, "records.delete", &json!({"table": "highlight", "id": kept})).expect("removed once signed in"); handle.client().sync_now().expect("a pass"); assert_eq!(door.count("highlight"), 0, "the object puts it in its bin too: {:?}", door.taken.lock().unwrap());}/// RULE (list-acts walk, 7 Nov 2026: a removed list's Undo found nothing on a/// signed-in phone): a table whose map carries `deleted_at` keeps its bin at/// the object too — a removed list reaches the object as its mark, never its/// delete, so the object holds it binned and the Undo brings it back live.#[test]fn a_removed_list_waits_in_the_objects_bin_and_its_undo_brings_it_back() { let (_dir, handle) = phone(); started_here(&handle); let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": "book", "data": {"title": "An invented book", "status": "want_to_read"}})).expect("a book"); let book = made["record"]["id"].as_str().or(made["id"].as_str()).map(str::to_string).unwrap_or_else(|| panic!("a book id: {made}")); let list = crate::methods::dispatch(&handle, "groups.create", &json!({"table": "book", "name": "An invented list", "records": [book]})).expect("a list"); let list = list["group"]["id"].as_str().expect("its id").to_string(); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("the copy takes the object's rows"); let held = |door: &Door| door.rows.lock().unwrap().get(&("record_group".to_string(), list.clone())).cloned(); let removed = crate::methods::dispatch(&handle, "groups.delete", &json!({"id": list})).expect("removed"); handle.client().sync_now().expect("a pass"); let binned = held(&door).unwrap_or_else(|| panic!("the object keeps the list: {:?}", door.taken.lock().unwrap())); assert!(binned["deleted_at"].is_string(), "the object holds it in its bin: {binned}"); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("the removal undone"); handle.client().sync_now().expect("a pass"); let back = held(&door).expect("the object still holds the list"); assert!(back["deleted_at"].is_null(), "the object has it back live: {back}"); let listed = crate::methods::dispatch(&handle, "groups.list", &json!({"table": "book"})).expect("the lists"); assert!(listed.to_string().contains("An invented list"), "the phone shows it again: {listed}");}/// RULE (whole walk on Cotton Cinemas Dev, 8 Nov 2026: a film binned and/// undone came back counted in All but no longer a film): a table the object/// keeps no bin for takes the object's delete; its tombstone pulled back leaves/// the record in this copy's Bin (26 Nov 2026; before, the fold took it from/// this copy). Its Undo makes it again whole — every column as it was, whether a/// choice with a default was written or never named — here and at the object.#[test]fn a_record_of_a_table_with_no_bin_comes_back_whole_from_its_undo() { let (_dir, handle) = phone(); started_here(&handle); todo(&handle, "An invented todo"); let door = Door::new(); door.keeps_tombstones.store(true, Ordering::SeqCst); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("the copy takes the object's rows and tables"); let cinemas = cotton_core::kit::package("cinemas").expect("the kit has Cinemas").expect("the package reads").package; let film = cinemas.tables.iter().find(|table| table.id == "film").expect("the film table"); let columns: Vec<&str> = film.columns.iter().filter(|column| column.computed.is_none()).map(|column| column.key.as_str()).collect(); let kept = |data: &Value| -> serde_json::Map<String, Value> { columns.iter().map(|key| ((*key).to_string(), data.get(*key).cloned().filter(|value| !value.is_null()).unwrap_or(Value::Null))).collect() }; for data in [json!({"title": "An invented harbour"}), json!({"title": "An invented lighthouse", "kind": "film", "year": "2019"})] { let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": "film", "data": data})).expect("a film"); let id = made["record"]["id"].as_str().unwrap_or_else(|| panic!("a film id: {made}")).to_string(); handle.client().sync_now().expect("a pass"); let at_object = || door.rows.lock().unwrap().get(&("film".to_string(), id.clone())).cloned(); let here = || crate::methods::dispatch(&handle, "records.get", &json!({"table": "film", "id": id})).map(|got| got["data"].clone()); let object_was = kept(&at_object().unwrap_or_else(|| panic!("the object holds {data}"))); let here_was = kept(&here().expect("the phone holds it")); assert_eq!(here_was.get("kind"), Some(&json!("film")), "{data}: a film is a film here: {here_was:?}"); let removed = crate::methods::dispatch(&handle, "records.delete", &json!({"table": "film", "id": id})).expect("binned"); handle.client().sync_now().expect("a pass"); assert!(at_object().is_none(), "{data}: the object's delete took it"); // The tombstone pulled back leaves it in this copy's Bin (CINEMAS DEV PROOF, 26 Nov 2026): Put back and Empty // find it there. let bin = crate::methods::dispatch(&handle, "cinemas.bin", &json!({})).expect("the Bin"); assert!(bin.to_string().contains(data["title"].as_str().unwrap()), "{data}: still in this phone's Bin: {bin}"); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("the bin undone"); handle.client().sync_now().expect("a pass"); assert_eq!(kept(&here().expect("back on the phone")), here_was, "{data}: every column comes back here as it was"); assert_eq!(kept(&at_object().unwrap_or_else(|| panic!("{data}: back at the object"))), object_was, "{data}: every column comes back at the object as it was"); }}/// RULE (Books 1.0.0 (3) and (4) walks, 7 Nov 2026: Undo after a book's/// Remove was refused on a signed-in phone): a removed book waits in the/// object's bin as a list does — its mark reaches the object, never its/// delete — and the receipt's Undo brings it back live here and there. A book/// holding facts no person writes (a Goodreads import's `source` and/// `goodreads_id`) undoes all the same: a Remove and its Undo write the bin's/// mark alone.#[test]fn a_removed_book_waits_in_the_objects_bin_and_its_undo_brings_it_back() { let (_dir, handle) = phone(); started_here(&handle); let export = "Book Id,Title,Author,Exclusive Shelf\n9001,An Invented Book,An Invented Author,to-read\n"; crate::methods::dispatch(&handle, "object.act", &json!({"act": "import_goodreads", "file": export})).expect("imported before sign-in"); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("the copy takes the object's rows"); let book = door.rows.lock().unwrap().iter().find(|((table, _), data)| table == "book" && data["source"] == "goodreads").map(|((_, id), _)| id.clone()).expect("the object holds the imported book"); let held = |door: &Door| door.rows.lock().unwrap().get(&("book".to_string(), book.clone())).cloned(); assert_eq!(held(&door).expect("held")["source"], json!("goodreads"), "a fact no person writes"); let removed = crate::methods::dispatch(&handle, "records.delete", &json!({"table": "book", "id": book})).expect("removed"); assert_eq!(removed["change"]["undoable"], json!(true), "the receipt offers an Undo that will work: {removed}"); handle.client().sync_now().expect("a pass"); let binned = held(&door).unwrap_or_else(|| panic!("the object keeps the book: {:?}", door.taken.lock().unwrap())); assert!(binned["deleted_at"].is_string(), "the object holds it in its bin: {binned}"); handle.client().sync_now().expect("a second pass folds the object's row"); let bin = crate::methods::dispatch(&handle, "records.get", &json!({"table": "book", "id": book})); assert!(bin.is_err() || bin.as_ref().is_ok_and(|got| !got["deleted_at"].is_null()), "out of the deck here: {bin:?}"); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("the removal undone"); handle.client().sync_now().expect("a pass"); let back = held(&door).expect("the object still holds the book"); assert!(back["deleted_at"].is_null(), "the object has it back live: {back}"); assert_eq!(back["source"], json!("goodreads"), "its facts kept: {back}"); handle.client().sync_now().expect("a second pass"); let here = crate::methods::dispatch(&handle, "records.get", &json!({"table": "book", "id": book})).expect("the book is here again"); assert!(here["deleted_at"].is_null(), "live on the phone: {here}"); assert_eq!(here["data"]["title"], json!("An Invented Book"), "{here}");}/// A phone signed in to `door`, its first rows already taken from the object.fn signed_in(handle: &CottonHandle, door: &Arc<Door>) { started_here(handle); todo(handle, "An invented first errand"); let (_, ended) = back_up(handle, door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("the copy takes the object's rows");}/// A record made on the phone and carried to the object; answers its id.fn carried(handle: &CottonHandle, table: &str, data: Value) -> String { let made = crate::methods::dispatch(handle, "records.create", &json!({"table": table, "data": data})).unwrap_or_else(|error| panic!("a {table}: {error:?}")); let id = made["record"]["id"].as_str().unwrap_or_else(|| panic!("a {table} id: {made}")).to_string(); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("a second pass reads the row's version"); id}/// What the object holds in `column` of the row.fn at_object(door: &Door, table: &str, id: &str, column: &str) -> Value { let rows = door.rows.lock().unwrap(); let row = rows.get(&(table.to_string(), id.to_string())).unwrap_or_else(|| panic!("the object holds {table} {id}: {:?}", door.taken.lock().unwrap())); row.get(column).cloned().unwrap_or(Value::Null)}/// RULE (undo-after-columns, 18 Nov 2026): a change goes up as the columns it/// named, and the way out of the bin is one of them. A Remove, its Undo and a/// restore through the bin each reach the object, sealed table or plain, and/// the record stays out of the bin on the passes after.#[test]fn every_way_out_of_the_bin_reaches_the_object() { for (table, data) in [("note", json!({"title": "An invented note", "body": "Invented."})), ("todo", json!({"title": "An invented errand"}))] { let (_dir, handle) = phone(); let door = Door::new(); door.also_serves.lock().unwrap().push("notebook"); signed_in(&handle, &door); let id = carried(&handle, table, data); let removed = crate::methods::dispatch(&handle, "records.delete", &json!({"table": table, "id": id})).expect("removed"); handle.client().sync_now().expect("a pass"); assert!(at_object(&door, table, &id, "trashed_at").is_string(), "{table}: the object holds it in its bin"); handle.client().sync_now().expect("a second pass folds the object's row"); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("the removal undone"); handle.client().sync_now().expect("a pass"); assert!(at_object(&door, table, &id, "trashed_at").is_null(), "{table}: the Undo reaches the object"); handle.client().sync_now().expect("a second pass"); assert!(at_object(&door, table, &id, "trashed_at").is_null(), "{table}: it stays out of the bin"); crate::methods::dispatch(&handle, "records.get", &json!({"table": table, "id": id})).unwrap_or_else(|error| panic!("{table}: live on the phone: {error:?}")); crate::methods::dispatch(&handle, "records.delete", &json!({"table": table, "id": id})).expect("removed again"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("a second pass folds the object's row"); assert!(at_object(&door, table, &id, "trashed_at").is_string(), "{table}: in the object's bin again"); crate::methods::dispatch(&handle, "records.update", &json!({"table": "bin", "id": id, "patch": {"state": "restored"}})).expect("restored from the bin"); handle.client().sync_now().expect("a pass"); assert!(at_object(&door, table, &id, "trashed_at").is_null(), "{table}: the restore reaches the object"); handle.client().sync_now().expect("a second pass"); assert!(at_object(&door, table, &id, "trashed_at").is_null(), "{table}: it stays restored"); }}/// RULE (CINEMAS DEV PROOF, 26 Nov 2026): a film's bin lives on the phone only/// (the object's film table has no `deleted_at`), so the Bin reaches the object/// as its delete, and Undo there must bring the row back whole: an update of a/// deleted row finds nothing, so it goes as a create over the tombstone.#[test]fn undo_of_a_binned_film_brings_it_back_on_the_object() { let (_dir, handle) = phone(); let door = Door::new(); door.keeps_tombstones.store(true, Ordering::SeqCst); signed_in(&handle, &door); let file = format!("{}/films/invented/whole.mp4", door.database); let id = carried(&handle, "film", json!({"title": "Proof Ferry", "kind": "film", "status": "want_to_watch", "file": file})); let held = |door: &Door| door.rows.lock().unwrap().contains_key(&("film".to_string(), id.clone())); assert!(held(&door), "the film reached the object"); let removed = crate::methods::dispatch(&handle, "records.delete", &json!({"table": "film", "id": id})).expect("binned"); handle.client().sync_now().expect("a pass"); assert!(!held(&door), "in the Bin: the object deleted it"); handle.client().sync_now().expect("a second pass folds the tombstone"); let bin = crate::methods::dispatch(&handle, "cinemas.bin", &json!({})).expect("the Bin"); assert!(bin.to_string().contains("Proof Ferry"), "the object's tombstone leaves the film in this phone's Bin: {bin}"); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("undone"); handle.client().sync_now().expect("a pass"); assert!(held(&door), "Undo brings the film back on the object: {:?}", door.taken.lock().unwrap().iter().rev().take(3).collect::<Vec<_>>()); assert_eq!(at_object(&door, "film", &id, "file"), json!(file), "whole, with its file"); handle.client().sync_now().expect("a second pass"); assert!(held(&door), "and it stays"); crate::methods::dispatch(&handle, "records.get", &json!({"table": "film", "id": id})).unwrap_or_else(|error| panic!("live on the phone: {error:?}"));}/// RULE (undo-after-columns, 18 Nov 2026): putting a sealed note away and/// bringing it back each reach the object, and neither touches its words.#[test]fn an_archive_and_its_return_reach_the_object() { let (_dir, handle) = phone(); let door = Door::new(); door.also_serves.lock().unwrap().push("notebook"); signed_in(&handle, &door); let id = carried(&handle, "note", json!({"title": "An invented note", "body": "Invented."})); let sealed = at_object(&door, "note", &id, "sealed_enc"); assert!(sealed.is_string(), "the note is sealed at the object"); crate::methods::dispatch(&handle, "records.update", &json!({"table": "note", "id": id, "patch": {"archived_at": "2026-11-18T10:00:00.000Z"}})).expect("archived"); handle.client().sync_now().expect("a pass"); assert!(at_object(&door, "note", &id, "archived_at").is_string(), "the archive reaches the object"); handle.client().sync_now().expect("a second pass folds the object's row"); crate::methods::dispatch(&handle, "records.update", &json!({"table": "note", "id": id, "patch": {"archived_at": null}})).expect("brought back"); handle.client().sync_now().expect("a pass"); assert!(at_object(&door, "note", &id, "archived_at").is_null(), "the return reaches the object"); handle.client().sync_now().expect("a second pass"); assert!(at_object(&door, "note", &id, "archived_at").is_null(), "it stays back"); assert_eq!(at_object(&door, "note", &id, "sealed_enc"), sealed, "its words are as they were");}/// RULE (undo-after-columns, 18 Nov 2026): an Undo made before this copy read/// the Remove's version is refused as `version_moved`, waits for the pull and/// goes again: the book comes back, on the object and here.#[test]fn an_undo_over_a_version_this_copy_has_not_read_goes_again_after_the_pull() { let (_dir, handle) = phone(); let door = Door::new(); signed_in(&handle, &door); let book = carried(&handle, "book", json!({"title": "An invented book", "status": "want_to_read"})); door.pages.store(false, Ordering::SeqCst); let removed = crate::methods::dispatch(&handle, "records.delete", &json!({"table": "book", "id": book})).expect("removed"); let _unread = handle.client().sync_now(); assert!(at_object(&door, "book", &book, "deleted_at").is_string(), "the Remove landed and its version was never read here"); door.pages.store(true, Ordering::SeqCst); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("the removal undone"); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } assert!(at_object(&door, "book", &book, "deleted_at").is_null(), "the Undo went again over the newest version"); let here = crate::methods::dispatch(&handle, "records.get", &json!({"table": "book", "id": book})).expect("the book is here"); assert!(here["deleted_at"].is_null(), "live on the phone: {here}"); assert_eq!(here["data"]["title"], json!("An invented book"), "{here}");}/// RULE (undo-after-columns, 18 Nov 2026): a Remove and its Undo that go up in/// one pass leave the book live at the object.#[test]fn a_remove_and_its_undo_in_one_pass_leave_the_book_live() { let (_dir, handle) = phone(); let door = Door::new(); signed_in(&handle, &door); let book = carried(&handle, "book", json!({"title": "An invented book", "status": "want_to_read"})); let removed = crate::methods::dispatch(&handle, "records.delete", &json!({"table": "book", "id": book})).expect("removed"); crate::methods::dispatch(&handle, "records.undo", &json!({"change_id": removed["change"]["id"]})).expect("the removal undone"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("a second pass"); assert!(at_object(&door, "book", &book, "deleted_at").is_null(), "live at the object"); let here = crate::methods::dispatch(&handle, "records.get", &json!({"table": "book", "id": book})).expect("the book is here"); assert!(here["deleted_at"].is_null(), "live on the phone: {here}");}/// RULE (books-4-walk, 6 Nov 2026: on Android the same EPUB, added on a phone/// before sign-in and already in the object from another phone, became two/// books after sign-in): a book the object already holds by its file IS that/// book — the backup posts no second row, the object's version stands, and/// the phone's list and highlight made on it follow the object's book.#[test]fn a_book_the_object_holds_by_its_file_is_adopted_as_that_book() { let (dir, handle) = phone(); let local = started_here(&handle); let file = dir.path().join("an-invented-book.epub"); std::fs::write(&file, b"PK\x03\x04 an invented book").expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "capture.media", &json!({ "path": file.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "an-invented-book.epub", "book": {"format": "epub", "title": "An invented EPUB"}, })) .expect("the book captured"); let key = captured["key"].as_str().or(captured["answer"]["key"].as_str()).expect("its key").to_string(); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "book"})).expect("the books"); let here = listed["records"][0]["id"].as_str().map(str::to_string).unwrap_or_else(|| panic!("the book made here: {listed}")); let list = crate::methods::dispatch(&handle, "groups.create", &json!({"table": "book", "name": "An invented list", "records": [here]})).expect("a list made here"); let list = list["group"]["id"].as_str().expect("its id").to_string(); crate::methods::dispatch(&handle, "records.create", &json!({"table": "highlight", "data": {"book": here, "text": "An invented passage", "locator": "{}"}})).expect("a highlight"); // The other phone's book: the same file, finished there. let theirs = "a0000000-0000-4000-8000-00000000b00c"; let object_key = key.replacen(&local, DATABASE, 1); let door = Door::new().holding("book", theirs, json!({"title": "An invented EPUB", "status": "finished", "format": "epub", "file": object_key})); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); assert_eq!(ended["adopt"]["refused"], json!(0), "the book is the object's, nothing refused: {ended}"); assert_eq!(door.count("book"), 1, "no second book: {:?}", door.taken.lock().unwrap()); assert_eq!(door.rows.lock().unwrap()[&("book".to_string(), theirs.to_string())]["status"], json!("finished"), "the object's version stands"); let rows = door.rows.lock().unwrap().clone(); let taken = door.taken.lock().unwrap().clone(); let member = rows.iter().find(|((table, _), data)| table == "group_member" && data["group"] == json!(list)).map(|(_, data)| data.clone()); assert_eq!(member.map(|data| data["record_id"].clone()), Some(json!(theirs)), "the list holds the object's book: {taken:?}"); let passage = rows.iter().find(|((table, _), _)| table == "highlight").map(|(_, data)| data["book"].clone()); assert_eq!(passage, Some(json!(theirs)), "the highlight is on the object's book: {taken:?}"); handle.client().sync_now().expect("a pass"); assert_eq!(copy_count(&handle, "SELECT COUNT(*) FROM cotton_book"), 1, "the copy holds one book");}/// RULE (books-android-leftovers walk, 6 Nov 2026: a book finished and rated/// on a phone before sign-in, already in the object as Want to read, came back/// Want to read): what the person did to a book here after adding it — read/// it, finished it, rated it — lands on the object's book by its file; the/// object's own create (its title) stands.#[test]fn what_was_done_to_a_book_the_object_holds_by_its_file_lands_on_that_book() { let (dir, handle) = phone(); let local = started_here(&handle); let file = dir.path().join("an-invented-book.epub"); std::fs::write(&file, b"PK\x03\x04 an invented book").expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "capture.media", &json!({ "path": file.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "an-invented-book.epub", "book": {"format": "epub", "title": "An invented EPUB"}, })) .expect("the book captured"); let key = captured["key"].as_str().or(captured["answer"]["key"].as_str()).expect("its key").to_string(); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "book"})).expect("the books"); let here = listed["records"][0]["id"].as_str().map(str::to_string).unwrap_or_else(|| panic!("the book made here: {listed}")); crate::methods::dispatch(&handle, "records.update", &json!({"table": "book", "id": here, "patch": {"status": "finished", "rating": 4}})).expect("finished and rated here"); let theirs = "a0000000-0000-4000-8000-00000000b00d"; let object_key = key.replacen(&local, DATABASE, 1); let door = Door::new().holding("book", theirs, json!({"title": "The object's own title", "status": "want_to_read", "format": "epub", "file": object_key})); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); assert_eq!(ended["adopt"]["refused"], json!(0), "nothing refused: {ended}"); assert_eq!(door.count("book"), 1, "no second book: {:?}", door.taken.lock().unwrap()); let book = door.rows.lock().unwrap()[&("book".to_string(), theirs.to_string())].clone(); assert_eq!(book["status"], json!("finished"), "finished here, finished there: {book}"); // Books are sealed (16 Nov 2026): the rating goes inside the seal, never in the clear, and the phone's copy holds it. assert!(book["sealed_enc"].is_string() && book.get("rating").is_none(), "the rating goes sealed: {book}"); handle.client().sync_now().expect("the copy takes the object's book"); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "book"})).expect("the books here"); let mine = listed["records"].as_array().and_then(|all| all.iter().find(|r| r["id"] == theirs)).cloned().unwrap_or_else(|| panic!("the object's book here: {listed}")); assert_eq!(mine["data"]["rating"], json!(4), "rated here, rated there: {mine}"); // A sealed table takes no clear patch (object_adopt.rs): the row as it stands here goes up whole, sealed under // the object's id, so the phone's title rides with it. Opening the object's row first, so its own title stands, is still to do (report.md). assert_eq!(mine["data"]["title"], json!("An invented EPUB"), "the row goes whole, sealed: {mine}");}/// RULE: a song this phone brought in is kept here and plays from its file,/// before sign-in and after it: the backup re-keys its keep with its file, so/// the player never asks the object for bytes this phone holds (the Music/// gaps lane, 5 Nov 2026: songs streamed once signed in).#[test]#[ignore = "TABLE DROP 1: the music tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"]fn songs_brought_in_before_sign_in_stay_kept_after_it() { let (dir, handle) = phone(); let local = started_here(&handle); let file = dir.path().join("01 Low Tide.mp3"); std::fs::write(&file, b"ID3 an invented song, not a real one").expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "music.capture", &json!({"songs": [{ "path": file.to_string_lossy(), "sourcePath": "Ana Vell/Harbour Lights/01 Low Tide.mp3", "tags": {"title": "Low Tide", "artist": "Ana Vell", "album": "Harbour Lights", "duration": 181.0}, }]})) .expect("the song captured"); let key = captured["songs"][0]["key"].as_str().unwrap_or_else(|| panic!("its key: {captured}")).to_string(); let here = |key: &str| crate::methods::dispatch(&handle, "songs.here.read", &json!({"key": key})).expect("what this phone keeps")["state"].clone(); let path = |key: &str| crate::methods::dispatch(&handle, "read.mediaPath", &json!({"args": {"key": key}})).expect("where its bytes are")["path"].clone(); assert_eq!(here(&key), json!("kept"), "brought in here, so kept here"); assert!(path(&key).as_str().is_some_and(|at| std::path::Path::new(at).is_file()), "its file is on this phone: {}", path(&key)); let (_, ended) = back_up(&handle, &Door::new()); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); let object_key = key.replacen(&local, DATABASE, 1); assert_eq!(here(&object_key), json!("kept"), "the song stays kept under the object's key"); assert!(path(&object_key).as_str().is_some_and(|at| std::path::Path::new(at).is_file()), "and plays from its file here: {}", path(&object_key));}/// RULE: a film this phone brought in is kept here before sign-in and after/// it: the backup re-keys its keep with its file, so On this phone still lists/// it and weighs it (the Cinemas walk, 5 Nov 2026: 0 films on this phone/// after a backup).#[test]fn films_brought_in_before_sign_in_stay_kept_after_it() { let (dir, handle) = phone(); let local = started_here(&handle); let bytes: &[u8] = b"invented whole film bytes, not a real film"; let file = dir.path().join("Night Ferry (2019).mp4"); std::fs::write(&file, bytes).expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "films.capture", &json!({"films": [{ "path": file.to_string_lossy(), "sourcePath": "Night Ferry (2019).mp4", "minutes": 101.4, "video": "avc1", "audio": "mp4a", "height": 1080, "bitrate": 4200, }]})) .expect("the film captured"); let key = captured["films"][0]["key"].as_str().unwrap_or_else(|| panic!("its key: {captured}")).to_string(); let here = |key: &str| crate::methods::dispatch(&handle, "films.here.read", &json!({"key": key})).expect("what this phone keeps")["state"].clone(); let on_phone = || crate::methods::dispatch(&handle, "films.onPhone", &json!({})).expect("On this phone's counts"); assert_eq!(here(&key), json!("kept"), "brought in here, so kept here"); assert_eq!(on_phone()["films"], json!(1), "{}", on_phone()); let (_, ended) = back_up(&handle, &Door::new()); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); let object_key = key.replacen(&local, DATABASE, 1); assert_ne!(object_key, key, "the backup re-keys the film's file"); assert_eq!(here(&object_key), json!("kept"), "the film stays kept under the object's key"); handle.client().sync_now().expect("the copy takes the object's rows"); assert_eq!(on_phone(), json!({"films": 1, "episodes": 0, "bytes": bytes.len()}), "On this phone lists and weighs it still");}/// RULE: backing up into an object that already has rows (the number had a Cotton) keeps both: the object's rows stand and the adopted rows join them, and the copy holds all of them.#[test]fn adopting_into_an_object_that_has_rows_keeps_both() { let (_dir, handle) = phone(); started_here(&handle); todo(&handle, "An invented errand made on this phone"); todo(&handle, "Another one made on this phone"); let door = Door::new() .holding("todo", "a0000000-0000-4000-8000-000000000001", json!({"title": "An invented errand the object had", "status": "open"})) .holding("todo", "a0000000-0000-4000-8000-000000000002", json!({"title": "Another the object had", "status": "open"})); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(door.count("todo"), 4, "the object's two and the phone's two"); handle.client().sync_now().expect("a pass"); assert_eq!(copy_count(&handle, "SELECT COUNT(*) FROM cotton_todos"), 4, "the copy shows all four");}/// RULE: an adopt killed part way — the app gone after the object took an act and before its answer came — resumes on the next backup from the receipts still unsent: every row is created at the object once, the one in flight is taken as this phone's own, and nothing is sent twice.#[test]fn an_adopt_killed_part_way_resumes_and_sends_nothing_twice() { let (_dir, handle) = phone(); let local = started_here(&handle); let made: Vec<String> = (0..6).map(|n| todo(&handle, &format!("Invented errand {n}"))).collect(); let door = Door::new(); *door.budget.lock().unwrap() = Some((3, Drop::After)); let (_, stopped) = back_up(&handle, &door); assert_eq!(stopped["adopt"]["status"], FAILED, "{stopped}"); assert_eq!(door.count("todo"), 4, "three answered and one landed unheard"); let layout = handle.client().layout().clone(); assert!(layout.replica(&local).exists(), "the local database is kept whole"); assert_eq!(connection_of(&handle).and_then(|mine| mine.workspace_id).as_deref(), Some(local.as_str())); assert_eq!(crate::phone::personal_object::made_rows(&layout.replica(&local)).expect("counted"), 3, "the three answered are marked sent in the local database"); *door.budget.lock().unwrap() = None; let (again, ended) = back_up(&handle, &door); assert_eq!(again["adopt"]["rows"], 6, "the rows counted when the adopt began: {again}"); assert_eq!(ended, json!({"adopt": {"status": DONE, "sent": 6, "rows": 6, "refused": 0}}), "{:?}", cotton_client::unsent::discarded(&layout, DATABASE)); assert_eq!(door.count("todo"), 6); let creates = door.creates(); for id in &made { assert_eq!(creates.get(id), Some(&1), "{id} is created once at the door: {creates:?}"); } assert!(cotton_client::unsent::discarded(&layout, DATABASE).is_empty(), "nothing was written down as lost");}/// RULE: a dropped line stops the adopt `failed` with the object's line — the local database whole, every row still on the phone — and backing up again (Try again) finishes it.#[test]fn a_dropped_line_fails_with_the_local_database_whole_and_try_again_finishes() { let (_dir, handle) = phone(); let local = started_here(&handle); for n in 0..4 { todo(&handle, &format!("Invented errand {n}")); } let door = Door::new(); *door.budget.lock().unwrap() = Some((2, Drop::Before)); let (_, stopped) = back_up(&handle, &door); assert_eq!(stopped["adopt"]["status"], FAILED); assert_eq!(stopped["adopt"]["sent"], 2, "{stopped}"); assert_eq!(stopped["adopt"]["rows"], 4); assert_eq!(stopped["adopt"]["code"], "offline"); // An object that did not answer keeps its own words in the log; the screen says the kit's line for `offline` (942c404d9). assert!(stopped["adopt"].get("line").is_none(), "the object's words stay off the screen: {stopped}"); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Local, Some(local.as_str())), "the phone stands on its own database"); assert_eq!(local_todos(&handle), 4, "every row is still on the phone"); *door.budget.lock().unwrap() = None; let (_, ended) = back_up(&handle, &door); assert_eq!(ended, json!({"adopt": {"status": DONE, "sent": 4, "rows": 4, "refused": 0}})); assert_eq!(door.count("todo"), 4); assert!(door.creates().values().all(|n| *n == 1));}/// RULE: a write the object refuses for good is written down (filed in Feedback once the copy opens) and counted refused, never lost silently; the adopt goes on and the rest land.#[test]fn a_refused_write_is_written_down_and_counted() { let (_dir, handle) = phone(); started_here(&handle); todo(&handle, "An invented errand"); note(&handle, "An invented note the object refuses"); let door = Door::new(); door.refuses.lock().unwrap().push("note".into()); let (_, ended) = back_up(&handle, &door); assert_eq!(ended, json!({"adopt": {"status": DONE, "sent": 1, "rows": 2, "refused": 1}})); assert_eq!(door.count("todo"), 1); let written = cotton_client::unsent::discarded(handle.client().layout(), DATABASE); let notes: Vec<_> = written.iter().flat_map(|entry| entry.changes.iter()).filter(|change| change.table == "cotton_notes").collect(); assert_eq!(notes.len(), 1, "the note is written down: {written:?}"); assert!(written.iter().any(|entry| entry.why == cotton_client::transport::object::ADOPT_DISCARDED_WHY && entry.reasons.values().any(|why| why.contains("takes nothing"))), "{written:?}");}/// RULE: a local row whose id the object already holds is not overwritten — the object's version stands, and the phone's write is counted refused with that reason.#[test]fn a_local_row_the_object_holds_keeps_the_objects_version() { let (_dir, handle) = phone(); started_here(&handle); let id = todo(&handle, "The phone's version"); let door = Door::new().holding("todo", &id, json!({"title": "The object's version", "status": "open"})); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["refused"], 1, "{ended} {:?}", cotton_client::unsent::discarded(handle.client().layout(), DATABASE)); assert_eq!(door.rows.lock().unwrap()[&("todo".to_string(), id.clone())]["title"], "The object's version"); let written = cotton_client::unsent::discarded(handle.client().layout(), DATABASE); assert!(written.iter().any(|entry| entry.reasons.values().any(|why| why == cotton_client::transport::object::OBJECT_STANDS)), "{written:?}");}/// RULE: `personal.adoptStatus` answers `{adopt: {status, sent, rows, refused}}` — `none` before any adopt this launch — and a failed one names the object's word and line.#[test]fn adopt_status_says_where_it_stands() { let (_dir, handle) = phone(); assert_eq!(call_with(&handle, "personal.adoptStatus", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("a status"), json!({"adopt": {"status": NONE, "sent": 0, "rows": 0, "refused": 0}})); started_here(&handle); todo(&handle, "An invented errand"); let door = Door::new(); *door.budget.lock().unwrap() = Some((0, Drop::Before)); back_up(&handle, &door); let said = call_with(&handle, "personal.adoptStatus", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("a status"); let mut keys: Vec<&str> = said["adopt"].as_object().expect("an object").keys().map(String::as_str).collect(); keys.sort_unstable(); // A dropped line is `offline`, whose words stay in the log (942c404d9): no `line`. assert_eq!(keys, ["code", "refused", "rows", "sent", "status"], "{said}"); assert_eq!(said["adopt"]["status"], FAILED);}/// A fresh install's launch: the shell publishes this phone's vault key, which founds the local database's vault and/// its one person (`founding::local_personal`), as `vault.publishKey` does before anyone signs in.fn founded_here(handle: &CottonHandle, local: &str) { let public = base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, cotton_core::vault::wrap::public_of(&[7u8; 32])); crate::phone::founding::local_personal(&handle.client(), &public).expect("founded"); let held = cotton_client::copy_keep::changes_in(&handle.client().layout().replica(local)).expect("the local copy reads"); let tables: std::collections::BTreeSet<&str> = held.iter().map(|change| change.table.as_str()).collect(); for table in ["cotton_admissions", "cotton_device_statements", "cotton_person_keys", "cotton_vault_state"] { assert!(tables.contains(table), "the founding holds a {table} row for the server: {tables:?}"); }}/// What the signed-in database would say waits to sync of the copies kept under it.fn kept_waiting(handle: &CottonHandle) -> Vec<String> { cotton_client::copy_keep::kept_changes(handle.client().layout(), DATABASE).into_iter().map(|change| format!("{} {} {}", change.place, change.table, change.op_id)).collect()}/// RULE (KEPT FOUR, Android walk 27 Nov 2026, 2 of 2): fresh install, use, sign in, the adopt path. The local/// database's founding (its admission, its device statement, its person key, its vault) is that database's own/// identity: the signed-in database has its own, so they are never carried into it and never kept or counted as the/// person's unsent work. Nothing is kept, and nothing says it waits to sync.#[test]fn a_fresh_install_used_then_signed_in_keeps_nothing_of_its_founding() { let (_dir, handle) = phone(); let local = started_here(&handle); founded_here(&handle, &local); note(&handle, "An invented note"); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); // KEPT FOUR 2 (decision a): a first-ever sign-in, so the local vault key founds the account (its wrap goes up); // the rest of the founding is the local database's own and never goes. let tables: std::collections::BTreeSet<String> = door.rows.lock().unwrap().keys().map(|(table, _)| table.clone()).collect(); assert!(tables.contains("vault_key"), "the local key founds the account: {tables:?}"); assert!(tables.iter().all(|table| !table.contains("admission") && !table.contains("person_key") && table != "vault_state" && !table.contains("device_statement")), "the rest of the founding never goes: {tables:?}"); assert_eq!(kept_waiting(&handle), Vec::<String>::new(), "nothing waits to sync"); assert!(cotton_client::copy_keep::kept(handle.client().layout(), Some(DATABASE)).is_empty(), "nothing is kept"); assert!(crate::methods::shell_account::sync_said(&handle.client())["stuck"].is_null(), "and the Sync page says nothing is stuck");}/// RULE (KEPT FOUR, KEPT FOUR 2): fresh install, sign in, the join path. Into a first-ever account the local vault key/// founds it (decision a: its wrap goes up, as it always did, and no row is counted for it); into an account with a/// vault nothing goes and the local database gives way. Either way nothing of it is kept or counted.#[test]fn a_fresh_install_signed_in_keeps_nothing_of_its_founding() { let (_dir, handle) = phone(); let local = started_here(&handle); founded_here(&handle, &local); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended, json!({"adopt": {"status": DONE, "sent": 0, "rows": 0, "refused": 0}}), "no row of the person's is counted for the founding"); assert!(door.rows.lock().unwrap().keys().any(|(table, _)| table == "vault_key"), "the local key founds the account"); assert!(!handle.client().layout().replica(&local).exists()); assert_eq!(kept_waiting(&handle), Vec::<String>::new(), "nothing waits to sync"); assert!(cotton_client::copy_keep::kept(handle.client().layout(), Some(DATABASE)).is_empty(), "nothing is kept"); assert!(crate::methods::shell_account::sync_said(&handle.client())["stuck"].is_null(), "and the Sync page says nothing is stuck");}/// RULE: a fresh local database (nothing a person made) gives way to the object's copy without an adopt.#[test]fn a_fresh_local_database_gives_way_without_an_adopt() { let (_dir, handle) = phone(); let local = started_here(&handle); let answer = call_with(&handle, "personal.connect", &ask(), Door::new() as Arc<dyn Exchange>).expect("connected"); assert_eq!(answer["databaseId"], DATABASE, "{answer}"); assert!(handle.client().adopting().is_none(), "no adopt ran"); assert!(!handle.client().layout().replica(&local).exists());}/// RULE: Stop backing up and signing in again with the same number connects the kept copy without an adopt, and a row made while it stood local goes up through the loop.#[test]fn stopping_backup_then_signing_in_again_adopts_nothing() { let (_dir, handle) = phone(); let door = Door::new(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("connected"); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let id = todo(&handle, "An invented errand made while standing local"); let again = call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("connected again"); assert_eq!(again["databaseId"], DATABASE, "no adopt: {again}"); assert!(handle.client().adopting().is_none()); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } let path = handle.client().layout().replica(DATABASE); assert!(door.rows.lock().unwrap().contains_key(&("todo".to_string(), id)), "the row went up through the loop: {:?} {:?}", door.taken.lock().unwrap(), cotton_client::unsent::unsent_changes(&path));}/// RULE: a definition changed before backup is posted after rows; the object's refusal is counted and written down verbatim.#[test]fn a_definition_changed_before_backup_is_sent_and_its_refusal_is_written_down() { let (_dir, handle) = phone(); started_here(&handle); todo(&handle, "An invented errand"); crate::methods::dispatch(&handle, "tools.remove", &json!({"tool_id": "cinemas"})).expect("the tool is removed here"); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(ended["adopt"]["sent"], 1, "the definition goes uncounted beside the rows: {ended}"); assert_eq!(ended["adopt"]["refused"], 1, "{ended}"); let written = cotton_client::unsent::discarded(handle.client().layout(), DATABASE); assert!(written.iter().any(|entry| entry.reasons.values().any(|why| why == "the kit keeps this tool")), "{written:?}");}/// RULE (coordinator, 1 Nov 2026): what the app writes for itself as it runs — usage counts, an act's history (`cotton_changes`), which device holds a file — is no row a person made: an adopt never posts it, and it stays with the local database.#[test]fn the_apps_own_rows_stay_with_the_local_database() { let (_dir, handle) = phone(); let local = started_here(&handle); todo(&handle, "An invented errand"); let path = handle.client().layout().replica(&local); let unsent = cotton_client::unsent::unsent_changes(&path).expect("unsent"); assert!(unsent.iter().any(|change| change.table == "cotton_changes"), "a write keeps its history beside it: {unsent:?}"); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended, json!({"adopt": {"status": DONE, "sent": 1, "rows": 1, "refused": 0}})); let taken = rows_taken(&door); assert_eq!(taken.len(), 1, "one act, the todo's: {taken:?}"); assert_eq!(taken[0]["args"]["table"], "todo");}// ── restore-from-phone (10 Nov 2026): a former object's copy goes whole ─────/// The object the phone's copy was pulled from, deleted since.const FORMER: &str = "a0a0a0a0-0000-4000-8000-0000000f0e01";fn ask_for(database: &str) -> Value { let mut asked = ask(); asked["databaseId"] = json!(database); asked}/// The former object holding `n` invented todos, a project and a todo in it.fn former_object(n: usize) -> Arc<Door> { let mut door = Door::of(FORMER).holding("project", "proj-invented-1", json!({"name": "An invented project", "slug": "an-invented-project"})); for i in 0..n { door = door.holding("todo", &format!("todo-invented-{i:04}"), json!({"title": format!("Invented errand {i}"), "status": "open"})); } door.holding("todo", "todo-invented-in-project", json!({"title": "An errand of the project", "status": "open", "project": "proj-invented-1"}))}/// This phone signed in to the former object, its copy pulled whole, and a/// todo made here delivered: a copy holding no unsent write.fn pulled_from(handle: &CottonHandle, former: &Arc<Door>) -> String { call_with(handle, "personal.connect", &ask_for(FORMER), Arc::clone(former) as Arc<dyn Exchange>).expect("connected to the former object"); let mine = todo(handle, "An invented errand made on this phone"); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } let path = handle.client().layout().replica(FORMER); assert!(cotton_client::unsent::unsent_changes(&path).expect("unsent").iter().all(|change| change.table != "cotton_todos"), "the todo made here is delivered"); mine}fn copy_todos(handle: &CottonHandle, database: &str) -> i64 { let copy = rusqlite::Connection::open(handle.client().layout().replica(database)).expect("a copy"); copy.query_row("SELECT COUNT(*) FROM cotton_todos", [], |row| row.get(0)).expect("a count")}/// Back up into `door`, watching that the former copy stands while any act lands.fn restore_into(handle: &CottonHandle, door: &Arc<Door>) -> (Value, Value) { *door.watched.lock().unwrap() = Some(handle.client().layout().replica(FORMER)); back_up(handle, door)}fn assert_whole(handle: &CottonHandle, door: &Arc<Door>, rows: usize, ended: &Value) { assert_eq!(ended["adopt"]["status"], DONE, "{ended} {:?}", cotton_client::unsent::discarded(handle.client().layout(), DATABASE)); assert_eq!((ended["adopt"]["sent"].as_u64(), ended["adopt"]["refused"].as_u64()), (Some(ended["adopt"]["rows"].as_u64().unwrap()), Some(0)), "{ended}"); assert_eq!(door.count("todo"), rows, "every live todo is in the new object"); assert_eq!(door.count("project"), 1, "and its project"); assert!(door.restored.lock().unwrap().values().all(|n| *n == 1), "each row is made once: {:?}", door.restored.lock().unwrap()); assert_eq!(copy_todos(handle, DATABASE), rows as i64, "the new copy holds every todo"); let mine = connection_of(handle).expect("a connection"); assert_eq!((mine.mode, mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Remote, Some(DATABASE))); assert!(!door.went_early.load(Ordering::SeqCst), "the former copy stood while the object took every row"); assert!(!handle.client().layout().replica(FORMER).parent().expect("a folder").exists(), "the former copy goes, at the end");}/// RULE (restore-from-phone, owner, 10 Nov 2026): a copy pulled from an object that is gone, standing local and holding no unsent write, signed in to a new empty object: every live row goes whole — pulled and delivered alike, parents before children, ids kept — the new copy holds them all, and the old copy goes only once it does.#[test]fn a_former_objects_copy_standing_local_goes_whole_into_a_new_object() { let (_dir, handle) = phone(); let former = former_object(5); let mine = pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); let (started, ended) = restore_into(&handle, &door); assert_eq!(started["adopt"]["rows"], 8, "five todos, the project's todo, the one made here and the project: {started}"); assert_whole(&handle, &door, 7, &ended); assert!(door.rows.lock().unwrap().contains_key(&("todo".to_string(), mine)), "the todo made on this phone, delivered, goes too"); let order: Vec<String> = door.taken.lock().unwrap().iter().filter(|act| act["act"] == "restore").flat_map(|act| act["args"]["rows"].as_array().cloned().unwrap_or_default()).map(|row| row["table"].as_str().unwrap_or_default().to_string()).collect(); let project = order.iter().position(|table| table == "project").expect("the project went"); assert!(order.iter().position(|table| table == "todo").expect("todos went") > project, "the project lands before the todos naming it: {order:?}");}/// RULE (owner's phone, 12 Nov 2026: one call of his backup ran out of time and the whole backup stopped, the card reading Signed out): an object that does not answer a call is asked again, half as many rows a call, and the backup goes on; every row lands once and the former copy goes only at the end.#[test]fn an_object_too_slow_for_a_big_call_is_asked_again_with_fewer_rows_and_the_backup_finishes() { let (_dir, handle) = phone(); let former = former_object(450); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); *door.answers_at_most.lock().unwrap() = Some(60); let (_, ended) = restore_into(&handle, &door); assert_whole(&handle, &door, 452, &ended); assert_eq!(*door.unanswered.lock().unwrap(), 2, "200 rows and 100 went unanswered, 50 a call landed"); let sizes: Vec<usize> = door.taken.lock().unwrap().iter().filter(|act| act["act"] == "restore").map(|act| act["args"]["rows"].as_array().map_or(0, Vec::len)).collect(); assert!(sizes.iter().all(|rows| *rows <= 50), "every call that landed carried at most 50 rows: {sizes:?}");}/// RULE (owner, 12 Nov 2026): a former copy is never deleted while it holds a live row in a table that did not go up. Every table this build names goes up, the app's kit or not; a table nothing names stays behind, so the old copy is kept, the phone signed in on its new copy, and the Account card names the table and how many rows. Its rows gone, the next sign-in removes it.#[test]fn a_former_copy_holding_rows_that_did_not_go_up_is_kept_and_the_card_names_the_table() { let (_dir, handle) = todos_kit_phone(); let former = former_object(5); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let old = handle.client().layout().replica(FORMER); { let copy = rusqlite::Connection::open(&old).expect("the former copy"); // A note is no table of the Todos kit; the keepsakes are a table no build names. copy.execute_batch( "CREATE TABLE cotton_invented_keepsakes (id TEXT PRIMARY KEY, title TEXT); INSERT INTO cotton_invented_keepsakes (id, title) VALUES ('k1', 'An invented keepsake'), ('k2', 'Another');", ) .expect("a table an earlier build kept"); } let door = Door::new(); let (_, ended) = restore_into(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert!(old.exists(), "the old copy is kept"); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Remote, Some(DATABASE)), "signed in on the new copy"); let card = crate::methods::dispatch(&handle, "shell.account", &json!({})).expect("shell.account"); let said = card["card"]["facts"].as_array().expect("facts").iter().find(|fact| fact["label"] == "Last error").map(|fact| fact["said"].as_str().unwrap_or_default().to_string()).unwrap_or_default(); assert!(said.contains("cotton_invented_keepsakes (2 items)"), "the card names the table and its rows: {card}"); rusqlite::Connection::open(&old).expect("the former copy").execute_batch("DELETE FROM cotton_invented_keepsakes").expect("emptied"); finish_left(&Phone::of(&handle), DATABASE); for _ in 0..100 { if !old.exists() { break } std::thread::sleep(std::time::Duration::from_millis(50)); } assert!(!old.exists(), "holding nothing that did not go up, the old copy goes");}/// RULE (owner's phone, 12 Nov 2026): a backup call that fails says which it was: the tables its rows were of, how many it carried and the seconds it waited, on the card and in the log.#[test]fn a_backup_call_that_gets_no_answer_is_named_with_its_tables_rows_and_seconds() { let (_dir, handle) = phone(); let former = former_object(5); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); *door.answers_at_most.lock().unwrap() = Some(0); let (_, stopped) = restore_into(&handle, &door); // Since 942c404d9 the call's own words (its tables, items and seconds) stay in the log, and the card says the kit's line for its code. assert_eq!(stopped["adopt"]["code"], "offline", "{stopped}"); assert!(stopped["adopt"].get("line").is_none(), "the object's words stay off the screen: {stopped}");}/// RULE: an object that answers nothing at all ends the backup once patience runs out, the former copy whole and the card saying the backup stopped, never Signed out; signing in again finishes it.#[test]fn an_object_that_never_answers_stops_the_backup_with_the_copy_whole_and_the_card_says_so() { let (_dir, handle) = phone(); let former = former_object(5); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); *door.answers_at_most.lock().unwrap() = Some(0); let (_, stopped) = restore_into(&handle, &door); assert_eq!(stopped["adopt"]["status"], FAILED, "{stopped}"); assert_eq!(*door.unanswered.lock().unwrap(), cotton_client::transport::object::RESTORE_PATIENCE as usize + 1, "asked again while patience lasted"); assert!(handle.client().layout().replica(FORMER).exists(), "the old copy is kept whole"); assert_eq!(copy_todos(&handle, FORMER), 7, "every row is still on the phone"); let card = crate::methods::dispatch(&handle, "shell.account", &json!({})).expect("shell.account"); assert_eq!(card["card"]["subtitle"], "Your data is safe on this phone. Sign in again to finish syncing it.", "{card}"); assert_eq!(card["line"], "Not synced yet", "{card}"); *door.answers_at_most.lock().unwrap() = None; let (_, ended) = restore_into(&handle, &door); assert_whole(&handle, &door, 7, &ended);}/// RULE: a copy still Remote, naming an object other than the one this sign-in answered, is never left behind: it stands local and goes whole the same way.#[test]fn a_remote_copy_of_another_object_goes_whole_into_the_new_one() { let (_dir, handle) = phone(); let former = former_object(3); pulled_from(&handle, &former); let door = Door::new(); let (_, ended) = restore_into(&handle, &door); assert_whole(&handle, &door, 5, &ended);}/// RULE: a restore stopped part way — a call that landed unheard — fails with the old copy whole, and backing up again sends only what is left: every row made once, nothing lost.#[test]fn a_whole_restore_stopped_part_way_resumes_and_makes_nothing_twice() { let (_dir, handle) = phone(); let former = former_object(250); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); *door.budget.lock().unwrap() = Some((1, Drop::After)); let (_, stopped) = restore_into(&handle, &door); assert_eq!(stopped["adopt"]["status"], FAILED, "{stopped}"); assert_eq!(stopped["adopt"]["sent"], cotton_client::transport::object::RESTORE_BATCH as u64, "the first call was answered: {stopped}"); assert!(handle.client().layout().replica(FORMER).exists(), "the old copy is kept whole"); assert_eq!(connection_of(&handle).and_then(|mine| mine.workspace_id).as_deref(), Some(FORMER)); *door.budget.lock().unwrap() = None; let (again, ended) = restore_into(&handle, &door); assert_eq!(again["adopt"]["rows"], 253, "{again}"); assert_whole(&handle, &door, 252, &ended); let calls = door.taken.lock().unwrap().iter().filter(|act| act["act"] == "restore").count(); assert_eq!(calls, 3 + cotton_client::transport::object::RESTORE_PATIENCE as usize, "two calls, the second asked again while patience lasted (each landing unheard, none made twice), then only what was left");}/// RULE: a row the object refuses for good is written down and counted refused; the rest land, and the old copy still goes once they are in.#[test]fn a_restored_row_the_object_refuses_is_written_down_and_counted() { let (_dir, handle) = phone(); let former = former_object(2); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); door.refuses.lock().unwrap().push("project".into()); let (_, ended) = restore_into(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(ended["adopt"]["refused"], 1, "the project: {ended}"); let written = cotton_client::unsent::discarded(handle.client().layout(), DATABASE); assert!(written.iter().any(|entry| entry.why == cotton_client::transport::object::ADOPT_DISCARDED_WHY && entry.reasons.values().any(|why| why.contains("takes nothing"))), "{written:?}");}/// RULE (restore-from-phone, Cinemas first, 10 Nov 2026): a film this phone downloaded, in a former object's copy, stays on the phone through the restore: it stays kept under the new object's key, its ledger row names the same bytes in the new copy's folder, it is neither put up again nor fetched again, and the player plays it from the file, never a stream.#[test]fn a_downloaded_film_still_plays_from_the_phone_after_a_whole_restore() { let (dir, handle) = phone(); let former = Door::of(FORMER); call_with(&handle, "personal.connect", &ask_for(FORMER), Arc::clone(&former) as Arc<dyn Exchange>).expect("connected to the former object"); let bytes: &[u8] = b"invented whole film bytes, not a real film"; let file = dir.path().join("Night Ferry (2019).mp4"); std::fs::write(&file, bytes).expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "films.capture", &json!({"films": [{ "path": file.to_string_lossy(), "sourcePath": "Night Ferry (2019).mp4", "minutes": 101.4, "video": "avc1", "audio": "mp4a", "height": 1080, "bitrate": 4200, }]})) .expect("the film captured"); let key = captured["films"][0]["key"].as_str().unwrap_or_else(|| panic!("its key: {captured}")).to_string(); assert!(key.starts_with(&format!("{FORMER}/films/")), "{key}"); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } handle.client().wake_media_drain(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); while !former.media.lock().unwrap().iter().any(|(path, _)| path == &format!("/v1/media/{key}")) { assert!(std::time::Instant::now() < deadline, "the film never went up to the former object: {:?}", former.media.lock().unwrap().iter().map(|(path, _)| path.clone()).collect::<Vec<_>>()); std::thread::sleep(std::time::Duration::from_millis(20)); } let film_id = former.rows.lock().unwrap().iter().find(|((table, _), _)| table == "film").map(|((_, id), _)| id.clone()).expect("the film row is the former object's"); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let here = |key: &str| crate::methods::dispatch(&handle, "films.here.read", &json!({"key": key})).expect("what this phone keeps")["state"].clone(); assert_eq!(here(&key), json!("kept")); let played = crate::methods::dispatch(&handle, "shell.player", &json!({"op": "play", "table": "film", "id": film_id})).expect("played signed out"); assert_eq!((played["now"]["file"].as_str(), played["now"].get("stream")), (Some(key.as_str()), None), "signed out, a downloaded film plays from its file: {played}"); let door = Door::new(); let (_, ended) = restore_into(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); let object_key = key.replacen(FORMER, DATABASE, 1); assert_eq!(door.rows.lock().unwrap()[&("film".to_string(), film_id.clone())]["file"], json!(object_key), "the film's row names the new object's key"); assert_eq!(here(&object_key), json!("kept"), "kept under the new key"); let layout = handle.client().layout().clone(); let copy = cotton_store::driver::Driver::open(layout.replica(DATABASE)).expect("the new copy"); let row = cotton_store::media_ledger::media_by_key(©, &object_key).expect("a read").expect("the ledger row is the new copy's"); drop(copy); assert_ne!(row.state, "pending", "the ledger says it is stored: it is not put up again"); let kept = std::path::PathBuf::from(row.local_path.expect("a path")); assert_eq!(std::fs::read(&kept).expect("the bytes are still on the phone"), bytes); assert!(!layout.replica(FORMER).parent().expect("a folder").exists(), "the former copy goes"); handle.client().wake_media_drain(); std::thread::sleep(std::time::Duration::from_millis(500)); assert!(door.media.lock().unwrap().is_empty(), "nothing is put up again: {:?}", door.media.lock().unwrap().iter().map(|(path, _)| path.clone()).collect::<Vec<_>>()); assert!(door.fetched.lock().unwrap().iter().all(|path| !path.contains("/films/")), "nor fetched again: {:?}", door.fetched.lock().unwrap()); let played = crate::methods::dispatch(&handle, "shell.player", &json!({"op": "play", "table": "film", "id": film_id})).expect("played"); assert_eq!((played["now"]["file"].as_str(), played["now"].get("stream")), (Some(object_key.as_str()), None), "it plays from the phone: {played}"); assert_eq!(crate::methods::dispatch(&handle, "films.onPhone", &json!({})).expect("counts"), json!({"films": 1, "episodes": 0, "bytes": bytes.len()}));}/// A phone on the todos kit (`kits/todos`), whose one tool lays the Account/// card's acts: the manifest the Todos app shipped, kept here as data since/// that app left the tree (22 Nov 2026). Days' kit starts on its calendar, so/// its Account card is not the shell's one-tool card these tests read.const TODOS_KIT_MANIFEST: &str = r#"{"genesis":"personal","flavour":"todos","name":"Todos","ground":"baizeTeal","databases":"single","database":"personal","business":{"server":{"real":"https://cottondb.com","dev":"https://dev.example.invalid"}},"fan":{"home":false,"tools":false,"opens":"todos"},"kit":"todos"}"#;fn todos_kit_phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(serde_json::from_str(TODOS_KIT_MANIFEST).expect("the todos kit's manifest")), }) .expect("an open core"); holds_the_data_keys(&handle); (dir, handle)}fn home(handle: &CottonHandle) -> Value { crate::methods::dispatch(handle, "shell.home", &json!({})).expect("shell.home")}/// The Account card, as the core answers it.fn account(handle: &CottonHandle) -> Value { crate::methods::dispatch(handle, "shell.account", &json!({"commit": "abc1234"})).expect("shell.account")}/// The acts standing on the Account card, by their words.fn account_acts(handle: &CottonHandle) -> Vec<String> { account(handle)["actions"].as_array().expect("actions").iter().filter_map(|act| act["label"].as_str().map(str::to_string)).collect()}/// The acts a held Todos card offers on Today, by their words.fn held_acts(handle: &CottonHandle) -> Vec<String> { let answer = crate::methods::dispatch(handle, "tools.acts", &json!({"table": "todo", "view": "todos/today"})).expect("tools.acts"); answer["actions"].as_array().expect("actions").iter().filter_map(|act| act["label"].as_str().map(str::to_string)).collect()}fn facts(card: &Value) -> Vec<(String, String)> { card["card"]["facts"].as_array().expect("facts").iter().map(|fact| (fact["label"].as_str().unwrap_or_default().to_string(), fact["said"].as_str().unwrap_or_default().to_string())).collect()}/// RULE (owner, 11 Nov 2026): sign-in lives on the Account card, never on a held card's acts. Signed out, the card says so on its tile and its face, names the app and its build, the phone's own database, nothing synced, the rows here, no error, and offers Sign in alone; signed in, it says who by name, the database by the first eight of its id and the Worker's host, and offers Back up now and Sign out. Nothing on it is the number or the credential, and a held todo offers no account act either way.#[test]fn the_account_card_says_where_this_phone_stands_and_holds_its_acts() { let (_dir, handle) = todos_kit_phone(); let local = started_here(&handle); todo(&handle, "An invented errand"); let out = account(&handle); assert_eq!((out["key"].as_str(), out["name"].as_str(), out["line"].as_str(), out["stand"].as_str()), (Some("account"), Some("Account"), Some("Signed out"), Some("local")), "{out}"); assert_eq!(out["card"]["subtitle"], "Signed out"); let said = facts(&out); assert_eq!(said.iter().map(|(label, _)| label.as_str()).collect::<Vec<_>>(), ["App", "Account", "Synced", "Waiting to sync", "Items on this phone", "Last error"]); assert!(said[0].1.starts_with("Todos ") && said[0].1.ends_with("abc1234"), "the app and its build: {said:?}"); assert_eq!(said[1].1, format!("{} · this phone only", &local[..8])); assert_eq!((said[2].1.as_str(), said[5].1.as_str()), ("Not yet", "None")); assert_eq!(account_acts(&handle), ["Sign in"]); assert!(held_acts(&handle).iter().all(|act| !["Sign in", "Sync now", "Sign out"].contains(&act.as_str())), "a held todo offers no account act: {:?}", held_acts(&handle)); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); handle.client().sync_now().expect("a pass"); let signed = account(&handle); assert_eq!(signed["stand"], "connected", "{signed}"); assert!(signed["line"].as_str().is_some_and(|line| line.starts_with("Synced ") || line == "Signed in"), "{signed}"); assert!(signed["card"]["subtitle"].as_str().is_some_and(|who| who.starts_with("Signed in")), "{signed}"); assert_eq!(facts(&signed)[1].1, format!("{} · cotton.example.com", &DATABASE[..8])); assert_eq!(account_acts(&handle), ["Sync now", "Sign out"]); assert!(held_acts(&handle).iter().all(|act| !["Sign in", "Sync now", "Sign out"].contains(&act.as_str()))); let whole = signed.to_string(); assert!(!whole.contains("synthetic-credential") && !whole.contains("+1"), "no credential and no number on the card: {whole}");}/// RULE (signin-sticks, the owner's phone, 11 Nov 2026: the object took the sign-in, the phone kept the credential, stayed signed out and said nothing): a connect the object took the sign-in for and this phone did not finish is said — `shell.home` stands failed with a line naming why, through a stand-local, until a connect takes or the person signs out — and Sign in still stands on the card to try again.#[test]fn a_sign_in_this_phone_did_not_finish_is_said_until_one_takes() { let (_dir, handle) = todos_kit_phone(); started_here(&handle); assert_eq!(home(&handle)["stand"], "local"); // The object answers as something this phone cannot keep a copy of. let not_personal = ScriptedExchange::new([Reply::ok(r#"{"business":{"kind":"shop","database_id":"a0a0a0a0-0000-4000-8000-00000000ad09"}}"#)]); let refused = call_with(&handle, "personal.connect", &ask(), not_personal as Arc<dyn Exchange>).expect_err("refused"); assert_eq!(refused.code, "not_personal"); // The app stands the phone local after a refusal, and it is still said. call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let said = home(&handle); assert_eq!(said["stand"], "failed", "{said}"); let line = said["backup"]["line"].as_str().unwrap_or_default(); assert!(line.contains("not your personal database"), "the line says why: {line}"); assert_eq!(account_acts(&handle), ["Sign in"], "Sign in stands to try again"); let card = account(&handle); assert_eq!(card["line"], "Not syncing", "{card}"); assert!(facts(&card)[5].1.contains("not your personal database"), "the last error is on the card with its time: {card}"); assert_eq!(card["trouble"], json!(true), "a sign-in that did not finish: a screen says plainly that it cannot reach Cotton: {card}"); // A connect that takes ends it. let (_, ended) = back_up(&handle, &Door::new()); assert_eq!(ended["adopt"]["status"], NONE, "an empty local database gives way: {ended}"); assert_eq!(home(&handle)["stand"], "connected"); assert_eq!(account_acts(&handle), ["Sync now", "Sign out"]); assert_eq!(account(&handle)["trouble"], json!(false), "a connect that took is no trouble");}/// RULE (signin-sticks, 11 Nov 2026; one copy, one object, 14 Nov 2026): a restore the object stopped answering part way stands failed with the object's line, Sign in standing on the card to take it up again; signing out forgets it, the old copy is set aside whole and the phone stands local on a fresh database with nothing left to say; signing in again takes the old copy back and the restore goes on.#[test]fn a_restore_that_failed_is_said_and_sign_out_forgets_it() { let (_dir, handle) = todos_kit_phone(); let former = former_object(250); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); *door.budget.lock().unwrap() = Some((1, Drop::After)); let (_, stopped) = restore_into(&handle, &door); assert_eq!(stopped["adopt"]["status"], FAILED, "{stopped}"); let said = home(&handle); assert_eq!(said["stand"], "failed", "{said}"); assert!(!said["backup"]["line"].as_str().unwrap_or_default().is_empty(), "the failure is said: {said}"); assert_eq!(account_acts(&handle), ["Sign in"], "Sign in stands to take the restore up again"); call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("signed out"); let after = home(&handle); assert_eq!(after["stand"], "local", "{after}"); assert_ne!(connection_of(&handle).and_then(|mine| mine.workspace_id).as_deref(), Some(FORMER), "the old copy is not drawn"); assert!(crate::phone::copy_aside::is_aside(handle.client().layout(), FORMER), "the old copy is kept whole, aside"); // Signed in again, the restore goes on from what is left and ends whole. *door.budget.lock().unwrap() = None; let (_, ended) = restore_into(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert!(door.restored.lock().unwrap().values().all(|n| *n == 1), "each row is made once"); assert_eq!(home(&handle)["stand"], "connected"); assert_eq!(account_acts(&handle), ["Sync now", "Sign out"]);}/// The `restore` acts the object took since `from`, as the ids of the todos they carried.fn restored_todos(door: &Door, from: usize) -> Vec<String> { door.taken.lock().unwrap()[from..].iter().filter(|act| act["act"] == "restore") .flat_map(|act| act["args"]["rows"].as_array().cloned().unwrap_or_default()) .filter(|row| row["table"] == "todo").filter_map(|row| row["id"].as_str().map(str::to_string)).collect()}/// RULE (owner, 11 Nov 2026: "a phone copy is never trusted as only a cache"): at sign-in and at every Back up now the phone asks the object what it holds and sends every live row it lacks, whatever the database id and whatever the copy's cursor, receipts or log say was sent. The same id's object, emptied, gets every row back; one holding some gets only the missing; a row the object binned is not made again; a second run sends nothing; and the Account card says how many rows went up.#[test]fn the_object_gets_every_row_it_lacks_whatever_the_copy_says_was_sent() { every_row_it_lacks_goes_up(false);}/// RULE (topup-ids, 11 Nov 2026): an object that answers which ids it holds is asked by ids alone, never pulled whole, and every rule of the top-up holds the same.#[test]fn an_object_that_answers_its_ids_is_never_pulled_whole_by_a_top_up() { every_row_it_lacks_goes_up(true);}/// RULE (topup-ids, 11 Nov 2026): a phone asks an object older than `GET /v1/held` by the whole pull, once it answers 404, and tops it up the same.#[test]fn an_object_older_than_the_ids_route_is_asked_by_the_whole_pull() { let (_dir, handle) = todos_kit_phone(); started_here(&handle); let id = todo(&handle, "An invented errand"); let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); // The new copy pulls its todo down before the object is emptied, as its sibling's does. handle.client().sync_now().expect("a pass"); door.rows.lock().unwrap().clear(); door.asked.lock().unwrap().clear(); let from = door.taken.lock().unwrap().len(); let went = top_up(&Phone::of(&handle), &ask(), Arc::clone(&door) as Arc<dyn Exchange>).unwrap_or_else(|refused| panic!("a top-up: {} ({})", refused.message, refused.code)); assert!(went.sent >= 1 && went.refused == 0, "{went:?}"); assert_eq!(restored_todos(&door, from), [id]); let asked = door.asked.lock().unwrap().clone(); let held = asked.iter().position(|path| path.starts_with("/v1/held?tables=")).unwrap_or_else(|| panic!("the ids asked first: {asked:?}")); assert!(asked[held..].iter().any(|path| path.starts_with("/v1/sync?since=0&tables=")), "then the whole pull: {asked:?}");}/// The rule of [`the_object_gets_every_row_it_lacks_whatever_the_copy_says_was_sent`], against an object that answers `GET /v1/held` (`ids`) or one older than it.fn every_row_it_lacks_goes_up(ids: bool) { let (_dir, handle) = todos_kit_phone(); started_here(&handle); let ids_of: Vec<String> = ["An invented errand", "A second invented errand", "A third invented errand"].iter().map(|title| todo(&handle, title)).collect(); let door = Door::new(); door.keeps_tombstones.store(true, Ordering::SeqCst); door.serves_held.store(ids, Ordering::SeqCst); let pulled_whole = |door: &Door| door.asked.lock().unwrap().iter().any(|path| path.starts_with("/v1/sync?since=0&tables=")); let ids = ids_of; let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); handle.client().sync_now().expect("a pass"); assert_eq!(door.count("todo"), 3, "the object holds the three"); let phone = Phone::of(&handle); door.asked.lock().unwrap().clear(); let run = || top_up(&phone, &ask(), Arc::clone(&door) as Arc<dyn Exchange>).unwrap_or_else(|refused| panic!("a top-up: {} ({})", refused.message, refused.code)); // Signed in and caught up: nothing is lacking, nothing is sent. let from = door.taken.lock().unwrap().len(); assert_eq!(run(), ToppedUp { sent: 0, refused: 0 }); assert!(restored_todos(&door, from).is_empty(), "nothing lacking, nothing sent"); // THE SAME ID, EMPTIED: the object founded again under this database's id holds nothing. door.rows.lock().unwrap().clear(); let from = door.taken.lock().unwrap().len(); let went = run(); let mut sent = restored_todos(&door, from); sent.sort(); let mut wanted = ids.clone(); wanted.sort(); assert_eq!(sent, wanted, "every todo goes back up"); assert!(went.sent >= 3 && went.refused == 0, "{went:?}"); assert_eq!(door.count("todo"), 3); assert_eq!(local_todos(&handle), 3, "and this phone keeps them"); // A SECOND RUN SENDS NOTHING. let from = door.taken.lock().unwrap().len(); assert_eq!(run(), ToppedUp { sent: 0, refused: 0 }); assert_eq!(door.taken.lock().unwrap().len(), from, "no act at all"); // HOLDING SOME: only the missing row goes. door.rows.lock().unwrap().remove(&("todo".to_string(), ids[0].clone())); let from = door.taken.lock().unwrap().len(); assert_eq!(run(), ToppedUp { sent: 1, refused: 0 }); assert_eq!(restored_todos(&door, from), [ids[0].clone()]); // BINNED ON THE OBJECT: its tombstone wins; the row is not made again. door.rows.lock().unwrap().remove(&("todo".to_string(), ids[1].clone())); door.tombstones.lock().unwrap().insert(("todo".to_string(), ids[1].clone()), "2026-11-11T09:00:00.000Z".to_string()); let from = door.taken.lock().unwrap().len(); assert_eq!(run(), ToppedUp { sent: 0, refused: 0 }); assert!(restored_todos(&door, from).is_empty(), "a binned row is not resurrected"); assert_eq!(door.count("todo"), 2); // BACK UP NOW (`personal.connect {topUp}`): the Account card says what went up. door.rows.lock().unwrap().remove(&("todo".to_string(), ids[2].clone())); let mut asked = ask(); asked["topUp"] = json!(true); call_with(&handle, "personal.connect", &asked, Arc::clone(&door) as Arc<dyn Exchange>).expect("connected"); for _ in 0..600 { if !handle.client().topping_up() && handle.client().topped_up().is_some() { break } std::thread::sleep(std::time::Duration::from_millis(50)); } assert_eq!(handle.client().topped_up().map(|(sent, refused, _)| (sent, refused)), Some((1, 0))); assert_eq!(door.count("todo"), 2, "the third is back, the binned one is not"); let said = facts(&account(&handle)); let line = said.iter().find(|(label, _)| label == "Saved to your account").unwrap_or_else(|| panic!("the card says what went up: {said:?}")); assert!(line.1.starts_with("1 item ("), "{line:?}"); assert_eq!(pulled_whole(&door), !door.serves_held.load(Ordering::SeqCst), "pulled whole only by an object without the ids route: {:?}", door.asked.lock().unwrap());}// ── one copy, one object (signout-keeps-rows, 14 Nov 2026) ──────────────────//// Books Dev on one simulator: B signed out, A signed in with another number,// and A's Want to read showed B's books — B's copy, kept as the local// database at sign-out, was restored whole into A's object. A copy that has// ever been signed in belongs to its object: another person's sign-in never// adopts, merges or sends it; sign-out takes it out of what the app draws./// B's object: another person's number, holding two invented todos.const PERSON_B: &str = "a0a0a0a0-0000-4000-8000-0000000b0b02";fn person_b() -> Arc<Door> { Door::of(PERSON_B) .of_person("+919000000002") .holding("todo", "todo-of-b-1", json!({"title": "An errand of B's", "status": "open"})) .holding("todo", "todo-of-b-2", json!({"title": "Another errand of B's", "status": "open"}))}/// Person A's object, empty: the number A signs in with is not B's.fn person_a() -> Arc<Door> { Door::new().of_person("+919000000001")}/// The todos the app draws, after the passes a signed-in phone runs (a/// signed-out one has no far end, and a pass changes nothing).fn drawn_todos(handle: &CottonHandle) -> Vec<String> { for _ in 0..3 { let _ = handle.client().sync_now(); } let listed = crate::methods::dispatch(handle, "records.list", &json!({"table": "todo"})).expect("the todos"); listed["records"].as_array().into_iter().flatten().filter_map(|record| record["data"]["title"].as_str().or(record["title"].as_str()).map(str::to_string)).collect()}fn sign_out(handle: &CottonHandle) -> Value { call_with(handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("signed out")}/// Sign in to `door` as its object, waiting for any adopt to end.fn sign_in_to(handle: &CottonHandle, door: &Arc<Door>, database: &str) -> Value { let answer = call_with(handle, "personal.connect", &ask_for(database), Arc::clone(door) as Arc<dyn Exchange>).expect("connected"); if let Some(adopting) = handle.client().adopting() { adopting.join(); } answer}/// Every row an act or a restore put into `door`.fn sent_into(door: &Arc<Door>) -> Vec<Value> { rows_taken(door)}/// Every act the object took but a phone handing it the arrival key's/// public half (e2e rulings R2), which a phone holding the data key does/// once: no row of anyone's.fn rows_taken(door: &Arc<Door>) -> Vec<Value> { door.taken.lock().unwrap().iter().filter(|act| !(act["args"]["table"] == "seal_key" && act["args"]["id"] == "arrival")).cloned().collect()}/// RULE (coordinator, 14 Nov 2026): B signs in, makes a todo, signs out; A signs in on the same phone with another number: nothing of B's copy reaches A's object — no act, no restore — and A's deck draws none of B's rows.#[test]fn a_second_person_signing_in_gets_none_of_the_first_persons_rows() { let (_dir, handle) = phone(); let b = person_b(); sign_in_to(&handle, &b, PERSON_B); todo(&handle, "An errand B made on this phone"); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } assert_eq!(drawn_todos(&handle).len(), 3, "B sees B's rows"); sign_out(&handle); let a = person_a(); let answer = sign_in_to(&handle, &a, DATABASE); assert_eq!(answer["databaseId"], DATABASE, "A connects to A's object at once, no adopt: {answer}"); assert!(sent_into(&a).is_empty(), "nothing of B's went into A's object: {:?}", sent_into(&a)); assert_eq!(a.count("todo"), 0); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } assert!(sent_into(&a).is_empty(), "nor by a pass: {:?}", sent_into(&a)); assert_eq!(drawn_todos(&handle), Vec::<String>::new(), "A's deck draws none of B's rows"); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Remote, Some(DATABASE)));}/// RULE (coordinator, 14 Nov 2026): a copy still connected to B's object (no sign-out, the app killed) is never sent into A's when A signs in with another number: it is set aside, and A gets a fresh copy.#[test]fn a_copy_still_connected_to_another_persons_object_is_set_aside_never_sent() { let (_dir, handle) = phone(); let b = person_b(); sign_in_to(&handle, &b, PERSON_B); let a = person_a(); let answer = sign_in_to(&handle, &a, DATABASE); assert_eq!(answer["databaseId"], DATABASE, "{answer}"); assert!(sent_into(&a).is_empty(), "{:?}", sent_into(&a)); assert_eq!(drawn_todos(&handle), Vec::<String>::new()); assert!(!handle.client().layout().replica(PERSON_B).exists(), "B's copy is no longer where the app opens copies");}/// RULE (coordinator, 14 Nov 2026): signing out takes the person's rows out of what the app draws: the phone stands on a fresh local database of its own, and B's copy is nowhere a read reaches.#[test]fn signing_out_takes_the_persons_rows_out_of_what_the_app_draws() { let (_dir, handle) = phone(); let b = person_b(); sign_in_to(&handle, &b, PERSON_B); assert_eq!(drawn_todos(&handle).len(), 2); let said = sign_out(&handle); assert_eq!(drawn_todos(&handle), Vec::<String>::new(), "nothing of B's is drawn"); let mine = connection_of(&handle).expect("a fresh local database"); assert_eq!(mine.mode, cotton_client::connection::ConnectionMode::Local); assert_ne!(mine.workspace_id.as_deref(), Some(PERSON_B), "{said}"); assert!(!handle.client().layout().replica(PERSON_B).exists(), "B's copy is set aside"); let home = crate::methods::dispatch(&handle, "shell.account", &json!({})).expect("shell.account"); assert!(!home.to_string().contains(&PERSON_B[..8]), "the Account card names nothing of B's database: {home}");}/// RULE (coordinator, 14 Nov 2026): a write B made and never sent waits in B's copy set aside: it never goes to A's object, and goes to B's when B signs in again, B's rows drawn again at once.#[test]fn an_unsent_write_waits_for_its_own_person_and_goes_when_they_sign_in_again() { let (_dir, handle) = phone(); let b = person_b(); sign_in_to(&handle, &b, PERSON_B); let unsent = todo(&handle, "An errand B never sent"); sign_out(&handle); let a = person_a(); sign_in_to(&handle, &a, DATABASE); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } assert!(sent_into(&a).is_empty(), "{:?}", sent_into(&a)); sign_out(&handle); let answer = sign_in_to(&handle, &b, PERSON_B); assert_eq!(answer["databaseId"], PERSON_B, "{answer}"); assert_eq!(drawn_todos(&handle).len(), 3, "B's rows, and the one never sent, are drawn again"); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } assert!(b.rows.lock().unwrap().contains_key(&("todo".to_string(), unsent)), "the write B never sent went to B's object: {:?}", sent_into(&b)); assert!(sent_into(&a).is_empty(), "and still nothing to A's");}/// RULE (owner, 1 Nov 2026, kept): a database this phone started that was never signed in is adopted at its first sign-in — here a database made after B signed out: the rows made in it go to A's object, and none of B's.#[test]fn a_database_never_signed_in_is_still_adopted_at_its_first_sign_in() { let (_dir, handle) = phone(); let b = person_b(); sign_in_to(&handle, &b, PERSON_B); sign_out(&handle); let mine = todo(&handle, "An errand made before A signed in"); let a = person_a(); sign_in_to(&handle, &a, DATABASE); let ended = status(&handle); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(ended["adopt"]["sent"], 1, "{ended}"); let held: Vec<String> = a.rows.lock().unwrap().keys().filter(|(table, _)| table == "todo").map(|(_, id)| id.clone()).collect(); assert_eq!(held, vec![mine], "the one row made here, none of B's"); assert_eq!(drawn_todos(&handle), vec!["An errand made before A signed in".to_string()]);}/// RULE (coordinator, 14 Nov 2026): a film kept on the phone follows its copy: once B signs out it is no longer on this phone for anyone, its bytes kept aside with B's copy; B signing in again finds it kept, and plays it from the file.#[test]fn a_film_kept_on_the_phone_follows_its_copy() { let (dir, handle) = phone(); let b = person_b(); sign_in_to(&handle, &b, PERSON_B); let bytes: &[u8] = b"invented film bytes, not a real film"; let file = dir.path().join("An Invented Ferry (2019).mp4"); std::fs::write(&file, bytes).expect("a synthetic file"); let captured = crate::methods::dispatch(&handle, "films.capture", &json!({"films": [{ "path": file.to_string_lossy(), "sourcePath": "An Invented Ferry (2019).mp4", "minutes": 101.4, "video": "avc1", "audio": "mp4a", "height": 1080, "bitrate": 4200, }]})) .expect("the film captured"); let key = captured["films"][0]["key"].as_str().unwrap_or_else(|| panic!("its key: {captured}")).to_string(); let here = |key: &str| crate::methods::dispatch(&handle, "films.here.read", &json!({"key": key})).expect("what this phone keeps")["state"].clone(); assert_eq!(here(&key), json!("kept")); let media = handle.client().layout().client_media_dir().join(PERSON_B); assert!(media.exists(), "B's media folder"); sign_out(&handle); assert_ne!(here(&key), json!("kept"), "signed out, B's film is no longer kept here for anyone"); assert_eq!(crate::methods::dispatch(&handle, "films.onPhone", &json!({})).expect("counts")["films"], 0); assert!(!media.exists(), "its bytes went aside with B's copy"); sign_in_to(&handle, &b, PERSON_B); assert_eq!(here(&key), json!("kept"), "B signed in again finds it kept"); assert_eq!(crate::methods::dispatch(&handle, "films.onPhone", &json!({})).expect("counts")["films"], 1); assert!(media.exists(), "its bytes back where the player reads them");}/// RULE (signout-walk, 14 Nov 2026, Books Dev on a simulator): A signs in and out, B signs in and out, a row is made on the phone's fresh database, A signs in again (A's copy taken back) and the adopt of that row stops part way, and A signs out: the phone stands on a database of its own, never refused `already_started` by a database left behind with no address, and a launch signed out after it stands as well.#[test]fn signing_out_after_a_copy_was_taken_back_over_a_used_local_database_stands_on_a_database() { let (_dir, handle) = phone(); let a = person_a(); let b = person_b(); sign_in_to(&handle, &a, DATABASE); sign_out(&handle); sign_in_to(&handle, &b, PERSON_B); sign_out(&handle); todo(&handle, "An errand made on the phone's own database"); // The line drops as A's sign-in sends that row (the app killed part way does the same). *a.budget.lock().unwrap() = Some((0, Drop::Before)); sign_in_to(&handle, &a, DATABASE); *a.budget.lock().unwrap() = None; let signed_out = call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>); assert!(signed_out.is_ok(), "A's sign-out stands the phone on a database: {signed_out:?}"); let mine = connection_of(&handle).expect("a database to stand on"); assert_eq!(mine.mode, cotton_client::connection::ConnectionMode::Local); assert_ne!(mine.workspace_id.as_deref(), Some(DATABASE)); assert!(!handle.client().layout().replica(DATABASE).exists(), "A's copy is set aside, nowhere a read reaches"); // The row made there was going into A's object: it waits aside with A's copy, or stands on the phone's own database; either way nothing of B's is drawn. let drawn = drawn_todos(&handle); assert!(drawn.iter().all(|title| title == "An errand made on the phone's own database"), "{drawn:?}"); let launched = call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>); assert!(launched.is_ok(), "a launch signed out stands too: {launched:?}"); // A phone the old build left holding no connection (its start refused) stands again at its next launch. let stood_on = connection_of(&handle).and_then(|mine| mine.workspace_id); std::fs::remove_file(handle.client().layout().connection_json()).expect("the connection removed"); let again = call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood"); assert_eq!(connection_of(&handle).and_then(|mine| mine.workspace_id), stood_on, "{again}");}/// Until the adopt's status is `want`, failing at once should it stop.fn adopt_reaches(handle: &CottonHandle, want: &str) -> Value { // Generous: making the copy takes a minute on a loaded box. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300); loop { let said = status(handle); if said["adopt"]["status"] == want { return said; } assert!(said["adopt"]["status"] != FAILED && std::time::Instant::now() < deadline, "the backup never reached {want}: {said}"); std::thread::sleep(std::time::Duration::from_millis(20)); }}/// RULE (seal_key_missing after sign-in, emulators 21 Nov 2026): Music Dev/// held 2,003 songs made before sign-in, and its first backup stopped at 0 of/// 3,088 rows on "seal_key_missing: no key for the data key of …": a sealed/// row goes up only under the object's data key, and the phone takes that key/// only on the object's connected copy (founded there for a new person, let in/// for an existing one), which the failed backup never connected. A send/// stopped by the key alone now connects the copy with the local database/// kept whole, waits in the kit's words, and sends every row sealed once the/// key is held; nothing goes in the clear meanwhile.#[test]fn a_backup_whose_object_key_this_phone_lacks_connects_and_sends_once_the_key_is_held() { let (_dir, handle) = todos_kit_phone(); let local = started_here(&handle); for n in 0..3 { todo(&handle, &format!("Invented errand {n}")); } handle.client().data_keys().forget(DATABASE); let door = Door::new(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE), "the object's copy is connected, where the key is taken"); let layout = handle.client().layout().clone(); assert!(layout.replica(&local).exists(), "the local database is kept whole while it waits"); assert_eq!(door.count("todo"), 0, "no row goes before the key: {:?}", door.taken.lock().unwrap()); let line = home(&handle)["backup"]["line"].as_str().unwrap_or_default().to_string(); assert!(line.contains("Setting up your account") && !line.contains("seal_") && !line.contains("unlocked"), "the kit's words, never the core's: {line}"); // The shell founds the key on the connected copy (or the person is let in). handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::from_bytes([9; 32])); handle.client().adopting().expect("the backup").join(); assert_eq!(status(&handle)["adopt"]["status"], DONE, "{}", status(&handle)); assert_eq!(door.count("todo"), 3, "every row went once the key was held"); assert!(door.rows.lock().unwrap().iter().filter(|((table, _), _)| table == "todo").all(|(_, data)| data["sealed_enc"].is_string() && data.get("title").is_none()), "sealed, never in the clear"); assert!(!layout.replica(&local).exists(), "the local database leaves its place once its rows are in (QUEUE BAD OP 4: anything unsent in it kept aside)");}/// RULE: a backup waiting for the key that the app closed meanwhile goes on/// at the next connect of that object (a launch), and sends its rows once/// the key is held, its local database kept until then.#[test]fn a_backup_waiting_for_the_key_goes_on_at_the_next_connect() { let (_dir, handle) = todos_kit_phone(); let local = started_here(&handle); for n in 0..2 { todo(&handle, &format!("Invented errand {n}")); } handle.client().data_keys().forget(DATABASE); let door = Door::new(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); // The app closes: the adopt's thread ends with it. handle.client().adopting().expect("the backup").stop(); let layout = handle.client().layout().clone(); assert!(layout.replica(&local).exists(), "kept whole"); // The next launch connects with the key the shell keeps. let mut launch = ask(); launch["dataKey"] = json!(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, [9u8; 32])); call_with(&handle, "personal.connect", &launch, Arc::clone(&door) as Arc<dyn Exchange>).expect("connected"); handle.client().adopting().expect("the backup goes on").join(); assert_eq!(status(&handle)["adopt"]["status"], DONE, "{}", status(&handle)); assert_eq!(door.count("todo"), 2); assert!(door.creates().values().all(|n| *n == 1), "each row once: {:?}", door.creates()); assert!(!layout.replica(&local).exists(), "and the local database leaves its place (QUEUE BAD OP 4: anything unsent in it kept aside)");}/// RULE (walk 3, emulator-5600, 24 Nov 2026): what a person made before signing in is never lost by signing out/// while its backup waits for another device. Days Dev: an event made signed out, then sign-in to a number whose/// account another device holds ("One more step: open another device of yours"), then Sign out. The phone's own/// database had gone aside with the account's copy and a fresh empty one was started, so the event was gone for/// good. Now the phone stands on its own database again, as it was before the sign-in, and a later sign-in with the/// key backs it up.#[test]fn signing_out_while_the_backup_waits_for_the_key_keeps_what_was_made_before_sign_in() { let (_dir, handle) = todos_kit_phone(); let local = started_here(&handle); for n in 0..2 { todo(&handle, &format!("Invented errand {n}")); } handle.client().data_keys().forget(DATABASE); let door = Door::new(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); sign_out(&handle); assert_eq!(connection_of(&handle).and_then(|held| held.workspace_id).as_deref(), Some(local.as_str()), "the phone stands on its own database again"); let mut drawn = drawn_todos(&handle); drawn.sort(); assert_eq!(drawn, ["Invented errand 0", "Invented errand 1"], "and draws what was made there"); let layout = handle.client().layout().clone(); assert!(!crate::phone::copy_aside::is_objects_copy(&layout.replica(&local)), "no longer marked as the account's"); // Signed in again with the key the shell keeps, the same rows are backed up. let mut launch = ask(); launch["dataKey"] = json!(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, [9u8; 32])); call_with(&handle, "personal.connect", &launch, Arc::clone(&door) as Arc<dyn Exchange>).expect("connected"); if let Some(adopting) = handle.client().adopting() { adopting.join(); } assert_eq!(status(&handle)["adopt"]["status"], DONE, "{}", status(&handle)); assert_eq!(door.count("todo"), 2, "both errands reach the account");}/// RULE (seal_key_missing after sign-in, 21 Nov 2026): no core code reaches a/// screen. A backup stopped on a sealing refusal ("seal_does_not_open: …")/// says the kit's line on the deck and on Account's Last error; the core's/// own words stay in the log. (Before, both said them as they were.)#[test]fn a_backup_stopped_on_a_sealing_refusal_says_the_kits_words_never_the_cores() { let (_dir, handle) = todos_kit_phone(); started_here(&handle); todo(&handle, "An invented errand"); let door = Door::new(); *door.faults.lock().unwrap() = Some((503, "seal_does_not_open".into(), "seal_does_not_open: the object could not open what it was sent".into())); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], FAILED, "{ended}"); let said = home(&handle); let line = said["backup"]["line"].as_str().unwrap_or_default(); assert!(!line.is_empty() && !line.contains("seal_"), "the deck says the kit's line: {said}"); let card = account(&handle); let error = card["card"]["facts"].as_array().expect("facts").last().expect("Last error")["said"].as_str().unwrap_or_default().to_string(); assert!(!error.contains("seal_") && error.contains("set up"), "Last error in the kit's words: {card}");}/// RULE (fault 3 of 21 Nov 2026: right after sign-in the Account card still/// offered Back up now and Sign out once the backup had stopped, and both/// answered "That didn't work"): a backup that ends moves every read and/// asks every screen again (a data event naming no table, after the client/// event that says how it ended), and the card the core answers then offers/// exactly the acts it takes.#[test]fn a_backup_that_ends_asks_the_account_card_again_and_it_offers_what_the_core_takes() { let (_dir, handle) = todos_kit_phone(); started_here(&handle); for n in 0..3 { todo(&handle, &format!("Invented errand {n}")); } let door = Door::new(); *door.budget.lock().unwrap() = Some((1, Drop::Before)); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); handle.client().adopting().expect("the backup").join(); assert_eq!(status(&handle)["adopt"]["status"], FAILED); let events = handle.events().buffered_events(); let ended = events.iter().rposition(|event| event["kind"] == "client" && event["payload"]["stage"] == ADOPT_FAILED).expect("the backup's end is said"); assert!( events[ended..].iter().any(|event| event["kind"] == "data" && event["payload"]["origin"] == ACCOUNT_ORIGIN), "a data event follows, so the card is asked again: {:?}", &events[ended..] ); let offered = account_acts(&handle); assert_eq!(offered, ["Sign in"], "the card offers what the core takes now"); for act in [crate::phone::tool_acts::ACCOUNT_BACK_UP, crate::phone::tool_acts::ACCOUNT_SIGN_OUT] { assert!(crate::phone::tool_acts::account(&handle.client(), act).is_err(), "{act} is not taken, and not offered"); }}/// RULE (fault 4 of 21 Nov 2026: Music on the emulator said "No albums yet"/// while its songs waited for the key): once a backup has connected the/// object's copy and its rows have not all gone up, an empty deck says it is/// bringing the person's things, in the shell's words with the table's/// plural; once they are in, the deck says its own.#[test]fn an_empty_deck_says_it_is_bringing_while_a_backup_waits_for_the_key() { let (_dir, handle) = todos_kit_phone(); started_here(&handle); todo(&handle, "Invented errand"); handle.client().data_keys().forget(DATABASE); let door = Door::new(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); let deck = |handle: &CottonHandle| crate::methods::dispatch(handle, "shell.deck", &json!({"table": "todo", "timezone": "Asia/Kolkata"})).expect("the deck reads"); let waiting = deck(&handle); let plural = cotton_core::kit::table("todo").expect("the todo table").plural.to_lowercase(); assert_eq!(waiting["empty"]["title"], json!(format!("Bringing your {plural}\u{2026}")), "{waiting}"); handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::from_bytes([9; 32])); handle.client().adopting().expect("the backup").join(); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } let done = deck(&handle); assert!(done["empty"]["title"].as_str().is_none_or(|title| !title.starts_with("Bringing")), "{done}");}/// RULE (fault 2 of 21 Nov 2026): the restore of a copy left by an earlier/// sign-in into the person's new database waits for the key the way a/// backup of a database this phone started does: a former copy's sealed rows/// go up only under the new object's data key, which this phone takes on the/// new object's connected copy. The send stopped by the key connects the/// copy with the former copy kept whole, nothing goes in the clear, and every/// row goes sealed once the key is held; then the former copy goes.#[test]fn a_former_copys_restore_whose_object_key_this_phone_lacks_connects_and_sends_once_the_key_is_held() { let (_dir, handle) = phone(); let former = former_object(3); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); handle.client().data_keys().forget(DATABASE); let door = Door::new(); *door.watched.lock().unwrap() = Some(handle.client().layout().replica(FORMER)); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE), "the new object's copy is connected, where the key is taken"); let layout = handle.client().layout().clone(); assert!(layout.replica(FORMER).exists(), "the former copy is kept whole while it waits"); assert_eq!(door.count("todo"), 0, "no sealed row goes before the key: {:?}", door.taken.lock().unwrap()); let line = home(&handle)["backup"]["line"].as_str().unwrap_or_default().to_string(); // The kit's words for the wait, which never say "unlocked" (c7e9ad640), and never the core's. assert!(!line.is_empty() && !line.contains("unlocked") && !line.contains("seal_"), "the kit's words, never the core's: {line}"); handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::from_bytes([9; 32])); handle.client().adopting().expect("the restore").join(); let ended = status(&handle); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(door.count("todo"), 5, "three errands, the project's and the one made here"); assert!(door.rows.lock().unwrap().iter().filter(|((table, _), _)| table == "todo").all(|(_, data)| data["sealed_enc"].is_string() && data.get("title").is_none()), "sealed, never in the clear"); assert!(door.restored.lock().unwrap().values().all(|n| *n == 1), "each row once: {:?}", door.restored.lock().unwrap()); assert!(!layout.replica(FORMER).parent().expect("a folder").exists(), "the former copy goes once its rows are in");}/// RULE: a restore waiting for the key that the app closed meanwhile goes on/// at the next connect of that object, and sends its rows once the key is/// held, the former copy kept until then.#[test]fn a_former_copys_restore_waiting_for_the_key_goes_on_at_the_next_connect() { let (_dir, handle) = phone(); let former = former_object(2); pulled_from(&handle, &former); call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); handle.client().data_keys().forget(DATABASE); let door = Door::new(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); handle.client().adopting().expect("the restore").stop(); let layout = handle.client().layout().clone(); assert!(layout.replica(FORMER).exists(), "kept whole"); let mut launch = ask(); launch["dataKey"] = json!(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, [9u8; 32])); call_with(&handle, "personal.connect", &launch, Arc::clone(&door) as Arc<dyn Exchange>).expect("connected"); handle.client().adopting().expect("the restore goes on").join(); assert_eq!(status(&handle)["adopt"]["status"], DONE, "{}", status(&handle)); assert_eq!(door.count("todo"), 4); assert!(door.restored.lock().unwrap().values().all(|n| *n == 1), "each row once: {:?}", door.restored.lock().unwrap()); assert!(!layout.replica(FORMER).parent().expect("a folder").exists(), "and the former copy goes");}/// RULE (Story walk, 25 Nov 2026): a backup says done only once the account's copy holds every row it sent. A/// script, a scene and its line made signed out, then sign-in with a new number: the line went up last, the/// phone's own database was removed, and the copy had not pulled it, so the scene stood empty until a relaunch.#[test]fn a_backup_is_done_only_once_the_copy_holds_what_it_sent() { let dir = tempfile::tempdir().unwrap(); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(json!({"genesis": "personal", "flavour": "story", "name": "Cotton Story", "databases": "single", "database": "personal", "business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } }, "fan": { "home": false, "tools": false, "opens": "story" }, "kit": "story", "ground": "blank"})), }).expect("an open core"); holds_the_data_keys(&handle); started_here(&handle); let said = |method: &str, request: Value| crate::methods::dispatch(&handle, method, &request).unwrap_or_else(|error| panic!("{method}: {error:?}")); let story = said("story.start", json!({"title": "An invented script"}))["story"].as_str().unwrap().to_string(); let scene = said("story.scene.add", json!({"story": story, "place": "Invented cliff", "time": "dawn"}))["scene"].as_str().unwrap().to_string(); said("story.line.add", json!({"scene": scene, "kind": "action", "text": "Gulls wheel overhead."})); handle.client().data_keys().forget(DATABASE); let door = Door::new(); door.also_serves.lock().unwrap().push("story"); call_with(&handle, "personal.connect", &ask(), Arc::clone(&door) as Arc<dyn Exchange>).expect("answered"); adopt_reaches(&handle, WAITING_KEY); handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::from_bytes([9; 32])); handle.client().adopting().expect("the backup").join(); assert_eq!(status(&handle)["adopt"]["status"], DONE, "{}", status(&handle)); // No pass run here: what the screens read the moment the backup says done. let shown = said("story.scene", json!({"id": scene})); let lines: Vec<&str> = shown["lines"].as_array().into_iter().flatten().filter_map(|line| line["text"].as_str()).collect(); assert_eq!(lines, ["Gulls wheel overhead."], "the scene's line stands in the copy once the backup is done: {shown}"); assert_eq!(said("story.scenes", json!({"story": story}))["rows"][0]["minutes_word"], json!("1 min"));}// ---- SITES ROWS (assets/design/sites/SYNC-DESIGN.md, design 2): Sites' list at sign-in.const SITES_KEY: &str = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";/// A phone on Cotton Sites' own kit, which carries the synced `site` table.fn sites_phone() -> (tempfile::TempDir, CottonHandle) { crate::phone::sites::reset_for_tests(); let dir = tempfile::tempdir().expect("a temp container"); let manifest = json!({ "genesis": "personal", "flavour": "sites", "name": "Cotton Sites", "databases": "single", "database": "personal", "kit": "sites" }); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(manifest), }) .expect("an open core"); holds_the_data_keys(&handle); (dir, handle)}fn sites(handle: &CottonHandle, method: &str, mut request: Value) -> Value { request["key"] = json!(SITES_KEY); crate::methods::dispatch(handle, method, &request).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message))}/// RULE: a site made before sign-in goes up with the adopt under its own key, and keeps what this phone kept of it:/// its sign-in (the store its key names) and the page it was left on. Every site goes: nothing is asked first.#[test]fn adopted_sites_keep_their_sign_in() { let (_dir, handle) = sites_phone(); let door = Door::new(); started_here(&handle); let added = sites(&handle, "sites.add", json!({ "label": "Club", "home": "club.example" })); let club = added["row"]["id"].as_str().unwrap().to_string(); let store = sites(&handle, "sites.open", json!({ "id": club }))["store"].clone(); sites(&handle, "sites.left", json!({ "id": club, "url": "https://club.example/board", "title": "Board" })); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); assert_eq!(ended["adopt"]["refused"], json!(0), "{ended}"); handle.client().sync_now().expect("a pass"); assert!(door.rows.lock().unwrap().keys().any(|(t, id)| t == "site" && *id == club), "the site went up at its key: {:?}", door.taken.lock().unwrap()); let home = sites(&handle, "sites.home", json!({})); assert_eq!(home["rows"][0]["id"], club.as_str()); assert_eq!(home["rows"][0]["line"], "club.example · Board", "its page came with it: {home}"); assert_eq!(sites(&handle, "sites.open", json!({ "id": club }))["store"], store, "the same sign-in");}const CLUB: &str = "0b0b0b0b-1111-4222-8333-444444444441";const BANK: &str = "0b0b0b0b-1111-4222-8333-444444444442";/// A site as an earlier build kept it only on this phone, with its sign-in and its page.fn kept_only_here(id: &str, label: &str, store: &str) -> cotton_core::sites::Row { let home = format!("https://{}.example/", label.to_lowercase()); cotton_core::sites::Row { id: id.into(), label: label.into(), last: Some(format!("{home}board")), home, stay: true, hidden: false, pinned: false, trackers: true, login: None, title: Some("Board".into()), state: None, sign_in_once: false, waiting: None, changed_at: 0, store: Some(store.into()) }}/// A SIGNED-IN, caught-up copy on a door, holding the given sites only on this phone (as an earlier build left them).fn signed_in_keeping_only(only: &[cotton_core::sites::Row]) -> (tempfile::TempDir, CottonHandle, Arc<Door>) { let (dir, handle) = sites_phone(); let door = Door::new(); door.keeps_tombstones.store(true, Ordering::SeqCst); started_here(&handle); sites(&handle, "sites.add", json!({ "label": "News", "home": "news.example" })); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); pass(&handle); pass(&handle); assert!(handle.client().caught_up(DATABASE)); // Caught up, then the line drops: a failed pass does not undo what the pull already brought. crate::phone::sites::caught_up_for_tests(&handle.client(), true); keep_only(&handle, only); (dir, handle, door)}/// The sites as an earlier build left them only on this phone, written into its file.fn keep_only(handle: &CottonHandle, only: &[cotton_core::sites::Row]) { let mut local = crate::phone::sites::local_for_tests(&handle.client()); for (i, row) in only.iter().enumerate() { local.entries.insert(row.id.clone(), row.clone()); local.only.insert(row.id.clone(), 9_000.0 + i as f64); } crate::phone::sites::write_local_as_for_tests(&handle.client(), &local);}/// A row the Mac writes or deletes on the object (site rows go in the clear on this door).fn mac_writes(door: &Door, id: &str, label: &str) { let home = format!("https://{}.example/", label.to_lowercase()); door.rows.lock().unwrap().insert(("site".to_string(), id.to_string()), json!({ "key": id, "label": label, "home": home, "stay": true, "hidden": false, "pinned": false, "trackers": true, "login": "", "position": 5_000.0 })); *door.version.lock().unwrap() += 1;}fn mac_deletes(door: &Door, id: &str) { door.rows.lock().unwrap().remove(&("site".to_string(), id.to_string())); door.tombstones.lock().unwrap().insert(("site".to_string(), id.to_string()), chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)); *door.version.lock().unwrap() += 1;}/// The line to the object down (every act dropped before it lands), or up again.fn line(door: &Door, up: bool) { *door.budget.lock().unwrap() = if up { None } else { Some((0, Drop::Before)) };}/// A pass that lands: one already running when the line came back may still answer for the line down.fn pass(handle: &CottonHandle) { let mut last = Ok(()); for _ in 0..5 { last = handle.client().sync_now().map(|_| ()); if last.is_ok() { return; } std::thread::sleep(std::time::Duration::from_millis(100)); } last.expect("a pass");}fn on_server(door: &Door, id: &str) -> bool { door.rows.lock().unwrap().keys().any(|(t, held)| t == "site" && held == id)}/// The site writes this phone still holds for the object.fn sites_queued(handle: &CottonHandle) -> i64 { handle .client() .with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_site'", &[]).map_err(|e| e.to_string()).map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))) .expect("the outbox")}fn shown_as(handle: &CottonHandle, label: &str) -> Vec<Value> { sites(handle, "sites.home", json!({}))["rows"].as_array().unwrap().iter().filter(|r| r["label"] == label).cloned().collect()}fn only_here(handle: &CottonHandle) -> Vec<String> { crate::phone::sites::local_for_tests(&handle.client()).only.keys().cloned().collect()}/// RULE (SITES NO SWITCH 2): on a signed-in copy a site an earlier build kept only on this phone is made a row at its/// own key and leaves this phone's list in the same turn, with nothing waiting on the server: the outbox holds its/// write like any site added offline, and the server has it at the next pass. Its sign-in and page stay.#[test]fn a_site_kept_only_here_goes_into_the_list_in_one_turn() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store")]); line(&door, false); let clubs = shown_as(&handle, "Club"); assert_eq!(clubs.len(), 1, "shown once"); assert_eq!(clubs[0]["id"], CLUB, "at its own key"); assert_eq!(clubs[0]["store"], "site-club-store", "its sign-in"); assert_eq!(clubs[0]["line"], "club.example · Board", "its page"); assert!(only_here(&handle).is_empty(), "out of this phone's list in the same turn, the server not asked"); assert!(sites_queued(&handle) > 0, "its write waits in the outbox"); assert!(!on_server(&door, CLUB)); line(&door, true); pass(&handle); assert!(on_server(&door, CLUB), "on the server"); assert_eq!(shown_as(&handle, "Club").len(), 1); assert_eq!(sites(&handle, "sites.open", json!({ "id": CLUB }))["store"], "site-club-store", "the same sign-in");}/// RULE (review of SITES NO SWITCH, 1 HIGH): removed while its row is still unsent, the site is erased like any row:/// it never reaches the server and never comes back, here or anywhere.#[test]fn a_site_removed_while_its_row_is_unsent_never_comes_back() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store")]); crate::phone::sites::freeze_for_tests(); line(&door, false); assert_eq!(shown_as(&handle, "Club").len(), 1); assert!(sites_queued(&handle) > 0, "unsent"); sites(&handle, "sites.delete", json!({ "id": CLUB })); crate::phone::sites::later_for_tests(6_000); assert!(shown_as(&handle, "Club").is_empty(), "gone here"); line(&door, true); pass(&handle); pass(&handle); assert!(!on_server(&door, CLUB), "never on the server"); for _ in 0..2 { assert!(shown_as(&handle, "Club").is_empty(), "never back"); pass(&handle); } assert!(only_here(&handle).is_empty());}/// RULE (review of SITES NO SWITCH, item 2): sent, then deleted on another device: the delete removes it here, and no/// ghost is drawn from this phone's file.#[test]fn a_site_sent_then_deleted_elsewhere_leaves_no_ghost() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store")]); assert_eq!(shown_as(&handle, "Club").len(), 1); pass(&handle); assert!(on_server(&door, CLUB), "sent"); // The Mac deletes it. mac_deletes(&door, CLUB); pass(&handle); pass(&handle); for _ in 0..2 { assert!(shown_as(&handle, "Club").is_empty(), "no ghost"); } assert!(only_here(&handle).is_empty()); assert!(!on_server(&door, CLUB), "not made again");}/// RULE (review of SITES NO SWITCH, item 3): an edit made while the row is unsent goes to the row and reaches the/// server after the create.#[test]fn an_edit_while_the_row_is_unsent_survives() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store")]); line(&door, false); assert_eq!(shown_as(&handle, "Club").len(), 1); sites(&handle, "sites.edit", json!({ "id": CLUB, "label": "Chess club" })); assert_eq!(shown_as(&handle, "Chess club").len(), 1); let from = door.taken.lock().unwrap().len(); line(&door, true); pass(&handle); pass(&handle); assert_eq!(sites_queued(&handle), 0, "everything went"); let acts: Vec<String> = door.taken.lock().unwrap()[from..] .iter() .filter(|act| act["args"]["table"] == "site" && act["args"]["id"] == CLUB) .map(|act| act["act"].as_str().unwrap_or_default().to_string()) .collect(); assert!(acts.first().is_some_and(|a| a == "create"), "the create first: {acts:?}"); assert!(acts.len() >= 2 || on_server(&door, CLUB), "the edit after it, or folded into it: {acts:?}"); assert_eq!(shown_as(&handle, "Chess club").len(), 1, "the edit stands"); assert!(shown_as(&handle, "Club").is_empty());}/// RULE (review of SITES NO SWITCH, item 8): a real kill between the create and the file write (injected): the next/// read finds the row in the store with its write in the outbox, makes nothing again, and lets the site go from here.#[test]fn a_kill_between_the_create_and_the_file_write_makes_it_once() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store")]); line(&door, false); crate::phone::sites::stop_retire_for_tests(1, true); // The run dies after the create (the list is still drawn, as after any failed tidy): the file is not written. assert_eq!(shown_as(&handle, "Club").len(), 1, "never twice, even right after the kill"); assert_eq!(only_here(&handle), [CLUB], "the file was not written"); let queued = sites_queued(&handle); assert!(queued > 0, "the create waits in the outbox"); assert_eq!(shown_as(&handle, "Club").len(), 1, "shown once"); assert_eq!(sites_queued(&handle), queued, "nothing made again"); assert!(only_here(&handle).is_empty()); line(&door, true); pass(&handle); assert!(on_server(&door, CLUB)); assert_eq!(door.rows.lock().unwrap().keys().filter(|(t, _)| t == "site").count(), 2, "News and Club, once");}/// RULE (review of SITES NO SWITCH, item 8): a left-here file carried into the signed-in copy's folder goes through/// the same turn: each site made a row once, with its sign-in, and the file taken in once.#[test]fn a_carried_left_here_file_goes_into_the_list_once() { let (_dir, handle, door) = signed_in_keeping_only(&[]); let key = cotton_core::chat::seal::key_from_text(SITES_KEY).unwrap(); let folder = crate::phone::sites::local_folder_for_tests(&handle.client()).unwrap(); let mut left = cotton_core::sites::Local::default(); left.entries.insert(CLUB.into(), kept_only_here(CLUB, "Club", "club-store")); left.only.insert(CLUB.into(), 9_000.0); let file = folder.join("sites.left-here.earlier.c1"); std::fs::write(&file, left.seal(&key, &[4; 12]).unwrap()).unwrap(); line(&door, false); let clubs = shown_as(&handle, "Club"); assert_eq!(clubs.len(), 1); assert_eq!(clubs[0]["id"], CLUB); assert_eq!(clubs[0]["store"], "site-club-store", "its sign-in"); assert!(!file.exists(), "taken in once"); assert!(only_here(&handle).is_empty()); line(&door, true); pass(&handle); assert!(on_server(&door, CLUB)); assert_eq!(shown_as(&handle, "Club").len(), 1);}/// RULE (review of SITES NO SWITCH, item 8): the copy switched part way through (a sign-out, another database):/// nothing more is made; the rest goes in, once each, when the copy is back.#[test]fn a_database_switch_part_way_makes_nothing_more() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store"), kept_only_here(BANK, "Bank", "bank-store")]); line(&door, false); crate::phone::sites::stop_retire_for_tests(1, false); sites(&handle, "sites.home", json!({})); assert_eq!(only_here(&handle).len(), 1, "one made before the switch, the other waits"); crate::phone::sites::go_on_retire_for_tests(); assert_eq!(shown_as(&handle, "Club").len(), 1); assert_eq!(shown_as(&handle, "Bank").len(), 1); assert!(only_here(&handle).is_empty()); line(&door, true); pass(&handle); assert!(on_server(&door, CLUB) && on_server(&door, BANK)); assert_eq!(door.rows.lock().unwrap().keys().filter(|(t, _)| t == "site").count(), 3, "each once");}/// RULE: an account deleted on this phone takes its copy's folder, and the website stores its sites named are owed for/// removal, though no Sites key is held then.#[test]fn account_delete_removes_website_stores() { let (_dir, handle) = sites_phone(); let door = Door::new(); started_here(&handle); sites(&handle, "sites.add", json!({ "label": "News", "home": "news.example" })); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("a pass"); let added = sites(&handle, "sites.add", json!({ "label": "Club", "home": "club.example" })); let club = added["row"]["id"].as_str().unwrap().to_string(); let store = sites(&handle, "sites.open", json!({ "id": club }))["store"].clone(); sites(&handle, "sites.left", json!({ "id": club, "url": "https://club.example/board" })); crate::phone::copy_aside::forget(&handle.client().layout().clone(), DATABASE, &cotton_client::copy_keep::PersonsAct::of_the_person()).expect("forgotten"); let gone = sites(&handle, "sites.stores.gone", json!({})); assert!(gone["stores"].as_array().unwrap().iter().any(|s| s["store"] == store), "{gone}");}/// RULE (review of SITES ROWS, item 5): Sites acts on a missing row only once the copy has truly caught up, tested on/// the real `ClientController::caught_up` of a signed-in copy: with the data key not held (a copy made again before/// the key), a site missing from the copy is kept and its website store is not touched; with the key held again and a/// pass that ended with nothing to come, the site seen gone owes its store.#[test]fn a_copy_without_the_key_drops_nothing() { let (_dir, handle) = sites_phone(); let door = Door::new(); door.keeps_tombstones.store(true, Ordering::SeqCst); started_here(&handle); let news = sites(&handle, "sites.add", json!({ "label": "News", "home": "news.example" }))["row"]["id"].as_str().unwrap().to_string(); sites(&handle, "sites.open", json!({ "id": news })); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("a pass"); let club = sites(&handle, "sites.add", json!({ "label": "Club", "home": "club.example" }))["row"]["id"].as_str().unwrap().to_string(); let store = sites(&handle, "sites.open", json!({ "id": club }))["store"].clone(); sites(&handle, "sites.left", json!({ "id": club, "url": "https://club.example/board" })); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("another"); assert!(handle.client().caught_up(DATABASE), "a pass with nothing to come"); // The key let go (a copy made again before the key is), and Club removed on another phone: its delete arrives. handle.client().data_keys().forget(DATABASE); door.rows.lock().unwrap().remove(&("site".to_string(), club.clone())); door.tombstones.lock().unwrap().insert(("site".to_string(), club.clone()), chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)); *door.version.lock().unwrap() += 1; let _ = handle.client().sync_now(); let home = sites(&handle, "sites.home", json!({})); assert!(sites(&handle, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "nothing owed without the key: {home}"); // The key held again and a pass that ended: still nothing queued by the row's absence (review of SITES ROWS 2, // blocking 1); its sign-in is offered instead. holds_the_data_keys(&handle); handle.client().sync_now().expect("a pass"); let home = sites(&handle, "sites.home", json!({})); assert!(sites(&handle, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "{home}"); // Only News and Club here, Club missing: one of two, offered by name. assert!(home["orphans"]["sites"].as_array().is_some_and(|s| s.iter().any(|o| o["label"] == "Club")), "{home}"); let _ = store;}/// RULE (review of SITES ROWS 2, blocking 1): a copy made again in the running app never removes a sign-in. Caught/// up dies with the copy it was said of (let go, made again, or a pass starting); and once the new copy is caught up/// and still lacks a site, its sign-in is offered, never queued.#[test]fn a_copy_made_again_queues_no_sign_in() { let (_dir, handle) = sites_phone(); let door = Door::new(); started_here(&handle); sites(&handle, "sites.add", json!({ "label": "News", "home": "news.example" })); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("a pass"); let club = sites(&handle, "sites.add", json!({ "label": "Club", "home": "club.example" }))["row"]["id"].as_str().unwrap().to_string(); sites(&handle, "sites.open", json!({ "id": club })); sites(&handle, "sites.left", json!({ "id": club, "url": "https://club.example/board" })); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("another"); sites(&handle, "sites.home", json!({})); assert!(handle.client().caught_up(DATABASE)); // Let go and opened again, as the heal does: caught up is gone with the copy. handle.client().detach(); assert!(!handle.client().caught_up(DATABASE), "caught up dies with the copy"); handle.client().attach_now().expect("the copy opens again"); assert!(!handle.client().caught_up(DATABASE)); // The copy made again holds none of his sites yet. handle.client().with_writer(|file| file.driver.run("DELETE FROM cotton_site", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap(); let home = sites(&handle, "sites.home", json!({})); assert!(sites(&handle, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "nothing queued while loading: {home}"); // Loading, unless the restarted loop has already caught the copy up again. if !handle.client().caught_up(DATABASE) { assert_eq!(home["loading"]["line"], "Loading your list…", "{home}"); } // Caught up again, and Club still not in this copy: offered, never queued. handle.client().sync_now().expect("a pass"); let home = sites(&handle, "sites.home", json!({})); assert!(sites(&handle, "sites.stores.gone", json!({}))["stores"].as_array().unwrap().is_empty(), "nothing queued by absence: {home}"); // Club is back in the copy (pulled again) or its sign-in is offered: never removed. let shown = home["rows"].as_array().unwrap().iter().any(|r| r["label"] == "Club"); assert!(shown || home["orphans"]["sites"].as_array().is_some_and(|s| !s.is_empty()), "{home}");}/// RULE (review of NO SWITCH 2, item 1): a site still in this phone's list while a row stands at its key (a run killed/// after its create), removed while the copy is not caught up: the row is erased, and never returns.#[test]fn a_site_here_with_its_row_standing_removed_before_caught_up_never_returns() { let (_dir, handle, door) = signed_in_keeping_only(&[kept_only_here(CLUB, "Club", "club-store")]); crate::phone::sites::freeze_for_tests(); line(&door, false); crate::phone::sites::stop_retire_for_tests(1, true); assert_eq!(shown_as(&handle, "Club").len(), 1); assert_eq!(only_here(&handle), [CLUB], "in the list here"); assert!(sites_queued(&handle) > 0, "and its row made"); crate::phone::sites::caught_up_for_tests(&handle.client(), false); sites(&handle, "sites.delete", json!({ "id": CLUB })); crate::phone::sites::later_for_tests(6_000); assert!(shown_as(&handle, "Club").is_empty()); assert!(only_here(&handle).is_empty()); line(&door, true); crate::phone::sites::caught_up_for_tests(&handle.client(), true); for _ in 0..2 { pass(&handle); assert!(shown_as(&handle, "Club").is_empty(), "never returns"); } assert!(!on_server(&door, CLUB), "erased");}/// RULE (review of NO SWITCH 2, item 2): the Mac made a row at the site's key before this phone pulled it. On the real/// caught-up check (no hook): nothing is made while the copy is behind, and once the pull brings the row it is the/// site, shown once, and no create is ever sent for it.#[test]fn a_row_the_mac_made_at_its_key_before_the_pull_is_the_site() { let (_dir, handle, door) = signed_in_keeping_only(&[]); crate::phone::sites::reset_for_tests(); keep_only(&handle, &[kept_only_here(CLUB, "Club", "club-store")]); mac_writes(&door, CLUB, "Club"); // Let go and opened again: caught up dies with the copy, and the row is not pulled yet. handle.client().detach(); handle.client().attach_now().expect("the copy opens again"); let from = door.taken.lock().unwrap().len(); // Behind, or caught up by the running loop meanwhile (the row then pulled): shown once, and never made here. assert_eq!(shown_as(&handle, "Club").len(), 1, "shown once"); assert_eq!(sites_queued(&handle), 0, "nothing made here while behind"); pass(&handle); pass(&handle); assert!(handle.client().caught_up(DATABASE)); let clubs = shown_as(&handle, "Club"); assert_eq!(clubs.len(), 1, "shown once"); assert_eq!(clubs[0]["id"], CLUB); assert_eq!(clubs[0]["store"], "site-club-store", "with its sign-in"); assert!(only_here(&handle).is_empty()); assert_eq!(sites_queued(&handle), 0, "nothing made here"); pass(&handle); let creates = door.taken.lock().unwrap()[from..].iter().filter(|a| a["act"] == "create" && a["args"]["table"] == "site").count(); assert_eq!(creates, 0, "no create sent"); assert_eq!(door.rows.lock().unwrap().keys().filter(|(t, _)| t == "site").count(), 2, "News and Club");}/// RULE (review of NO SWITCH 2, item 2): on a signed-in copy, a site whose row was erased here goes in under the/// derived key; a kill between that create and the file write makes it once, with its sign-in. (A row deleted on/// the Mac leaves no trace here, so its own key is free again: it comes back once there, as accepted.)#[test]fn a_kill_under_the_derived_key_makes_it_once() { let (_dir, handle, door) = signed_in_keeping_only(&[]); crate::phone::sites::freeze_for_tests(); mac_writes(&door, CLUB, "Club"); pass(&handle); assert_eq!(shown_as(&handle, "Club").len(), 1); sites(&handle, "sites.delete", json!({ "id": CLUB })); crate::phone::sites::later_for_tests(6_000); assert!(shown_as(&handle, "Club").is_empty(), "erased here"); pass(&handle); assert!(!on_server(&door, CLUB)); keep_only(&handle, &[kept_only_here(CLUB, "Club", "club-store")]); let derived = crate::phone::sites::derived_key(CLUB); line(&door, false); crate::phone::sites::stop_retire_for_tests(1, true); assert_eq!(shown_as(&handle, "Club").len(), 1, "never twice, even right after the kill"); assert_eq!(only_here(&handle), [CLUB], "the file was not written"); let queued = sites_queued(&handle); let clubs = shown_as(&handle, "Club"); assert_eq!(clubs.len(), 1); assert_eq!(clubs[0]["id"], derived.as_str(), "under the derived key"); assert_eq!(clubs[0]["store"], "site-club-store", "its sign-in"); assert_eq!(sites_queued(&handle), queued, "nothing made again"); assert!(only_here(&handle).is_empty()); line(&door, true); pass(&handle); assert!(on_server(&door, &derived) && !on_server(&door, CLUB)); assert_eq!(door.rows.lock().unwrap().keys().filter(|(t, _)| t == "site").count(), 2, "News and Club, once");}/// RULE: a copy that was an account's, stood local (signed out keeping the copy), goes whole into the next account with/// every site, each with its sign-in (nothing is left off: the switch is gone, 27 Nov 2026).#[test]fn a_former_copy_going_whole_takes_every_site() { let (_dir, handle) = sites_phone(); let former = Door::of(FORMER); call_with(&handle, "personal.connect", &ask_for(FORMER), Arc::clone(&former) as Arc<dyn Exchange>).expect("connected to the former object"); let club = sites(&handle, "sites.add", json!({ "label": "Club", "home": "club.example" }))["row"]["id"].as_str().unwrap().to_string(); let store = sites(&handle, "sites.open", json!({ "id": club }))["store"].clone(); sites(&handle, "sites.left", json!({ "id": club, "url": "https://club.example/board", "title": "Board" })); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let door = Door::new(); let (_, ended) = restore_into(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert!(door.rows.lock().unwrap().keys().any(|(t, id)| t == "site" && *id == club), "Club goes up: {:?}", door.rows.lock().unwrap().keys().collect::<Vec<_>>()); let home = sites(&handle, "sites.home", json!({})); let row = home["rows"].as_array().unwrap().iter().find(|r| r["label"] == "Club").expect("Club").clone(); assert_eq!(row["store"], store, "with its sign-in: {home}"); assert_eq!(row["line"], "club.example · Board");}/// A carry of Sites' file that fails (a full disk) keeps the earlier copy's folder: what this phone kept of its sites/// (sign-ins, pages) waits there; the next list open carries it and removes the folder (review of SITES ROWS 5, item 2).#[test]fn a_failed_sites_carry_keeps_the_earlier_copy() { let (_dir, handle) = sites_phone(); let former = Door::of(FORMER); call_with(&handle, "personal.connect", &ask_for(FORMER), Arc::clone(&former) as Arc<dyn Exchange>).expect("connected to the former object"); let club = sites(&handle, "sites.add", json!({ "label": "Club", "home": "club.example" }))["row"]["id"].as_str().unwrap().to_string(); sites(&handle, "sites.left", json!({ "id": club, "url": "https://club.example/board", "title": "Board" })); for _ in 0..3 { handle.client().sync_now().expect("a pass"); } call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); let earlier = crate::phone::sites::local_folder_for_tests(&handle.client()).unwrap(); assert!(earlier.join("sites.local.c1").exists()); crate::phone::sites::carry_fails_from_for_tests(&earlier); let door = Door::new(); let (_, ended) = restore_into(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert!(earlier.join("sites.local.c1").exists(), "the earlier copy stays with what this phone kept"); crate::phone::sites::carry_goes_from_for_tests(&earlier); let home = sites(&handle, "sites.home", json!({})); assert!(!earlier.exists(), "carried at last: the earlier copy removed"); let row = home["rows"].as_array().unwrap().iter().find(|r| r["label"] == "Club").expect("Club").clone(); assert_eq!(row["line"], "club.example · Board", "its page came along: {home}");}/// RULE (ABSENCE 6 owed, ABSENCE 7 item 8): Blocked's gate on the real wiring of a signed-in copy, not the test/// switch: before the copy is an account's it is the phone's own; once signed in it knows every message only after a/// pass that ended with nothing to come and with the data key held; a parked pull row of a table it judges closes it;/// a copy let go is caught up no more.#[test]fn blocked_waits_for_a_real_caught_up_pass_with_the_key() { let (_dir, handle) = sites_phone(); let door = Door::new(); started_here(&handle); sites(&handle, "sites.add", json!({ "label": "News", "home": "news.example" })); const BLOCKED: &[&str] = &["email_sender", "message", "thread", "email"]; let knows = || crate::phone::chat_timer::knows_every(&handle.client(), BLOCKED); assert!(knows(), "the phone's own copy, never an account's"); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], json!(DONE), "{ended}"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("another"); assert!(handle.client().caught_up(DATABASE), "a pass with nothing to come"); assert!(knows(), "signed in, caught up, the key held"); handle.client().data_keys().forget(DATABASE); assert!(!knows(), "caught up without the key: it may lack rows it cannot open"); holds_the_data_keys(&handle); assert!(knows()); handle.client().with_writer(|file| file.driver.run("INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, tbl, row_id) VALUES ('op-invented', 'pull', 'newer-shape', 'invented', '2026-11-27T00:00:00Z', 0, 'cotton_blocked_senders', 'sender-later')", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap(); assert!(!knows(), "a sender's row waiting in _parked"); handle.client().with_writer(|file| file.driver.run("DELETE FROM _parked WHERE op_id = 'op-invented'", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap(); assert!(knows()); handle.client().detach(); assert!(!knows(), "a copy let go is caught up no more");}/// RULE (QUEUE BAD OP 5, item 1): what an adopt could not carry (a change that does not read in this build) keeps the/// local database whole aside, FILED UNDER THE SIGNED-IN DATABASE it now belongs to: listed there, never under the/// local id nobody reads, and removed with that account.#[test]fn what_an_adopt_could_not_carry_is_kept_under_the_signed_in_database() { let (_dir, handle) = phone(); let local = started_here(&handle); todo(&handle, "An invented errand"); { let layout = handle.client().layout().clone(); let db = cotton_store::Driver::open(&layout.replica(&local)).expect("the local copy"); db.run( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig) \ VALUES ('bad-queued', 'change', 'synthetic-author', 'cotton_todos', 'todo-damaged', '0000000000001:0000:x', 1, '2026-09-08T09:00:00.000Z', X'00FF', NULL)", &[], ) .expect("a change that does not read"); } let door = Door::new(); let (_, ended) = back_up(&handle, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(door.count("todo"), 1, "what reads went up"); let layout = handle.client().layout().clone(); assert!(!layout.replica(&local).exists(), "the local database's place is free"); assert!(cotton_client::copy_keep::kept(&layout, Some(&local)).is_empty(), "nothing under the local id"); let kept = cotton_client::copy_keep::kept(&layout, Some(DATABASE)); assert_eq!(kept.len(), 1, "kept under the signed-in database: {kept:?}"); assert_eq!(kept[0].state.adopted_from.as_deref(), Some(local.as_str())); let listed = cotton_client::copy_keep::kept_changes(&layout, DATABASE); assert_eq!(listed.iter().map(|change| change.op_id.as_str()).collect::<Vec<_>>(), ["bad-queued"], "only what the adopt could not carry: {listed:?}"); crate::phone::copy_aside::forget(&layout, DATABASE, &cotton_client::copy_keep::PersonsAct::of_the_person()).expect("the account deleted"); assert!(cotton_client::copy_keep::kept(&layout, None).is_empty(), "account delete removes it with the rest");}// ── KEPT FOUR 2: passwords made before sign-in, read on a second device ──────/// Phone A's vault key (the Keychain's private half), and phone B's.const VAULT_A: [u8; 32] = [21; 32];const VAULT_B: [u8; 32] = [22; 32];fn b64_of(bytes: &[u8]) -> String { base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, bytes)}fn public_b64(secret: &[u8; 32]) -> String { b64_of(&cotton_core::vault::wrap::public_of(secret))}/// A second phone: another device key, another container.fn second_phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(b64_of(&[8u8; 32])), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")), }) .expect("an open core"); holds_the_data_keys(&handle); (dir, handle)}fn unlock(handle: &CottonHandle, secret: &[u8; 32]) -> Result<Value, crate::methods::MethodError> { crate::methods::dispatch(handle, "vault.unlock", &json!({ "privateKey": b64_of(secret) }))}/// A password made on this phone before anyone signed in: the shell publishes the vault key at launch, which founds/// the local vault; Keys unlocks it and saves a login. Answers its id.fn password_before_sign_in(handle: &CottonHandle) -> String { crate::methods::dispatch(handle, "vault.publishKey", &json!({ "publicKey": public_b64(&VAULT_A) })).expect("the key published, the local vault founded"); unlock(handle, &VAULT_A).expect("the local vault opens"); let made = crate::methods::dispatch(handle, "vault.create", &json!({ "kind": "login", "name": "An invented login", "site": "example.com", "username": "someone", "fields": { "password": "an-invented-password-1" } })).expect("a login"); made["id"].as_str().expect("an id").to_string()}/// The vault key row the object holds for `device`, wrapping `vmk` to `secret`'s public half: what an approval writes.fn vault_row(device: &str, secret: &[u8; 32], vmk: &[u8; 32]) -> Value { let wrapped = cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(secret), vmk).expect("a wrap"); json!({ "workspace_id": DATABASE, "device_id": device, "public_key": public_b64(secret), "wrapped_vmk": wrapped, "vmk_version": 1, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z" })}/// Phone B signs in to the account, is let in by an approval that wraps `vmk` to its key, and reads.fn read_on_a_second_phone(door: &Arc<Door>, vmk: &[u8; 32], password_id: &str) -> (Value, usize) { let (_dir, b) = second_phone(); call_with(&b, "personal.connect", &ask(), Arc::clone(door) as Arc<dyn Exchange>).expect("B signs in"); let device_b = b.client().self_device_id().expect("B's device id"); door.rows.lock().unwrap().insert(("vault_key".into(), format!("approved-{device_b}")), vault_row(&device_b, &VAULT_B, vmk)); for _ in 0..3 { b.client().sync_now().expect("a pass"); } unlock(&b, &VAULT_B).expect("B opens the account's vault"); let revealed = crate::methods::dispatch(&b, "vault.reveal", &json!({ "id": password_id })).expect("B reads the password"); let copy = rusqlite::Connection::open(b.client().layout().replica(DATABASE)).expect("B's copy"); let notes: i64 = copy.query_row("SELECT COUNT(*) FROM cotton_notes", [], |row| row.get(0)).expect("B's notes"); (revealed, notes as usize)}/// RULE (KEPT FOUR 2, decision a; review LOW): a note and a password made before a FIRST-EVER sign-in: the local/// vault key founds the account (its wrap goes up first), the password goes up as it is, and a second phone let in/// reads both. Nothing is kept on phone A afterwards.#[test]fn a_password_made_before_a_first_ever_sign_in_is_read_on_a_second_phone() { let (_dir, a) = phone(); let local = started_here(&a); note(&a, "An invented note"); let password = password_before_sign_in(&a); let door = Door::new(); let (_, ended) = back_up(&a, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); let taken = door.taken.lock().unwrap().clone(); let first_vault = taken.iter().position(|act| act["args"]["table"] == "vault_key"); let first_secret = taken.iter().position(|act| act["args"]["table"] == "secret"); assert!(first_vault.is_some() && first_secret.is_some() && first_vault < first_secret, "the local key's wrap founds the account before the password goes: {taken:?}"); // What phone B's approval wraps is the very key phone A founded with. let founder = door.rows.lock().unwrap().iter().find(|((table, _), _)| table == "vault_key").map(|(_, data)| data.clone()).expect("the founding wrap"); let vmk: [u8; 32] = cotton_core::vault::unwrap(&VAULT_A, founder["wrapped_vmk"].as_str().unwrap()).expect("A's key opens its wrap").try_into().unwrap(); let (revealed, notes) = read_on_a_second_phone(&door, &vmk, &password); assert!(revealed.to_string().contains("an-invented-password-1"), "{revealed}"); assert_eq!(notes, 1); assert!(cotton_client::copy_keep::kept(a.client().layout(), Some(DATABASE)).is_empty(), "nothing kept: the key is the account's"); assert!(!a.client().layout().replica(&local).exists());}/// RULE (KEPT FOUR 2, decision b; review H1 and LOW): a note and a password made before signing in to an account that/// ALREADY has a vault: the password is never posted under the local key; the local copy stays kept, holding the only/// wrap of the local key, until phone A's next unlock seals the password again under the account's key; then a second/// phone reads it, and the kept copy goes.#[test]fn a_password_made_before_signing_in_to_an_account_with_a_vault_is_sealed_again_and_read_on_a_second_phone() { let (_dir, a) = phone(); let local = started_here(&a); note(&a, "An invented note"); let password = password_before_sign_in(&a); let door = Door::new(); let account_vmk = [42u8; 32]; let device_a = a.client().self_device_id().expect("A's device id"); door.rows.lock().unwrap().insert(("vault_state".into(), DATABASE.into()), json!({ "workspace_id": DATABASE, "vmk_version": 1, "rotated_at": "2026-10-20T09:00:00.000Z", "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z" })); // Phone A was let in already (an approval from the account's first phone). door.rows.lock().unwrap().insert(("vault_key".into(), format!("approved-{device_a}")), vault_row(&device_a, &VAULT_A, &account_vmk)); let (_, ended) = back_up(&a, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); let taken = door.taken.lock().unwrap().clone(); assert!(!taken.iter().any(|act| act["args"]["table"] == "secret"), "no password goes up under the local key: {taken:?}"); // No rival wrap: this phone's own row, published and given the account's wrap (`take_own_key`), and nothing else. for act in taken.iter().filter(|act| act["args"]["table"] == "vault_key") { assert!(!act["args"]["id"].as_str().unwrap_or_default().starts_with("founder:"), "the local key's founding never goes: {act}"); if let Some(wrapped) = act["args"]["data"]["wrapped_vmk"].as_str() { assert_eq!(cotton_core::vault::unwrap(&VAULT_A, wrapped).as_deref(), Some(&account_vmk[..]), "every wrap sent is of the account's key"); } } let layout = a.client().layout().clone(); let kept = cotton_client::copy_keep::kept(&layout, Some(DATABASE)); assert_eq!(kept.len(), 1, "the local copy is kept, with the only wrap of its key"); password_waits_quietly(&layout); // A's next unlock seals it again under the account's key, and it goes up. unlock(&a, &VAULT_A).expect("A opens the account's vault"); for _ in 0..3 { a.client().sync_now().expect("a pass"); } assert!(door.rows.lock().unwrap().contains_key(&("secret".to_string(), password.clone())), "the password reached the account: {:?}", door.taken.lock().unwrap()); assert!(!cotton_client::copy_keep::kept_changes(&layout, DATABASE).iter().any(|change| change.table == "cotton_secrets"), "it waits no more"); let (revealed, notes) = read_on_a_second_phone(&door, &account_vmk, &password); assert!(revealed.to_string().contains("an-invented-password-1"), "{revealed}"); assert_eq!(notes, 1); // KEPT FOUR 3 C: a complete read of the server (each pass's own, and this one) finds the password sealed again // there: the key is let go, and the next recovery lets the kept copy go. crate::phone::vault_carry::settle_after_pass(&a.client()); assert!(cotton_client::vault_keep::key_files(&layout).unwrap().is_empty(), "the server holds it sealed again: the key is let go"); let live = layout.replica(DATABASE); let db = cotton_store::driver::Driver::open(&live).expect("the copy"); let mut ids = cotton_client::seams::op_ids(Arc::new(cotton_client::seams::SystemRandom)); cotton_client::copy_keep::recover(&layout, DATABASE, &db, &live, chrono::Utc::now().timestamp_millis(), &mut ids).expect("recovery"); assert!(cotton_client::copy_keep::kept(&layout, Some(DATABASE)).is_empty(), "the kept copy goes once nothing depends on its key"); assert!(!layout.replica(&local).exists());}/// The password waits with the local key in its own file, recorded there, and is not shown as a kept change/// (KEPT FOUR 3 B: nothing on the Sync screen).fn password_waits_quietly(layout: &cotton_client::layout::Layout) { let files = cotton_client::vault_keep::key_files(layout).expect("the key files"); assert!(files.iter().any(|file| file.sealed.iter().any(|row| row.table == "cotton_secrets")), "the password waits with its key: {files:?}"); assert!(!cotton_client::copy_keep::kept_changes(layout, DATABASE).iter().any(|change| change.table == "cotton_secrets"), "never shown as kept");}/// RULE (KEPT FOUR 3 B): a phone whose founding the object refuses (another phone founded the account first, after/// this one heard no vault) drops its founding: never a kept row, never written down as refused, never counted, never/// posted again; its key stays in its own file and the password waits for the re-seal, with nothing on the Sync screen.#[test]fn a_founding_the_object_refuses_is_dropped_quietly_and_its_key_kept() { let (_dir, a) = phone(); started_here(&a); note(&a, "An invented note"); let _password = password_before_sign_in(&a); let door = Door::new(); door.refuses.lock().unwrap().push("vault_key".into()); let (_, ended) = back_up(&a, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert_eq!(ended["adopt"]["refused"], json!(0), "a founding given way is not a refusal: {ended}"); let layout = a.client().layout().clone(); assert!(!cotton_client::unsent::kept_rows(&layout, DATABASE).iter().any(|row| cotton_client::founding::is_founding(&row.table)), "never a kept row"); let discarded = serde_json::to_string(&cotton_client::unsent::discarded(&layout, DATABASE)).unwrap(); assert!(!discarded.contains("cotton_vault_keys"), "never written down as refused: {discarded}"); assert!(!door.taken.lock().unwrap().iter().any(|act| act["args"]["table"] == "secret"), "nothing posted under the local key"); let files = cotton_client::vault_keep::key_files(&layout).unwrap(); assert_eq!(files.len(), 1, "the local key in its own file"); assert_eq!(files[0].account.as_deref(), Some(DATABASE)); password_waits_quietly(&layout); // Later passes never post the founding again. let before = door.taken.lock().unwrap().len(); for _ in 0..2 { a.client().sync_now().expect("a pass"); } assert!(!door.taken.lock().unwrap()[before..].iter().any(|act| act["args"]["table"] == "vault_key" && act["args"]["id"].as_str().is_some_and(|id| id.starts_with("founder:"))), "never posted again");}/// RULE (KEPT FOUR 2, decision b): into an account with a vault whose key is not yet on this phone (waiting for an/// approval), the password waits and the local key stays: an unlock opens nothing, nothing is carried.#[test]fn a_password_waits_with_its_local_key_until_this_phone_is_let_in() { let (_dir, a) = phone(); started_here(&a); let _password = password_before_sign_in(&a); let door = Door::new(); door.rows.lock().unwrap().insert(("vault_state".into(), DATABASE.into()), json!({ "workspace_id": DATABASE, "vmk_version": 1, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z" })); door.rows.lock().unwrap().insert(("vault_key".into(), "the-first-phone".into()), vault_row("another-device", &[99; 32], &[42; 32])); let (_, ended) = back_up(&a, &door); assert_eq!(ended["adopt"]["status"], DONE, "{ended}"); assert!(unlock(&a, &VAULT_A).is_err(), "not let in yet"); let layout = a.client().layout().clone(); assert_eq!(cotton_client::copy_keep::kept(&layout, Some(DATABASE)).len(), 1, "the local key stays"); password_waits_quietly(&layout); let live = layout.replica(DATABASE); let db = cotton_store::driver::Driver::open(&live).expect("the copy"); let mut ids = cotton_client::seams::op_ids(Arc::new(cotton_client::seams::SystemRandom)); cotton_client::copy_keep::recover(&layout, DATABASE, &db, &live, chrono::Utc::now().timestamp_millis(), &mut ids).expect("recovery"); assert_eq!(cotton_client::copy_keep::kept(&layout, Some(DATABASE)).len(), 1, "recovery never takes it");}/// The ledger rows a capture wrote: the original's and its renditions'.fn ledger_of(handle: &CottonHandle, key: &str) -> cotton_store::media_ledger::MediaRow { handle.client().with_file(|file| cotton_store::media_ledger::media_by_key(file.driver, key).map_err(|error| error.to_string())).expect("a read").expect("a row")}/// RULE: A capture copied from Photos says so on its ledger row (source photos, not captured here, so it may leave once the object holds it), goes by the rule it was given (wifi) with who asked, and its renditions go by the same rule and stay; a capture that says nothing is every app's capture as before (any network, captured here).#[test]fn a_capture_from_photos_carries_its_rule_and_its_source() { let (dir, handle) = phone(); started_here(&handle); let picked = dir.path().join("kept.jpg"); std::fs::write(&picked, b"an invented Photos original").expect("a synthetic file"); let thumb = dir.path().join("kept-thumb.jpg"); std::fs::write(&thumb, b"an invented thumbnail").expect("a synthetic file"); let filed = crate::methods::dispatch( &handle, "capture.media", &json!({"path": picked.to_string_lossy(), "mime": "image/jpeg", "filename": "kept.jpg", "kind": "photo", "thumbPath": thumb.to_string_lossy(), "network": "wifi", "askedBy": "albums.keep", "source": "photos"}), ) .expect("filed"); let key = filed["key"].as_str().expect("a key").to_string(); let original = ledger_of(&handle, &key); assert_eq!((original.network.as_str(), original.asked_by.as_deref(), original.source.as_deref(), original.captured_here), ("wifi", Some("albums.keep"), Some("photos"), false)); let renditions = handle .client() .with_file(|file| file.driver.all("SELECT key FROM _media WHERE key <> ? AND tier = 'thumb'", &[rusqlite::types::Value::Text(key.clone())]).map_err(|error| error.to_string())) .expect("a read"); assert_eq!(renditions.len(), 1, "the thumbnail was queued"); let thumb_row = ledger_of(&handle, renditions[0].text("key").expect("a key")); assert_eq!((thumb_row.network.as_str(), thumb_row.source.as_deref()), ("wifi", None), "a rendition goes by the rule and stays here"); let plain = picture(&handle, dir.path()); let plain = ledger_of(&handle, &plain); assert_eq!((plain.network.as_str(), plain.asked_by.as_deref(), plain.source.as_deref(), plain.captured_here), ("any", None, None, true));}/// RULE: A capture's upload words are checked before a byte moves: a network rule other than any or wifi, a source other than photos, or a document from Photos is refused.#[test]fn a_capture_with_an_unknown_rule_is_refused_before_a_byte_moves() { let (dir, handle) = phone(); started_here(&handle); let picked = dir.path().join("x.jpg"); std::fs::write(&picked, b"an invented picture").expect("a synthetic file"); for (extra, kind) in [(json!({"network": "satellite"}), "photo"), (json!({"source": "drive"}), "photo"), (json!({"source": "photos"}), "document")] { let mut request = json!({"path": picked.to_string_lossy(), "mime": if kind == "photo" { "image/jpeg" } else { "application/pdf" }, "filename": "x.jpg", "kind": kind}); for (field, value) in extra.as_object().expect("an object") { request[field] = value.clone(); } let refused = crate::methods::dispatch(&handle, "capture.media", &request).expect_err("refused"); assert_eq!(refused.code, "bad_request", "{request}"); }}