3496 lines · 231.5 KB · RustRaw
//! `personal.connect` against a scripted personal object: the copy it makes,//! the connection it writes, and the copy it makes again.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_client::transport::Exchange;use serde_json::json;use super::*;const DATABASE: &str = "11111111-1111-4111-8111-111111111111";pub(super) fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, cotton()); (dir, handle)}/// The phone in `dir` opened as the app `manifest` says.fn phone_in(dir: &tempfile::TempDir, manifest: serde_json::Value) -> CottonHandle { 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")}/// Cotton Books' manifest, as the app sends it.fn books() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/books/flavour.json")).expect("Books' manifest")}/// Cotton's own manifest, as the app sends it.pub(super) fn cotton() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")}fn object(role: &str) -> Arc<ScriptedExchange> { ScriptedExchange::new([ Reply::ok(&json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": [], "tables": [], "etag": "e1"}).to_string()), Reply::ok(&json!({"person": {"id": "owner-person", "phone": "+919000000009", "role": role}, "version": 3}).to_string()), ])}fn ask() -> serde_json::Value { json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "credential": "synthetic-credential", "windows": {"message": 90}, "deviceName": "An invented phone"})}#[test]fn a_code_is_asked_by_number_at_the_open_host_and_names_the_database() { let (_dir, handle) = phone(); let exchange = ScriptedExchange::new([Reply::ok(&json!({"challenge_id": "ch-1", "expires_in": 300, "known": false, "database_id": DATABASE, "host": "https://cotton.example.com"}).to_string())]); let answer = call_with(&handle, "personal.code", &json!({"server": "https://cotton.example.com", "phone": "+919000000009"}), Arc::clone(&exchange) as Arc<dyn Exchange>).expect("a challenge"); assert_eq!(answer, json!({"challengeId": "ch-1", "expiresIn": 300, "known": false, "databaseId": DATABASE, "sentTo": "We sent a code by text message to +91 ••••••••09."})); let asked = exchange.only(); assert_eq!((asked.method.as_str(), asked.path.as_str()), ("POST", "/v1/code"), "no slug and no prefix: the number finds the database"); let body: serde_json::Value = serde_json::from_slice(&asked.body).expect("a JSON body"); assert_eq!(body["phone"], "+919000000009"); assert_eq!(body["device_id"].as_str(), handle.client().self_device_id().as_deref());}/// RULE (NEXT-SIGNIN, owner, 28 Nov 2026): the card never shows the number back in full: its country code and its/// last two digits, decided here so both phones say the same.#[test]fn the_number_a_code_went_to_is_shown_masked() { use crate::phone::personal_object::masked_number; assert_eq!(masked_number("+919000000009"), "+91 ••••••••09"); assert_eq!(masked_number("+91 98765 43210"), "+91 ••••••••10"); assert_eq!(masked_number("+15550100199"), "+1 ••••••••99"); assert_eq!(masked_number("+447700900123"), "+44 ••••••••23"); assert_eq!(masked_number("+971500000012"), "+971 •••••••12"); assert_eq!(masked_number("+79000000042"), "+7 ••••••••42"); assert_eq!(masked_number("9000000009"), "••••••••09"); assert_eq!(masked_number("+91"), "+91 "); assert_eq!(masked_number(""), ""); for number in ["+919000000009", "+15550100199", "+971500000012"] { let line = crate::phone::personal_object::sent_to(number); assert!(!line.contains(&number[3..]), "{line}"); assert!(line.starts_with("We sent a code by text message to +"), "{line}"); }}/// RULE (NEXT-SIGNIN, owner, 28 Nov 2026): the name is asked only of a new account, after its code is proved. A card/// that says `nameAfter` sends the code alone; a new account is answered `nameNeeded` (no credential), and the same/// code goes again with the name.#[test]fn a_new_account_is_asked_its_name_only_after_the_code() { let (_dir, handle) = phone(); let granted = json!({"credential": format!("ctd_{DATABASE}_synthetic"), "person": {"id": "owner-person", "role": "owner"}, "version": 4, "expires_in": 7_776_000, "database_id": DATABASE}); let exchange = ScriptedExchange::new([Reply::ok(&json!({"name_needed": true, "database_id": DATABASE}).to_string()), Reply::ok(&granted.to_string())]); let ask = json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "challengeId": "ch-1", "code": "123456", "nameAfter": true}); let first = call_with(&handle, "personal.signIn", &ask, Arc::clone(&exchange) as Arc<dyn Exchange>).expect("proved"); assert_eq!(first, json!({"nameNeeded": true})); let mut named = ask.clone(); named["name"] = json!("Asha Invented"); let second = call_with(&handle, "personal.signIn", &named, Arc::clone(&exchange) as Arc<dyn Exchange>).expect("signed in"); assert_eq!(second["credential"], format!("ctd_{DATABASE}_synthetic")); let sent = exchange.seen(); let bodies: Vec<serde_json::Value> = sent.iter().map(|r| serde_json::from_slice(&r.body).expect("a JSON body")).collect(); assert_eq!(bodies[0]["name_after"], true); assert!(bodies[0].get("name").is_none(), "the code goes alone"); assert_eq!((bodies[1]["code"].as_str(), bodies[1]["name"].as_str()), (Some("123456"), Some("Asha Invented")), "the same code, with the name");}/// RULE (the launch walk, 22 Nov 2026: Send code on an empty field said "could not do that just now. Try again."): no/// number typed is `bad_phone`, which the phones say as a number that cannot take a code, and nothing is sent.#[test]fn a_code_with_no_number_typed_is_a_bad_phone_and_asks_nothing() { let (_dir, handle) = phone(); for blank in [json!(""), json!(" "), serde_json::Value::Null] { let exchange = ScriptedExchange::new([]); let refused = call_with(&handle, "personal.code", &json!({"server": "https://cotton.example.com", "phone": blank}), Arc::clone(&exchange) as Arc<dyn Exchange>).unwrap_err(); assert_eq!(refused.code, "bad_phone", "{blank}"); assert_eq!(exchange.calls(), 0, "nothing was sent for {blank}"); }}#[test]fn a_sign_in_proves_the_code_at_its_database_and_hands_back_the_credential() { let (_dir, handle) = phone(); let granted = json!({"credential": format!("ctd_{DATABASE}_synthetic"), "person": {"id": "owner-person", "role": "owner"}, "version": 4, "expires_in": 7_776_000, "database_id": DATABASE, "host": "https://cotton.example.com"}); let exchange = ScriptedExchange::new([Reply::ok(&granted.to_string())]); let ask = json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "challengeId": "ch-1", "code": "123456", "name": " "}); let answer = call_with(&handle, "personal.signIn", &ask, Arc::clone(&exchange) as Arc<dyn Exchange>).expect("signed in"); assert_eq!(answer, json!({"credential": format!("ctd_{DATABASE}_synthetic"), "person": {"id": "owner-person", "role": "owner"}, "expiresIn": 7_776_000, "databaseId": DATABASE})); let asked = exchange.only(); assert_eq!(asked.path, "/v1/sign-in"); let body: serde_json::Value = serde_json::from_slice(&asked.body).expect("a JSON body"); assert_eq!(body["database_id"], DATABASE); assert_eq!(body["challenge_id"], "ch-1"); assert_eq!(body["code"], "123456"); assert!(body.get("name").is_none(), "a blank name is not sent"); let mut missing = ask.clone(); missing.as_object_mut().expect("an object").remove("databaseId"); assert_eq!(call_with(&handle, "personal.signIn", &missing, ScriptedExchange::new([]) as Arc<dyn Exchange>).unwrap_err().code, "bad_request");}#[test]fn connect_refuses_an_object_that_is_not_the_database_the_sign_in_named() { let (_dir, handle) = phone(); let mut other = ask(); other["databaseId"] = json!("22222222-2222-4222-8222-222222222222"); let refused = call_with(&handle, "personal.connect", &other, object("owner") as Arc<dyn Exchange>).unwrap_err(); assert_eq!(refused.code, "wrong_database"); assert!(!handle.client().layout().connection_json().exists(), "nothing is made for a database the object is not");}#[test]fn connect_makes_the_objects_copy_mine_and_names_the_object_its_server() { let (_dir, handle) = phone(); let exchange = object("owner"); let answer = call_with(&handle, "personal.connect", &ask(), Arc::clone(&exchange) as Arc<dyn Exchange>).expect("connected"); assert_eq!(answer["databaseId"], DATABASE); assert_eq!(answer, json!({"databaseId": DATABASE, "ownerId": answer["ownerId"]}), "nothing else is said"); let layout = handle.client().layout().clone(); assert!(layout.replica(DATABASE).exists(), "the copy is where the loop opens it"); let mine = cotton_client::connection::ConnectionFile::at(layout.connection_json()).read().expect("a connection"); assert_eq!(mine.workspace_id.as_deref(), Some(DATABASE)); assert_eq!(mine.base_url, "https://cotton.example.com"); assert_eq!(exchange.nth(0).header("authorization"), Some("Bearer synthetic-credential"), "on the open host the bearer names the object, even for its definitions"); assert_eq!(exchange.nth(0).path, "/v1/definitions"); assert_eq!(exchange.nth(1).header("authorization"), Some("Bearer synthetic-credential")); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); let copy = rusqlite::Connection::open(layout.replica(DATABASE)).expect("the copy"); let named: String = copy .query_row("SELECT name FROM cotton_devices WHERE device_id = ?1 AND revoked_at IS NULL", [handle.identity().device_id.clone().expect("a key")], |row| row.get(0)) .expect("this phone is in its own device list"); assert_eq!(named, "An invented phone");}/// A phone signed in syncs with Cotton's server: its sync line names no Mac/// (launch walk of Words, 22 Nov 2026: "Up to date with your Mac" and/// "Sending 4 changes to your Mac" in shell.home on a phone).#[test]fn a_signed_in_phones_sync_line_names_no_mac() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let status = handle.client().sync_status(); let line = &status["status"]["line"]; assert_eq!(status["status"]["withCotton"], true, "{status}"); assert_eq!(line["state"], "not_reached", "no pass has answered yet: {line}"); assert_eq!(line["words"], "Cotton not reached yet"); // A later launch, its copy already here (marked as the object's when it was made). handle.client().detach(); crate::phone::personal_object::let_go(&handle.client()); let status = handle.client().sync_status(); assert!(status["status"]["line"]["words"].as_str().is_some_and(|words| !words.contains("Mac")), "{status}");}/// RULE (29 Oct 2026): a copy this sign-in does not name as the object's — made under another address of the same database — is the object's cache made again, never set aside beside itself or synced over: its file goes with its journal and the note an earlier build's stopped move left, and the object's copy starts in its place.#[test]fn a_copy_this_sign_in_does_not_name_is_made_again_and_nothing_is_set_aside() { let (_dir, handle) = phone(); let layout = handle.client().layout().clone(); let earlier = layout.replica(DATABASE); std::fs::create_dir_all(earlier.parent().expect("a folder")).expect("the folder"); drop(crate::fixture::seeded(&earlier)); rusqlite::Connection::open(&earlier).expect("the earlier copy").execute_batch("CREATE TABLE invented_marker (x)").expect("a marker"); let note = std::path::PathBuf::from(format!("{}{}", earlier.display(), cotton_client::bootstrap::not_moved::NOT_MOVED_SUFFIX)); std::fs::write(¬e, r#"{"stamped": 140, "why": "an earlier build's reason"}"#).expect("the note"); // The synthetic life holds messages and emails, which go up sealed: a // phone with no data key keeps the copy (`copy_kept`), so this one holds one. handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::mint()); // The object is asked what it holds and takes the rows it lacks before the copy goes (11 Nov 2026). let answer = call_with(&handle, "personal.connect", &ask(), the_garden() as Arc<dyn Exchange>).expect("connected"); assert!(answer.get("setAside").is_none(), "nothing is set aside: {answer}"); let copy = rusqlite::Connection::open(&earlier).expect("the copy"); let marker: i64 = copy.query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = 'invented_marker'", [], |row| row.get(0)).expect("a count"); assert_eq!(marker, 0, "the earlier copy was made again, not kept"); assert_eq!(stamp(©), cotton_store::migrate::SCHEMA_VERSION); assert!(!note.exists(), "the earlier build's note went with its copy"); let beside: Vec<String> = std::fs::read_dir(earlier.parent().expect("a folder")).expect("the folder").filter_map(|entry| entry.ok()?.file_name().into_string().ok()).collect(); assert!(!beside.iter().any(|name| name.contains("relay")), "no copy beside it: {beside:?}");}#[test]fn only_the_owner_keeps_a_copy_and_a_window_names_a_kept_table() { let (_dir, handle) = phone(); let refused = call_with(&handle, "personal.connect", &ask(), object("staff") as Arc<dyn Exchange>).unwrap_err(); assert_eq!(refused.code, "owner_only"); let mut unknown = ask(); unknown["windows"] = json!({"no_such_table": 30}); assert_eq!(call_with(&handle, "personal.connect", &unknown, object("owner") as Arc<dyn Exchange>).unwrap_err().code, "bad_request");}/// RULE (launch-fast, 21 Nov 2026): the data key the shell keeps for the database rides the connect, so the core holds it before the copy's first pass pulls a page and no sealed row of a launch is parked for want of it.#[test]fn the_kept_data_key_rides_the_connect_and_is_held_before_any_pass() { use base64::Engine; let (_dir, handle) = phone(); let mut asked = ask(); asked["dataKey"] = json!(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([7u8; 32])); call_with(&handle, "personal.connect", &asked, object("owner") as Arc<dyn Exchange>).expect("connected"); let status = crate::methods::dispatch(&handle, "seal.status", &json!({})).expect("the seal's status"); assert_eq!(status["keyHeld"], json!(true), "held at the connect: {status}"); let mut bad = ask(); bad["dataKey"] = json!("not a key"); assert_eq!(call_with(&handle, "personal.connect", &bad, object("owner") as Arc<dyn Exchange>).unwrap_err().code, "bad_request");}#[test]fn a_later_launch_connects_its_copy_without_asking_the_object() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("the first launch"); handle.client().detach(); let offline = ScriptedExchange::new([]); let answer = call_with(&handle, "personal.connect", &ask(), Arc::clone(&offline) as Arc<dyn Exchange>).expect("connected offline"); assert_eq!(answer["databaseId"], DATABASE); assert_eq!(answer["ownerId"], "owner-person"); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE));}#[test]fn a_picture_is_the_objects_original_at_the_width_the_card_draws() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let replica = handle.client().layout().replica(DATABASE); let sha = "a".repeat(64); let original = format!("{DATABASE}/photos/{sha}.heic"); rusqlite::Connection::open(&replica) .expect("the copy") .execute( "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) \ VALUES ('photo:' || ?3, ?1, ?2, ?3, 'image/heic', 10, '2026-10-20T09:00:00Z', '2026-10-20T09:00:00Z', '2026-10-20T09:00:00Z')", rusqlite::params![DATABASE, original, sha], ) .expect("a photo"); let exchange = ScriptedExchange::new([Reply::new(200, b"thumb".to_vec()), Reply::new(200, b"poster".to_vec()), Reply::json(404, r#"{"code": "not_found", "message": "no such picture"}"#)]); let media = ObjectMedia { transport: ObjectMediaTransport::new(ObjectAddress::open("https://cotton.example.com").expect("an address"), Arc::clone(&exchange) as Arc<dyn Exchange>, "synthetic-credential".into()), replica, stories: None, }; let dir = tempfile::tempdir().expect("a folder"); let dest = dir.path().join("picture"); use crate::phone::media::MediaFetch as _; // R6: the rendition the device made is its own file under its own key, asked first. media.fetch_to(DATABASE, &format!("{DATABASE}/photos/{sha}.t256.jpg"), &dest).expect("a thumbnail"); assert_eq!(std::fs::read(&dest).expect("written"), b"thumb"); assert_eq!(exchange.nth(0).path, format!("/v1/media/{DATABASE}/photos/{sha}.t256.jpg")); assert_eq!(exchange.nth(0).header("authorization"), Some("Bearer synthetic-credential")); media.fetch_to(DATABASE, &format!("{DATABASE}/videos/{sha}.d1600.jpg"), &dest).expect("a poster"); assert_eq!(exchange.nth(1).path, format!("/v1/media/{DATABASE}/videos/{sha}.d1600.jpg")); let missing = media.fetch_to(DATABASE, &format!("{DATABASE}/attachments/nothing.pdf"), &dest).unwrap_err(); assert_eq!(exchange.nth(2).path, format!("/v1/media/{DATABASE}/attachments/nothing.pdf")); assert_eq!(missing.status, Some(404)); let unknown = media.fetch_to(DATABASE, &format!("{DATABASE}/photos/{}.t256.jpg", "b".repeat(64)), &dest).unwrap_err(); assert_eq!(unknown.status, Some(404), "a hash this copy has no photo of is asked of nobody"); assert_eq!(exchange.calls(), 3); // The sweep uses that same authenticated transport and lands the result // in the ledger/store location read.mediaPath (and the deck) reads. let door = ScriptedExchange::new([Reply::new(200, b"swept thumb".to_vec())]); handle.client().set_media_fetch(Some(Arc::new(ObjectMedia { transport: ObjectMediaTransport::new(ObjectAddress::open("https://cotton.example.com").unwrap(), Arc::clone(&door) as Arc<dyn Exchange>, "synthetic-credential".into()), replica: handle.client().layout().replica(DATABASE), stories: None, }))); let pass = crate::phone::media_sweep::run(&handle.client(), handle.events(), crate::phone::media_sweep::Caps { fetches: 1, in_flight: 1 }).expect("swept"); assert_eq!(pass.landed, 1); assert_eq!(pass.failed, 0); assert_eq!(door.nth(0).path, format!("/v1/media/{DATABASE}/photos/{sha}.t256.jpg")); assert_eq!(door.nth(0).header("authorization"), Some("Bearer synthetic-credential")); let thumb = format!("{DATABASE}/photos/{sha}.t256.jpg"); let path = handle.client().with_file(|file| Ok(crate::phone::media::local_path_of(file.driver, &thumb))).unwrap().expect("the deck's thumbnail"); assert_eq!(std::fs::read(path).unwrap(), b"swept thumb");}/// RULE (R6): a rendition no device made is drawn by the object only from a clear original stored before R6; a/// sealed original is never drawn there (`sealed_file`), so the original itself comes down, opened, in its place.#[test]fn a_rendition_no_device_made_falls_back_to_the_clear_original_or_the_original_whole() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let replica = handle.client().layout().replica(DATABASE); let sha = "c".repeat(64); let original = format!("{DATABASE}/photos/{sha}.jpg"); rusqlite::Connection::open(&replica) .expect("the copy") .execute( "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) \ VALUES ('photo:' || ?3, ?1, ?2, ?3, 'image/jpeg', 10, '2026-10-20T09:00:00Z', '2026-10-20T09:00:00Z', '2026-10-20T09:00:00Z')", rusqlite::params![DATABASE, original, sha], ) .expect("a photo"); let none = || Reply::json(404, r#"{"code": "not_found", "message": "no such media"}"#); let exchange = ScriptedExchange::new([ none(), Reply::new(200, b"drawn by the object".to_vec()), none(), Reply::json(400, r#"{"code": "sealed_file", "message": "a sealed file is never drawn at a size"}"#), Reply::new(200, b"the original".to_vec()), ]); let media = ObjectMedia { transport: ObjectMediaTransport::new(ObjectAddress::open("https://cotton.example.com").expect("an address"), Arc::clone(&exchange) as Arc<dyn Exchange>, "synthetic-credential".into()), replica, stories: None, }; let dir = tempfile::tempdir().expect("a folder"); let dest = dir.path().join("picture"); use crate::phone::media::MediaFetch as _; let thumb = format!("{DATABASE}/photos/{sha}.t256.jpg"); media.fetch_to(DATABASE, &thumb, &dest).expect("drawn from a clear original"); assert_eq!(std::fs::read(&dest).unwrap(), b"drawn by the object"); assert_eq!(exchange.nth(1).path, format!("/v1/media/{original}?width=256")); media.fetch_to(DATABASE, &thumb, &dest).expect("the original in its place"); assert_eq!(exchange.nth(3).path, format!("/v1/media/{original}?width=256")); assert_eq!(exchange.nth(4).path, format!("/v1/media/{original}")); assert_eq!(std::fs::read(&dest).unwrap(), b"the original");}/// RULE: a chat picture's thumbnail is the object's picture at 256 pixels, found by the key its thumbnail carries; the phone never asks for the picture whole to make one.#[test]fn a_chat_pictures_thumbnail_is_the_objects_picture_at_256_pixels() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let replica = handle.client().layout().replica(DATABASE); let exchange = ScriptedExchange::new([Reply::new(200, b"thumb".to_vec())]); let media = ObjectMedia { transport: ObjectMediaTransport::new(ObjectAddress::named("https://cotton.example.com", "asha").expect("an address"), Arc::clone(&exchange) as Arc<dyn Exchange>, "synthetic-credential".into()), replica, stories: None, }; let dir = tempfile::tempdir().expect("a folder"); let dest = dir.path().join("picture"); use crate::phone::media::MediaFetch as _; let picture = format!("{DATABASE}/messages/thread-1/{}.png", "c".repeat(64)); let thumb = cotton_core::media::keys::thumb_key_for(&picture).expect("a chat's picture has a thumbnail"); media.fetch_to(DATABASE, &thumb, &dest).expect("a thumbnail"); assert_eq!(std::fs::read(&dest).expect("written"), b"thumb"); assert_eq!(exchange.nth(0).path, format!("/v1/media/{picture}?width=256")); assert_eq!(exchange.calls(), 1);}#[test]fn a_sync_the_object_answers_401_signs_the_phone_out_and_keeps_its_copy() { let (_dir, handle) = phone(); // The object, then a refusal for every pass after (the loop may dial first). let revoked = || Reply::json(401, r#"{"code": "credential_revoked", "message": "this sign-in was ended; sign in again"}"#); let exchange = ScriptedExchange::new([ Reply::ok(&json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": [], "tables": [], "etag": "e1"}).to_string()), Reply::ok(&json!({"person": {"id": "owner-person", "phone": "+919000000009", "role": "owner"}, "version": 3}).to_string()), revoked(), revoked(), revoked(), revoked(), ]); call_with(&handle, "personal.connect", &ask(), Arc::clone(&exchange) as Arc<dyn Exchange>).expect("connected"); assert!(handle.client().sync_now().is_err(), "the pass fails"); let _ = handle.client().sync_now(); let said: Vec<serde_json::Value> = handle .events() .buffered_events() .into_iter() .filter(|event| event["payload"]["phase"] == "personal") .collect(); assert_eq!(said.len(), 1, "told once: {said:?}"); assert_eq!(said[0]["payload"]["stage"], SIGNED_OUT); assert_eq!(said[0]["payload"]["code"], "credential_revoked"); assert!(handle.client().layout().replica(DATABASE).exists(), "the copy stays"); assert_eq!(exchange.calls(), 3, "a signed-out phone dials the object no more");}/// The device id a sign-in names — and the object files the phone's row/// under — is the public half of the key the Keychain holds, handed down at/// open (`OpenConfig.device_secret`), never anything in the container: a/// phone whose container is gone and whose Keychain is kept (a reinstall)/// signs in and syncs as the same device.#[test]fn the_device_a_sign_in_names_outlives_the_container_when_the_keychain_holds_its_key() { let asked = |handle: &CottonHandle| -> String { let exchange = ScriptedExchange::new([Reply::ok(r#"{"challenge_id": "ch-1", "expires_in": 300, "known": true}"#)]); crate::phone::business::call_with(handle, "business.code", &json!({"server": "https://cotton.example.com", "slug": "asha", "phone": "+919000000009"}), exchange.as_ref()) .expect("a code asked for"); let sent: serde_json::Value = serde_json::from_slice(&exchange.nth(0).body).expect("a JSON body"); sent["device_id"].as_str().expect("the device id").to_string() }; let (container, before) = phone(); let signed_in_as = asked(&before); assert_eq!(before.identity().source, "keychain"); drop(before); drop(container); let (_fresh, after) = phone(); assert_eq!(asked(&after), signed_in_as, "the same device to the object after the container is gone"); assert_eq!(after.client().self_device_id().as_deref(), Some(signed_in_as.as_str()));}/// A personal object answering by route, however often and in whatever order/// the loop dials it: its definitions (304 to the etag it serves), a sync page/// at its version with no rows, the owner, and every act taken.#[derive(Debug)]struct Served { definitions: std::sync::Mutex<serde_json::Value>, version: std::sync::Mutex<i64>, /// The rows every sync page carries. rows: std::sync::Mutex<serde_json::Value>, /// Whether `/v1/sync` answers at all: off, no page ever lands. pages: std::sync::atomic::AtomicBool, /// Its sync answers name this phone's device row, so the phone writes on it. names_device: std::sync::atomic::AtomicBool, /// Whether `/v1/act` takes a write: off, it asks for it again later. acts: std::sync::atomic::AtomicBool, /// Every act taken, as posted. taken: std::sync::Mutex<Vec<serde_json::Value>>, /// Every media PUT taken: its path, content type and bytes. media: std::sync::Mutex<Vec<(String, Option<String>, Vec<u8>)>>, /// Set, a pass's first page says more follows, and every later page /// fails with this status — 0 is an object that cannot be reached. stuck_page: std::sync::Mutex<Option<u16>>, /// Every sync page asked, by path. asked: std::sync::Mutex<Vec<String>>, /// Set, how many `restore` calls still land; the next is answered 503. restores_left: std::sync::Mutex<Option<usize>>, /// Set, its pages give the wall clock's time, so a write made now is /// judged now and goes out (off: a fixed October time). serves_now: std::sync::atomic::AtomicBool, /// Set, every `/v1/sync` is answered this status with the Worker's own /// `internal_error` body (the outage of 21 Nov 2026). sync_fails: std::sync::Mutex<Option<u16>>, /// Set, `/v1/definitions` is answered this status with the Worker's own /// `internal_error` body. definitions_fail: std::sync::Mutex<Option<u16>>, /// Set, a pass's first page says more follows, and every later page /// carries a row of a table nothing has placed yet. later_page_unplaced: std::sync::atomic::AtomicBool, /// Set, its sync answers never say `again`, as a Worker before 21 Nov 2026 did. old_worker: std::sync::atomic::AtomicBool, /// The binned rows `/v1/bin` answers, as stored. bin: std::sync::Mutex<serde_json::Value>, /// Set, every `/v1/blind` is answered this status with the Worker's own `internal_error` body. blind_fails: std::sync::Mutex<Option<u16>>, /// The account's own switches every sync page says (`features`, the Worker's `/v1/admin/mail-all`); null says none. features: std::sync::Mutex<serde_json::Value>, /// Set, every sync page and `/v1/me` carry this generation (RESTORE 2), and an act whose `x-cotton-generation` /// is another is refused `409 generation_moved`, landing nothing. generation: std::sync::Mutex<Option<String>>, /// Set with it, the time the server was put back to (`restored_to`). restored_to: std::sync::Mutex<Option<String>>, /// Set, every sync page and act is answered `503 account_frozen` (RESTORE 2: the account held still). frozen: std::sync::atomic::AtomicBool,}/// What the Worker answers when it fails (`apps/business/src/http.ts`).const WORKER_FAILED: &str = r#"{"code": "internal_error", "message": "the business did not answer"}"#;impl Served { fn new(tables: serde_json::Value, tools: serde_json::Value, boards: serde_json::Value, etag: &str) -> Arc<Served> { Arc::new(Served { definitions: std::sync::Mutex::new(served(tables, tools, boards, etag)), version: std::sync::Mutex::new(3), rows: std::sync::Mutex::new(json!([])), pages: std::sync::atomic::AtomicBool::new(true), names_device: std::sync::atomic::AtomicBool::new(false), acts: std::sync::atomic::AtomicBool::new(true), taken: std::sync::Mutex::new(Vec::new()), media: std::sync::Mutex::new(Vec::new()), stuck_page: std::sync::Mutex::new(None), asked: std::sync::Mutex::new(Vec::new()), restores_left: std::sync::Mutex::new(None), serves_now: std::sync::atomic::AtomicBool::new(false), sync_fails: std::sync::Mutex::new(None), definitions_fail: std::sync::Mutex::new(None), later_page_unplaced: std::sync::atomic::AtomicBool::new(false), old_worker: std::sync::atomic::AtomicBool::new(false), bin: std::sync::Mutex::new(json!([])), blind_fails: std::sync::Mutex::new(None), features: std::sync::Mutex::new(serde_json::Value::Null), generation: std::sync::Mutex::new(None), restored_to: std::sync::Mutex::new(None), frozen: std::sync::atomic::AtomicBool::new(false), }) } fn serve(&self, tables: serde_json::Value, tools: serde_json::Value, boards: serde_json::Value, etag: &str) { *self.definitions.lock().expect("the definitions") = served(tables, tools, boards, etag); *self.version.lock().expect("the version") += 1; }}fn served(tables: serde_json::Value, tools: serde_json::Value, boards: serde_json::Value, etag: &str) -> serde_json::Value { json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": tools, "tables": tables, "flavour": {}, "boards": boards, "etag": etag})}/// An invented data-only table as the object serves it.fn served_table(id: &str) -> serde_json::Value { json!({ "id": id, "name": "Bed", "plural": "Beds", "picture": null, "builtin": false, "engine": null, "columns": [{"key": "label", "name": "Label", "type": "text", "required": true}], "title": "label", "date": null, "project": null, "order": null, "slip": {"title": "label", "subtitle": null, "trailing": null, "photo": null, "toggle": null}, "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["label"]}], "instructions": "Invented for a test.", })}impl Served { /// Whether this sync request is the page that fails: noted, and an /// object that cannot be reached fails the request itself. fn asks_stuck_page(&self, path: &str) -> Result<bool, String> { self.asked.lock().expect("the pages asked").push(path.to_string()); match *self.stuck_page.lock().expect("the stuck page") { Some(0) if path.contains("cursor=") => Err("the object could not be reached (invented)".into()), Some(_) => Ok(path.contains("cursor=")), None => Ok(false), } }}impl Exchange for Served { 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> { let failing = |status: &std::sync::Mutex<Option<u16>>| *status.lock().expect("the failing status"); let reply = if self.frozen.load(std::sync::atomic::Ordering::SeqCst) && (request.path.starts_with("/v1/sync") || request.path.starts_with("/v1/act")) { Reply::json(503, r#"{"code": "account_frozen", "message": "the account is held still for a moment", "retry_after_s": 30}"#).with_header("retry-after", "30") } else if let Some(status) = failing(&self.definitions_fail).filter(|_| request.path.starts_with("/v1/definitions")) { Reply::json(status, WORKER_FAILED) } else if let Some(status) = failing(&self.blind_fails).filter(|_| request.path.starts_with("/v1/blind")) { self.asked.lock().expect("the pages asked").push(request.path.to_string()); Reply::json(status, WORKER_FAILED) } else if let Some(status) = failing(&self.sync_fails).filter(|_| request.path.starts_with("/v1/sync")) { self.asked.lock().expect("the pages asked").push(request.path.to_string()); Reply::json(status, WORKER_FAILED) } else if request.path.starts_with("/v1/sync") && self.later_page_unplaced.load(std::sync::atomic::Ordering::SeqCst) { let mut page = json!({"version": *self.version.lock().expect("the version"), "rows": [], "server_time": "2026-10-26T09:00:00.000Z", "device": "invented-phone-row"}); if request.path.contains("cursor=") { page["rows"] = json!([{"table": "invented_unplaced", "id": "invented-row", "version": 4, "owner": null, "data": {"label": "An invented row"}, "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"}]); } else { page["next"] = json!("page-two"); } Reply::ok(&page.to_string()) } else if request.path.starts_with("/v1/definitions") { let definitions = self.definitions.lock().expect("the definitions").clone(); let held = request.headers.iter().find(|(name, _)| name.eq_ignore_ascii_case("if-none-match")).map(|(_, value)| value.clone()); if held == Some(format!("\"{}\"", definitions["etag"].as_str().unwrap_or_default())) { Reply::new(304, Vec::new()) } else { Reply::ok(&definitions.to_string()) } } else if request.path.starts_with("/v1/sync") && self.asks_stuck_page(request.path)? { Reply::json(422, r#"{"code": "invented_refusal", "message": "this page is one the copy cannot take (invented)"}"#) } else if request.path.starts_with("/v1/sync") && !self.pages.load(std::sync::atomic::Ordering::SeqCst) { Reply::new(503, br#"{"error":{"code":"unavailable","message":"no page for this test"}}"#.to_vec()) } else if request.path.starts_with("/v1/sync") { let device = if self.names_device.load(std::sync::atomic::Ordering::SeqCst) { json!("invented-phone-row") } else { serde_json::Value::Null }; let time = if self.serves_now.load(std::sync::atomic::Ordering::SeqCst) { chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) } else { "2026-10-26T09:00:00.000Z".to_string() }; let mut page = json!({"version": *self.version.lock().expect("the version"), "rows": *self.rows.lock().expect("the rows"), "server_time": time, "device": device}); let features = self.features.lock().expect("the features").clone(); if !features.is_null() { page["features"] = features; } if let Some(generation) = self.generation.lock().expect("the generation").clone() { page["generation"] = json!(generation); if let Some(at) = self.restored_to.lock().expect("the restored time").clone() { page["restored_to"] = json!(at); } } // The tables a later pass carries again whole, said as the Worker says them. if let Some(again) = request.path.split("again=").nth(1).map(|rest| rest.split('&').next().unwrap_or_default()).filter(|_| !self.old_worker.load(std::sync::atomic::Ordering::SeqCst)) { page["again"] = json!(again.split(',').collect::<Vec<_>>()); } if self.stuck_page.lock().expect("the stuck page").is_some() { page["next"] = json!("page-two"); } Reply::ok(&page.to_string()) } else if request.path.starts_with("/v1/act") && request.headers.iter().find(|(name, _)| name.eq_ignore_ascii_case("x-cotton-generation")).is_some_and(|(_, held)| Some(held) != self.generation.lock().expect("the generation").as_ref()) { self.asked.lock().expect("the pages asked").push(format!("refused {}", request.path)); Reply::json(409, &json!({"code": "generation_moved", "message": "the server was put back", "generation": *self.generation.lock().expect("the generation"), "restored_to": *self.restored_to.lock().expect("the restored time")}).to_string()) } else if request.path.starts_with("/v1/act") && !self.acts.load(std::sync::atomic::Ordering::SeqCst) { Reply::new(503, br#"{"error":{"code":"unavailable","message":"asked again later"}}"#.to_vec()) } else if request.path.starts_with("/v1/act") { let body: serde_json::Value = serde_json::from_slice(request.body.unwrap_or_default()).expect("an act's JSON"); self.taken.lock().expect("the acts").push(body.clone()); // `restore`, as the Worker answers it: each row made. if body["act"] == "restore" { // A restore the test stops part way: the calls left land, the next finds the object failing. if let Some(left) = self.restores_left.lock().expect("the restores left").as_mut() { if *left == 0 { return ScriptedExchange::new([Reply::new(503, br#"{"error":{"code":"unavailable","message":"the object stopped answering"}}"#.to_vec())]).send(origin, request, ceiling); } *left -= 1; } let restored: Vec<serde_json::Value> = body["args"]["rows"].as_array().into_iter().flatten().map(|row| json!({"table": row["table"], "id": row["id"], "landed": "made"})).collect(); // The object holds what it made: its next page serves it. if let Some(held) = self.rows.lock().expect("the rows").as_array_mut() { for row in body["args"]["rows"].as_array().into_iter().flatten() { held.push(json!({"table": row["table"], "id": row["id"], "version": 4, "owner": null, "data": row["data"], "created_at": "2026-10-20T09:00:00.000Z", "updated_at": "2026-10-20T09:00:00.000Z"})); } } return ScriptedExchange::new([Reply::ok(&json!({"version": 4, "changed": [], "restored": restored}).to_string())]).send(origin, request, ceiling); } Reply::ok("{}") } else if request.path.starts_with("/v1/media/") && request.method == "PUT" { let content_type = request.headers.iter().find(|(name, _)| name.eq_ignore_ascii_case("content-type")).map(|(_, value)| value.clone()); self.media.lock().expect("the media").push((request.path.to_string(), content_type, request.body.unwrap_or_default().to_vec())); Reply::json(201, r#"{"stored":true}"#) } else if request.path.starts_with("/v1/bin") { self.asked.lock().expect("the pages asked").push(request.path.to_string()); Reply::ok(&json!({"rows": *self.bin.lock().expect("the bin"), "more": false}).to_string()) } else if request.path.starts_with("/v1/me") { Reply::ok(&json!({"person": {"id": "owner-person", "phone": "+919000000009", "role": "owner"}, "version": 3, "generation": *self.generation.lock().expect("the generation"), "restored_to": *self.restored_to.lock().expect("the restored time")}).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) }}/// An invented tool as the object serves it.fn served_tool(id: &str, name: &str) -> serde_json::Value { json!({ "id": id, "name": name, "purpose": "Invented for a test.", "card_stock": "sage", "tables": ["todo"], "instructions": "", "automations": [], "author": {"device": "cotton", "name": "Cotton"}, "signature": null, })}fn tool_name(copy: &rusqlite::Connection, id: &str) -> Option<String> { copy.query_row("SELECT json_extract(definition, '$.name') FROM cotton_tool_definitions WHERE id = ?1", [id], |row| row.get(0)).ok()}/// RULE: the fan draws the object's tools: a connected phone's copy holds every table, tool and board `/v1/definitions` serves (not the package's own tool), beside the build's shell; unserved kit tools leave the copy, and a tool whose home table the app does not ship draws from the object's; a tool the object serves under an app tool's id is the object's, and a tool the object stops serving leaves the copy.#[test]fn the_objects_tools_and_boards_reach_the_copy_the_fan_draws() { let (_dir, handle) = phone(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let package = json!({"format_version": 1, "id": "personal", "name": "Personal", "tables": ["todo"]}); let mut garden = served_tool("garden", "Garden"); garden["tables"] = json!(["garden_bed"]); let object = Served::new(json!([served_table("garden_bed")]), json!([garden, served_tool("notebook", "Journal"), package]), json!([home]), "e1"); // The made table's rows come down with its definition. *object.rows.lock().expect("the rows") = json!([{ "table": "garden_bed", "id": "bed-1", "version": 3, "owner": null, "data": {"label": "North bed"}, "created_at": "2026-10-26T08:00:00.000Z", "updated_at": "2026-10-26T08:00:00.000Z", }]); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("a pass that finds the copy matching"); let path = handle.client().layout().replica(DATABASE); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(tool_name(©, "garden").as_deref(), Some("Garden"), "the object's tool is the copy's"); assert_eq!(tool_name(©, "notebook").as_deref(), Some("Journal"), "the object's Notebook, not the app's"); assert_eq!(tool_name(©, "todos"), None, "a kit tool the object does not serve leaves the copy"); assert_eq!(tool_name(©, "personal"), None, "the package's own tool is no tool"); let board: (String, i64) = copy .query_row("SELECT definition, builtin FROM cotton_board_definitions WHERE id = 'home'", [], |row| Ok((row.get(0)?, row.get(1)?))) .expect("Home's board"); assert_eq!((serde_json::from_str::<serde_json::Value>(&board.0).expect("JSON"), board.1), (home.clone(), 0), "Home lands as the object keeps it"); let db = cotton_store::driver::Driver::open(&path).expect("the copy"); let fan = cotton_tools::home_arrangement::tools(&db, DATABASE, None, true).expect("the fan's tools read"); assert!(fan.iter().any(|tool| tool == "garden") && !fan.iter().any(|tool| tool == "todos"), "{fan:?}"); let held: (String, i64) = copy .query_row("SELECT definition, builtin FROM cotton_table_definitions WHERE id = 'garden_bed'", [], |row| Ok((row.get(0)?, row.get(1)?))) .expect("the object's table is the copy's"); assert_eq!((serde_json::from_str::<serde_json::Value>(&held.0).expect("JSON"), held.1), (served_table("garden_bed"), 0)); let tables = cotton_tools::definitions::table_definitions_from_driver(&db, DATABASE).expect("the tables read"); assert!(tables.definitions.iter().any(|table| table.id == "garden_bed"), "Garden's home table draws: {:?}", tables.refused); assert!(!tables.definitions.iter().any(|table| table.id == "todo"), "an unserved kit table is not drawn"); let bed: String = copy.query_row("SELECT label FROM cotton_garden_bed WHERE id = 'bed-1'", [], |row| row.get(0)).expect("the made table's row is the copy's"); assert_eq!(bed, "North bed"); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "garden_bed"})).expect("Garden's list"); assert!(listed.to_string().contains("North bed"), "Garden draws its row: {listed}"); object.serve(json!([served_table("garden_bed")]), json!([served_tool("notebook", "Journal")]), json!([home]), "e2"); handle.client().sync_now().expect("a pass after the object moved"); assert_eq!(tool_name(©, "garden"), None, "a tool the object no longer serves leaves the copy"); assert_eq!(tool_name(©, "notebook").as_deref(), Some("Journal")); assert_eq!(tool_name(©, "todos"), None); let parked: i64 = copy.query_row("SELECT COUNT(*) FROM _parked", [], |row| row.get(0)).expect("a count"); assert_eq!(parked, 0);}/// RULE (28 Oct 2026, the first paint): a sign-in's copy draws the object's tools, tables and boards the moment `personal.connect` answers, from the definitions it asked to learn the database — before any page of `/v1/sync` lands; a pass that cannot land a page takes none of them away.#[test]fn a_new_copy_draws_the_objects_definitions_before_any_page_lands() { let (_dir, handle) = phone(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let mut garden = served_tool("garden", "Garden"); garden["tables"] = json!(["garden_bed"]); let object = Served::new(json!([served_table("garden_bed")]), json!([garden, served_tool("notebook", "Journal")]), json!([home]), "e1"); object.pages.store(false, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); let _ = handle.client().sync_now(); let path = handle.client().layout().replica(DATABASE); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(tool_name(©, "garden").as_deref(), Some("Garden"), "the object's own tool is drawn with no page landed"); assert_eq!(tool_name(©, "notebook").as_deref(), Some("Journal"), "the object's Notebook over the app's"); let board: String = copy.query_row("SELECT definition FROM cotton_board_definitions WHERE id = 'home'", [], |row| row.get(0)).expect("Home's board"); assert_eq!(serde_json::from_str::<serde_json::Value>(&board).expect("JSON"), home); let db = cotton_store::driver::Driver::open(&path).expect("the copy"); let fan = cotton_tools::home_arrangement::tools(&db, DATABASE, None, true).expect("the fan's tools read"); assert!(fan.iter().any(|tool| tool == "garden"), "{fan:?}"); let tables = cotton_tools::definitions::table_definitions_from_driver(&db, DATABASE).expect("the tables read"); assert!(tables.definitions.iter().any(|table| table.id == "garden_bed"), "Garden's home table draws: {:?}", tables.refused); let pages: i64 = copy.query_row("SELECT COUNT(*) FROM _cursors WHERE author_device_id = 'object'", [], |row| row.get(0)).expect("a count"); assert_eq!(pages, 0, "no page of the catch-up has landed");}/// The copy as a build of schema 141 wrote it (cotton-store's snapshot of/// that schema, the tables and nothing in them), at `path`, stamped 141.fn copy_written_at_141(path: &std::path::Path) { for suffix in ["", "-wal", "-shm"] { let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); } let mut objects: Vec<cotton_store::create::SchemaObject> = serde_json::from_str(include_str!("../../../cotton-store/tests/fixtures/schema-v141.json")).expect("the 141 snapshot"); objects.sort_by_key(|object| match object.kind.as_str() { "table" if object.is_fts5_virtual() => 1, "table" => 0, "index" => 2, _ => 3, }); // One transaction, as a build makes a file (`create_workspace`): 733 // statements committed one by one are 733 fsyncs, a minute on the box. let mut copy = rusqlite::Connection::open(path).expect("a file"); let shape = copy.transaction().expect("a transaction"); for object in &objects { shape.execute_batch(&object.sql).expect("the 141 shape"); } shape.execute_batch("PRAGMA user_version = 141").expect("the stamp"); shape.commit().expect("the 141 copy");}/// Stamp this build's copy as a build wrote it whose rise to this one is NOT/// add-only: one shipped table's statement is not this build's, so a move/// would rebuild it, and the copy is made again from the object (a copy whose/// rise only adds is moved in place instead:/// `a_copy_an_earlier_build_wrote_that_only_adds_is_moved_in_place_and_keeps_its_rows`).fn written_by_a_build_whose_rise_rebuilds(copy: &rusqlite::Connection) { copy.execute_batch(&format!( "PRAGMA writable_schema = ON; UPDATE sqlite_master SET sql = sql || ' /* as an earlier build wrote it */' WHERE type = 'table' AND name = 'cotton_notes'; PRAGMA writable_schema = OFF; PRAGMA user_version = {}", cotton_store::migrate::SCHEMA_VERSION - 1 )) .expect("an earlier build's shape and stamp");}fn stamp(copy: &rusqlite::Connection) -> u32 { copy.query_row("PRAGMA user_version", [], |row| row.get(0)).expect("the stamp")}fn the_garden() -> Arc<Served> { let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let mut garden = served_tool("garden", "Garden"); garden["tables"] = json!(["garden_bed"]); Served::new(json!([served_table("garden_bed")]), json!([garden, served_tool("notebook", "Journal")]), json!([home]), "e1")}fn phone_for_update() -> (tempfile::TempDir, CottonHandle) { let phone = phone(); // These fixtures replace the file to model an app update. The old app's // post-pass jobs must not outlive it and open the replacement beside the // reader under test. Detach stops scheduling, but an in-flight pass // finishes independently, as do vault/media post-pass jobs. These tests // drive each pass explicitly instead of running an old app's schedule // while replacing its file for the new launch. phone.1.client().set_runtime(None); phone.1.client().set_after_pass(Arc::new(|| {})); phone}// Hold new opens while replacing the file, and join an attach a background// reader (the thumbnail sweep, the voice-words timer) may already have started. The old app is gone during a real update.// The new launch's attach_now releases placing after the replacement is whole.fn detach_for_update(handle: &CottonHandle) { handle.client().set_placing(true); handle.client().detach(); assert_eq!(handle.client().with_file(|_| Ok(())).unwrap_err(), crate::shell::client::PLACING_A_COPY);}/// RULE (29 Oct 2026, the owner's phone on 331 over a copy its 32x build wrote): a copy another build wrote is made again from the object at connect, never moved in place — the copy of schema 141 goes, the object's copy at this build's schema opens in its place drawing the object's tools before any page, and its passes dial the object.#[test]fn a_copy_an_earlier_build_wrote_is_made_again_from_the_object() { let (_dir, handle) = phone_for_update(); let object = the_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the first launch"); detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); copy_written_at_141(&path); assert!(handle.client().attached_database().is_none()); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(stamp(©), cotton_store::migrate::SCHEMA_VERSION, "the copy is this build's"); let widgets: i64 = copy.query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = 'cotton_widgets'", [], |row| row.get(0)).expect("a count"); assert_eq!(widgets, 0, "nothing of the 141 file is left: it was made again, not moved"); assert_eq!(tool_name(©, "garden").as_deref(), Some("Garden"), "the fan draws the object's tools at once"); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); handle.client().sync_now().expect("a pass dials the object: nothing is moving"); let taken = object.taken.lock().expect("the acts").clone(); assert!( taken.iter().any(|act| act["act"] == "update" && act["args"]["table"] == "device" && act["args"]["id"] == "invented-phone-row" && act["args"]["data"]["copy_remade_at"].is_string()), "the device row says the copy was made again: {taken:?}" );}/// This build's copy at `path` as the build at schema `at` wrote it: the/// objects this build added since then dropped, the stamp set back. Only for/// a rise that ADDED (each object of the `at` snapshot is this build's to the/// byte), which every rise from 148 is.fn copy_as_written_at(path: &std::path::Path, at: u32) { let snapshot = |text: &str| -> std::collections::BTreeMap<String, cotton_store::create::SchemaObject> { serde_json::from_str::<Vec<cotton_store::create::SchemaObject>>(text).expect("a snapshot").into_iter().map(|object| (object.name.clone(), object)).collect() }; let then = snapshot(match at { 148 => include_str!("../../../cotton-store/tests/fixtures/schema-v148.json"), 149 => include_str!("../../../cotton-store/tests/fixtures/schema-v149.json"), other => panic!("no snapshot kept here for {other}"), }); let now = snapshot(include_str!("../../../cotton-store/tests/fixtures/schema-snapshot.json")); // Columns a later rise appended by ADD COLUMN (151's _writes.implied, 152's mail columns, 156's cotton_groups.hidden, // 157's four on _media): dropped below, so the table is as it was. const APPENDED: [(&str, &str); 18] = [("_media", "last_code"), ("_media", "network"), ("_media", "asked_by"), ("_media", "source"), ("cotton_groups", "hidden"), ("_writes", "implied"), ("cotton_emails", "to_line"), ("cotton_emails", "cc_line"), ("cotton_emails", "direction"), ("cotton_emails", "message_id"), ("cotton_emails", "message_refs"), ("cotton_emails", "list_unsubscribe"), ("cotton_emails", "list_unsubscribe_post"), ("cotton_emails", "list_id"), ("cotton_emails", "precedence"), ("cotton_emails", "auto_submitted"), ("cotton_emails", "gmail_category"), ("cotton_emails", "archived_at")]; for (name, object) in &then { if APPENDED.iter().any(|(table, _)| table == name) { continue; } assert_eq!(now.get(name).map(|o| &o.sql), Some(&object.sql), "{name}: the rise from {at} only added"); } let copy = rusqlite::Connection::open(path).expect("the copy"); // The later objects first: a later index may stand on an appended column (155's Inbox index on archived_at). let mut added: Vec<&cotton_store::create::SchemaObject> = now.values().filter(|object| !then.contains_key(&object.name)).collect(); // Triggers and indexes before the tables they stand on. added.sort_by_key(|object| object.kind == "table"); for object in added { let kind = if object.kind == "table" { "TABLE" } else if object.kind == "index" { "INDEX" } else { "TRIGGER" }; copy.execute_batch(&format!("DROP {kind} IF EXISTS \"{}\"", object.name)).expect("the later object goes"); } for (table, column) in APPENDED { copy.execute_batch(&format!("ALTER TABLE \"{table}\" DROP COLUMN \"{column}\"")).expect("the appended column goes"); } // Each table as the earlier build wrote it, once every column appended to it has gone. for table in APPENDED.iter().map(|(table, _)| *table).collect::<std::collections::BTreeSet<_>>() { let sql: String = copy.query_row("SELECT sql FROM sqlite_master WHERE name = ?1", [table], |row| row.get(0)).expect("the table"); assert_eq!(Some(&sql), then.get(table).map(|o| &o.sql), "{table} as {at} wrote it"); } copy.execute_batch(&format!("PRAGMA user_version = {at}")).expect("the earlier stamp");}/// RULE (owner, 21 Nov 2026: every update that raised the schema threw the owner's copy away, and Chat stood empty for the 25 minutes the whole object took to come down): a copy an earlier build wrote, whose rise to this build only ADDS (148 → 150 and 149 → 150: a search index, two indexes), is moved in place at connect — every row it held is still there and lists at once (though the object no longer serves it), it is stamped with this build's schema and holds the added objects, it is not made again, and its next pass asks from its cursor, not from nothing.#[test]fn a_copy_an_earlier_build_wrote_that_only_adds_is_moved_in_place_and_keeps_its_rows() { for at in [149, 148] { let (_dir, handle) = phone_for_update(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let mut garden = served_tool("garden", "Garden"); garden["tables"] = json!(["garden_bed"]); let object = Served::new(json!([served_table("garden_bed")]), json!([garden]), json!([home]), "e1"); *object.version.lock().expect("the version") = 7; *object.rows.lock().expect("the rows") = json!([{ "table": "garden_bed", "id": "bed-1", "version": 3, "owner": null, "data": {"label": "North bed"}, "created_at": "2026-10-26T08:00:00.000Z", "updated_at": "2026-10-26T08:00:00.000Z", }]); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the first launch"); handle.client().sync_now().expect("the first pull"); detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); copy_as_written_at(&path, at); // Made again, the copy would hold nothing the object no longer serves. *object.rows.lock().expect("the rows") = json!([]); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); let asked_before = object.asked.lock().expect("the pages asked").len(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(stamp(©), cotton_store::migrate::SCHEMA_VERSION, "{at}: the copy is this build's"); let added: i64 = copy.query_row("SELECT COUNT(*) FROM sqlite_master WHERE name IN ('idx_cotton_msg_messages_expires', 'idx_cotton_msg_messages_timer')", [], |row| row.get(0)).expect("a count"); assert_eq!(added, 2, "{at}: it holds what this build added"); let bed: String = copy.query_row("SELECT label FROM cotton_garden_bed WHERE id = 'bed-1'", [], |row| row.get(0)).expect("the row it held"); assert_eq!(bed, "North bed", "{at}: every row it held is still there"); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "garden_bed"})).expect("Garden's list"); assert!(listed.to_string().contains("North bed"), "{at}: Garden lists its row at once: {listed}"); handle.client().sync_now().expect("a pass"); let asked = object.asked.lock().expect("the pages asked").clone(); let pulled: Vec<&String> = asked[asked_before..].iter().filter(|path| path.contains("/v1/sync?")).collect(); assert!(!pulled.is_empty() && pulled.iter().all(|path| !path.contains("since=0")), "{at}: the pass asks from its cursor: {pulled:?}"); let taken = object.taken.lock().expect("the acts").clone(); assert!(!taken.iter().any(|act| act["args"]["data"]["copy_remade_at"].is_string()), "{at}: the copy was not made again: {taken:?}"); }}/// RULE (21 Nov 2026): a copy made again keeps this phone's media ledger, which is the phone's alone and never on the object — a file still to go up (a chat imported, a picture taken) is still to go up in the new copy, and a file already up is still named, so it is neither fetched again nor left on the disk with nothing naming it. Before, every update that raised the schema dropped the ledger: such files were never sent, other phones asked the object for them in vain, and the media folder kept files nobody counted.#[test]fn a_copy_made_again_keeps_this_phones_media_ledger() { let (_dir, handle) = phone_for_update(); let object = the_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the first launch"); detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); copy_written_at_141(&path); let media = handle.client().layout().client_media_dir().join(DATABASE); let pending = media.join("aa/imported.jpg"); let pending_key = format!("{DATABASE}/messages/thread-1/{}.jpg", "a".repeat(64)); let thumb_key = format!("{DATABASE}/photos/{}.t256.jpg", "b".repeat(64)); { let copy = rusqlite::Connection::open(&path).expect("the 141 copy"); copy.execute( "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, state, created_at, updated_at) VALUES (?1, ?2, ?3, 'image/jpeg', 7, ?4, 'pending', '2026-11-01T10:00:00.000Z', '2026-11-01T10:00:00.000Z')", rusqlite::params![pending_key, DATABASE, "a".repeat(64), pending.to_string_lossy()], ) .expect("a file still to go up"); copy.execute( "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, state, created_at, updated_at) VALUES (?1, ?2, ?3, 'image/webp', 5, ?4, 'synced', '2026-11-02T10:00:00.000Z', '2026-11-02T10:00:00.000Z')", rusqlite::params![thumb_key, DATABASE, "b".repeat(64), media.join("bb/thumb.webp").to_string_lossy()], ) .expect("a thumbnail already here"); } call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); let copy = cotton_store::driver::Driver::open(&path).expect("the copy"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION, "made again"); let up = cotton_store::media_ledger::media_by_key(©, &pending_key).expect("read").expect("the file still to go up is named"); assert_eq!((up.state.as_str(), up.local_path.as_deref()), ("pending", Some(pending.to_string_lossy().as_ref()))); let here = cotton_store::media_ledger::media_by_key(©, &thumb_key).expect("read").expect("the thumbnail is named"); assert_eq!(here.state, "synced"); assert_eq!(cotton_store::media_ledger::every_media_row(©).expect("the ledger").len(), 2);}/// RULE (owner, 11 Nov 2026, before Todos is cut for a phone holding the only copy of a thousand todos): a copy is never deleted unless the object holds every live row of it, or refused the row for good with its id written down. A copy another build wrote, whose rows the object lacks, is topped up before it is made again; when the top-up stops part way (the object stops answering) the remake is put off: the copy is where it was, at its own schema, every row in it, the sign-in says `copy_kept`, and the Account card says why. The next sign-in sends only what is still lacking, and only then is the copy made again.#[test]fn a_copy_is_not_made_again_until_the_object_holds_every_row_of_it() { let (_dir, handle) = phone_for_update(); let object = the_garden(); let todos = cotton_core::kit::package("todos").expect("the kit has Todos").expect("the package reads").package; { let mut definitions = object.definitions.lock().expect("the definitions"); definitions["tables"].as_array_mut().expect("tables").extend(todos.tables.iter().map(|table| json!(table))); definitions["tools"].as_array_mut().expect("tools").push(json!(todos.tool)); } call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); holds_the_data_key(&handle, &object); // More rows than one restore call carries. This object takes each create and keeps no row of it, as one emptied since: asked what it holds, it lacks them all. let many = cotton_client::transport::object::RESTORE_BATCH + 5; for n in 0..many { crate::methods::dispatch(&handle, "records.create", &json!({"table": "todo", "data": {"title": format!("An invented errand {n}")}})).expect("a todo"); } detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); let todos_here = |path: &std::path::Path| -> i64 { rusqlite::Connection::open(path).expect("the copy").query_row("SELECT COUNT(*) FROM cotton_todos", [], |row| row.get(0)).expect("a count") }; assert_eq!(todos_here(&path), many as i64); { let copy = rusqlite::Connection::open(&path).expect("the copy"); written_by_a_build_whose_rise_rebuilds(©); } // The todos the object holds, each a row a restore made. let restored = |object: &Served| -> usize { object.rows.lock().expect("the rows").as_array().map_or(0, |rows| rows.iter().filter(|row| row["table"] == "todo").count()) }; // THE TOP-UP STOPS PART WAY: one call lands, the object stops answering. *object.restores_left.lock().expect("the restores left") = Some(1); let kept = call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).unwrap_err(); assert_eq!(kept.code, "copy_kept", "{}", kept.message); assert!(kept.message.contains("status 503"), "the sign-in says why: {}", kept.message); assert_eq!(restored(&object), cotton_client::transport::object::RESTORE_BATCH, "one call landed"); assert!(path.exists(), "the copy is where it was"); assert_eq!(todos_here(&path), many as i64, "every row is still in it"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION - 1, "at its own schema: not made again"); 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(); // The core's words (status 503) stay in the log: the card says the kit's line (incident, 21 Nov 2026). assert!(said.starts_with("Cotton could not be reached just now. Nothing here is lost"), "the Account card says why: {card}"); assert!(!said.contains("status 503"), "never the core's words: {card}"); // RULE (owner, 21 Nov 2026): each fact names itself, and the card says plainly that this phone cannot reach the database. let facts = card["card"]["facts"].as_array().expect("facts"); let ids: Vec<&str> = facts.iter().filter_map(|fact| fact["id"].as_str()).collect(); assert_eq!(ids.len(), facts.len(), "every fact names itself: {card}"); assert_eq!(ids[..5], ["app", "database", "synced", "waiting", "here"], "in the card's order: {card}"); assert_eq!(ids.last(), Some(&"error"), "the last error last: {card}"); assert_eq!(card["trouble"], json!(false), "still connected and synced: no trouble, though the last error stands on the card: {card}"); // THE NEXT SIGN-IN sends only what the object still lacks, and only then is the copy made again. *object.restores_left.lock().expect("the restores left") = None; call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected once the object holds every row"); assert_eq!(restored(&object), many, "the five still lacking went, and none twice"); let ids: std::collections::BTreeSet<String> = object.rows.lock().expect("the rows").as_array().unwrap().iter().filter(|row| row["table"] == "todo").filter_map(|row| row["id"].as_str().map(str::to_string)).collect(); assert_eq!(ids.len(), many, "each todo once"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION, "now it is this build's");}/// RULE (owner, 21 Nov 2026: Books on the emulator, updated over a copy stuck on "Waiting to send 1 row", refused its sign-in `copy_kept` for ever): a copy an earlier build wrote that holds the zone claim an earlier Books wrote (a `news_settings` row and its write, a table Books' kit does not carry, so the copy holds no definition to seal it with) is made again all the same: the write is let go, the row goes with the copy and is never sent, in the clear or sealed, and the new copy waits on nothing.#[test]fn a_copy_holding_a_zone_claim_its_kit_does_not_carry_is_made_again() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, books()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); holds_the_data_key(&handle, &object); // What an earlier Books wrote at launch: the claim, made as before the kit guarded it. let kit = handle.client().layout().root().join("app_kit.json"); let aside = handle.client().layout().root().join("app_kit.json.aside"); std::fs::rename(&kit, &aside).expect("the kit set aside"); crate::methods::dispatch(&handle, "write", &json!({"tool": "materialize_todo_recurrences", "args": {"timezone": "Asia/Kolkata"}})).expect("the claim written"); std::fs::rename(&aside, &kit).expect("the kit back"); let path = handle.client().layout().replica(DATABASE); let claims = |path: &std::path::Path| -> (i64, i64) { let copy = rusqlite::Connection::open(path).expect("the copy"); let rows = copy.query_row("SELECT COUNT(*) FROM cotton_news_settings", [], |row| row.get(0)).expect("a count"); let queued = copy.query_row("SELECT COUNT(*) FROM _outbox WHERE tbl = 'cotton_news_settings'", [], |row| row.get(0)).expect("a count"); (rows, queued) }; assert_eq!(claims(&path), (1, 1), "the earlier build's claim, waiting to send"); detach_for_update(&handle); { let copy = rusqlite::Connection::open(&path).expect("the copy"); written_by_a_build_whose_rise_rebuilds(©); } call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected: the claim keeps no copy"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION, "made again"); assert_eq!(claims(&path), (0, 0), "the claim went with the old copy"); // QUEUE BAD OP 5 (item 5): the object never took it, so it is not answered: kept aside with the old copy, listed, // never sent back into a copy that cannot send it, and ended only by the person. let kept = cotton_client::copy_keep::kept_changes(handle.client().layout(), DATABASE); assert_eq!(kept.iter().filter(|change| change.table == "cotton_news_settings").count(), 1, "the claim is kept and listed: {kept:?}"); handle.client().sync_now().expect("a pass"); assert_eq!(handle.client().sync_status()["pending"], json!(0), "nothing waits to send"); let taken = object.taken.lock().expect("the acts").clone(); let said = serde_json::to_string(&taken).expect("the acts") + &serde_json::to_string(&*object.rows.lock().expect("the rows")).expect("the rows"); assert!(!said.contains("news_settings"), "no row of the claim reached the object: {taken:?}");}/// RULE (owner, 11 Nov 2026): a table in the copy that this build has no name for is never skipped silently. While it holds a live row the copy is not made again: the sign-in is refused `copy_kept`, and the refusal, the log and the Account card name the table. Its rows binned or gone, the copy is made again.#[test]fn a_copy_holding_rows_in_a_table_this_build_cannot_name_is_kept() { let (_dir, handle) = phone_for_update(); let object = the_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); { let copy = rusqlite::Connection::open(&path).expect("the copy"); // A table an earlier build kept and this one dropped: no spec, no definition. copy.execute_batch(&format!( "CREATE TABLE cotton_invented_keepsakes (id TEXT PRIMARY KEY, title TEXT, deleted_at TEXT); INSERT INTO cotton_invented_keepsakes (id, title, deleted_at) VALUES ('k1', 'An invented keepsake', NULL), ('k2', 'Another', NULL), ('k3', 'A binned one', '2026-11-01T00:00:00.000Z'); CREATE TABLE cotton_invented_empty (id TEXT PRIMARY KEY);", )) .expect("an earlier build's table"); written_by_a_build_whose_rise_rebuilds(©); } let kept = call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).unwrap_err(); assert_eq!(kept.code, "copy_kept", "{}", kept.message); assert!(kept.message.contains("cotton_invented_keepsakes (2 rows)"), "the table is named with its live rows: {}", kept.message); assert!(!kept.message.contains("cotton_invented_empty"), "a table holding nothing keeps no copy: {}", kept.message); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(stamp(©), cotton_store::migrate::SCHEMA_VERSION - 1, "at its own schema: not made again"); assert_eq!(copy.query_row("SELECT COUNT(*) FROM cotton_invented_keepsakes", [], |row| row.get::<_, i64>(0)).expect("a count"), 3, "every row is still in it"); 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"), "the Account card names the table: {card}"); // No live row left in it: the copy is made again. copy.execute_batch("UPDATE cotton_invented_keepsakes SET deleted_at = '2026-11-02T00:00:00.000Z'").expect("binned"); drop(copy); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected once the table holds no live row"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION, "now it is this build's");}/// RULE (owner, 11 Nov 2026): a copy this build cannot read at all is never deleted either: nothing of it can be shown to the object, so the sign-in is refused `copy_kept` and the file stays byte for byte, for a build that can read it.#[test]fn a_copy_this_build_cannot_read_is_kept_byte_for_byte() { let (_dir, handle) = phone(); let path = handle.client().layout().replica(DATABASE); std::fs::create_dir_all(path.parent().expect("a folder")).expect("the folder"); let unreadable = b"not a database this build reads: an invented file".repeat(64); std::fs::write(&path, &unreadable).expect("the file"); let kept = call_with(&handle, "personal.connect", &ask(), the_garden() as Arc<dyn Exchange>).unwrap_err(); assert_eq!(kept.code, "copy_kept", "{}", kept.message); assert_eq!(std::fs::read(&path).expect("the file is there"), unreadable, "not a byte of it changed");}/// RULE: a copy another build wrote sends what it holds that the object does not before it goes — a write the object asks for again later keeps the copy where it was and the connect says so; once the object takes it, the copy is made again with nothing left unsent.#[test]fn an_earlier_builds_copy_sends_its_unsent_writes_before_it_goes() { let (_dir, handle) = phone(); let object = the_garden(); // A copy draws only the tables the object serves. Give this synthetic // object the real kit package whose write the case needs to preserve. let todos = cotton_core::kit::package("todos").expect("the kit has Todos").expect("the package reads").package; { let mut definitions = object.definitions.lock().expect("the definitions"); definitions["tables"].as_array_mut().expect("tables").extend(todos.tables.iter().map(|table| json!(table))); definitions["tools"].as_array_mut().expect("tools").push(json!(todos.tool)); } call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); holds_the_data_key(&handle, &object); object.acts.store(false, std::sync::atomic::Ordering::SeqCst); crate::methods::dispatch(&handle, "records.create", &json!({"table": "todo", "data": {"title": "An invented errand"}})).expect("a todo"); let _ = handle.client().sync_now(); handle.client().detach(); let path = handle.client().layout().replica(DATABASE); let unsent = |path: &std::path::Path| cotton_client::unsent::unsent_changes(path).expect("the copy's unsent writes").into_iter().filter(|change| change.table == "cotton_todos").count(); assert_eq!(unsent(&path), 1, "the todo waits to be sent"); { let copy = rusqlite::Connection::open(&path).expect("the copy"); written_by_a_build_whose_rise_rebuilds(©); } let kept = call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).unwrap_err(); assert_eq!(kept.code, "copy_kept"); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(stamp(©), cotton_store::migrate::SCHEMA_VERSION - 1, "the copy is where it was"); drop(copy); object.acts.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected once the object takes it"); let taken = object.taken.lock().expect("the acts").clone(); assert!( // Sealed (e2e rulings R1): its title travels inside sealed_enc. taken.iter().any(|act| act["act"] == "create" && act["args"]["table"] == "todo" && act["args"]["data"]["sealed_enc"].as_str().is_some_and(|text| text.starts_with("s1:"))), "the todo reached the object: {taken:?}" ); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(stamp(©), cotton_store::migrate::SCHEMA_VERSION); drop(copy); assert_eq!(unsent(&path), 0, "nothing is left unsent"); assert!(cotton_client::unsent::discarded(handle.client().layout(), DATABASE).is_empty(), "nothing was lost");}/// RULE: a copy of the object another build wrote is never opened or moved by any read before the connect makes it again: the attach refuses it and says it is made again when the phone connects.#[test]fn no_read_moves_a_copy_of_the_object_another_build_wrote() { let (_dir, handle) = phone_for_update(); call_with(&handle, "personal.connect", &ask(), the_garden() as Arc<dyn Exchange>).expect("connected"); detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); copy_written_at_141(&path); let refused = handle.client().attach_now().unwrap_err(); assert_eq!(refused, crate::shell::client::ANOTHER_BUILDS_COPY); let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_eq!(stamp(©), 141, "untouched"); let moving: i64 = copy.query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = '_shape_move'", [], |row| row.get(0)).expect("a count"); assert_eq!(moving, 0, "no move begun");}/// RULE: a served copy an earlier build set aside before its update is never restored and moved by the attach: the heal is only for a database this device holds alone, so the copy set aside stays as it was.#[test]fn the_attach_never_restores_a_served_copy_set_aside_before_an_update() { let (_dir, handle) = phone_for_update(); call_with(&handle, "personal.connect", &ask(), the_garden() as Arc<dyn Exchange>).expect("connected"); detach_for_update(&handle); let path = handle.client().layout().replica(DATABASE); let before = std::path::PathBuf::from(format!("{}.before-update", path.display())); copy_written_at_141(&before); for suffix in ["", "-wal", "-shm"] { let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); } let _ = handle.client().attach_now(); assert!(before.exists(), "the copy set aside is where it was"); let set_aside = rusqlite::Connection::open(&before).expect("the copy set aside"); assert_eq!(stamp(&set_aside), 141, "untouched"); if path.exists() { let copy = rusqlite::Connection::open(&path).expect("the copy"); assert_ne!(stamp(©), 141, "the copy set aside was not put back"); let moving: i64 = copy.query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = '_shape_move'", [], |row| row.get(0)).expect("a count"); assert_eq!(moving, 0, "no move begun"); }}/// An invented person row as the object serves it.fn served_person(id: &str, name: &str) -> serde_json::Value { json!({ "table": "person", "id": id, "version": 3, "owner": null, "data": {"full_name": name}, "created_at": "2026-10-26T08:00:00.000Z", "updated_at": "2026-10-26T08:00:00.000Z", })}/// RULE: who you are is the object's to say (apps/business/src/owner.ts: the person whose phone is the sign-in number): the `owner_person_id` `/v1/definitions` serves with the database's meta lands on the copy, and `read.you` answers that person — nobody while the object names none, the person it names once it does, and the person it moves the link to after a merge — with nothing on the phone choosing.#[test]fn read_you_answers_the_person_the_object_names() { let (_dir, handle) = phone(); let object = Served::new(json!([]), json!([]), json!([]), "e1"); *object.rows.lock().expect("the rows") = json!([served_person("person-me", "Invented Owner"), served_person("person-kept", "Invented Survivor")]); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); let you = crate::methods::dispatch(&handle, "read.you", &json!({})).expect("read.you answers"); assert_eq!(you["owner"], json!(crate::phone::you::NO_OWNER_YET), "the object names nobody yet: {you}"); assert_eq!(you["person_id"], serde_json::Value::Null); let name = |owner: &str, etag: &str| { let mut definitions = object.definitions.lock().expect("the definitions"); definitions["business"]["owner_person_id"] = json!(owner); definitions["etag"] = json!(etag); *object.version.lock().expect("the version") += 1; }; name("person-me", "e2"); handle.client().sync_now().expect("a pass after the object linked its owner"); let you = crate::methods::dispatch(&handle, "read.you", &json!({})).expect("read.you answers"); assert_eq!((you["owner"].clone(), you["person_id"].clone(), you["name"].clone()), (json!(crate::phone::you::OWNER_LINKED), json!("person-me"), json!("Invented Owner"))); name("person-kept", "e3"); handle.client().sync_now().expect("a pass after the object followed a merge"); let you = crate::methods::dispatch(&handle, "read.you", &json!({})).expect("read.you answers"); assert_eq!(you["person_id"], json!("person-kept")); let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); let parked: i64 = copy.query_row("SELECT COUNT(*) FROM _parked", [], |row| row.get(0)).expect("a count"); assert_eq!(parked, 0);}/// RULE: a rendition's original can live in a declared photo column without/// a Photos row. Both thumbnail and display resolve the actual stored key.#[test]fn a_film_poster_without_a_photos_row_is_fetched_from_its_declared_column() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).unwrap(); let original = format!("{DATABASE}/photos/{}.jpg", "e".repeat(64)); crate::phone::media_tests::declared_film(&handle, &original); let media = ObjectMedia { transport: ObjectMediaTransport::new(ObjectAddress::open("https://cotton.example.com").unwrap(), object("owner") as Arc<dyn Exchange>, "synthetic-credential".into()), replica: handle.client().layout().replica(DATABASE), stories: None, }; assert_eq!(media.source(&cotton_core::media::keys::thumb_key_for(&original).unwrap()).unwrap(), (original.clone(), Some(256))); assert_eq!(media.source(&cotton_core::media::keys::display_key_for(&original).unwrap()).unwrap(), (original, Some(1600)));}/// RULE (1 Nov 2026): a phone on its personal object sends its captures UP: `personal.connect` starts the media drain over the copy with the object's door, so a picture filed on the phone goes up as `PUT /v1/media/<key>` under the same credential with its content type, its ledger row is synced, and its bytes stay on the phone; the drain's counts reach the device row with the next pass.#[test]fn a_connected_phone_sends_its_captures_to_the_object() { capture_goes_to_object("picked.jpg", "image/jpeg", "photo");}#[test]fn a_shared_mov_is_kept_as_video_and_uploaded_with_its_content_type() { capture_goes_to_object("shared.mov", "video/quicktime", "video");}fn capture_goes_to_object(filename: &str, mime: &str, kind: &str) { let (dir, handle) = phone(); let object = Served::new(json!([]), json!([]), json!([]), "e1"); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); // The person's data key, as the shell hands it over at launch: their files go up sealed under it (R6). let dk = cotton_core::seal::DataKey::from_bytes([7; 32]); handle.client().data_keys().hold(DATABASE, &dk); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert!(handle.client().media_drain_status().is_some(), "a connected phone runs a drain"); let picked = dir.path().join(filename); 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": mime, "filename": filename, "kind": kind})) .expect("the picture is filed"); let key = filed["key"].as_str().map(str::to_string).unwrap_or_else(|| panic!("a key: {filed}")); handle.client().wake_media_drain(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); let put = loop { if let Some(put) = object.media.lock().expect("the media").iter().find(|(path, _, _)| path.ends_with(&key)).cloned() { break put; } assert!(std::time::Instant::now() < deadline, "the picture never went up"); std::thread::sleep(std::time::Duration::from_millis(20)); }; assert_eq!(put.0, format!("/v1/media/{key}")); // R6: the object is handed the picture sealed, typed only as a sealed file, and the person's key opens it. assert_eq!(put.1.as_deref(), Some(cotton_client::media::sealed::SEALED_FILE_TYPE)); assert_eq!(&put.2[..4], b"CTF1"); assert!(!put.2.windows(8).any(|w| w == b"invented"), "the picture's bytes never reach the object"); let root = cotton_core::seal::keys::file_root(&dk, DATABASE).unwrap(); let mut opened = Vec::new(); cotton_core::seal::file::open_file(&cotton_core::seal::file::person_file_key(&root, &key), &key, &mut put.2.as_slice(), &mut opened).expect("it opens with the person's key"); assert_eq!(opened, b"an invented picture"); let path = handle.client().layout().replica(DATABASE); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); let row = loop { let copy = cotton_store::driver::Driver::open(&path).expect("the copy"); let row = cotton_store::media_ledger::media_by_key(©, &key).expect("a read").expect("the ledger row"); if row.state == "synced" || std::time::Instant::now() > deadline { break row; } std::thread::sleep(std::time::Duration::from_millis(20)); }; assert_eq!(row.state, "synced"); assert_eq!(row.content_type, mime); assert!(key.contains(&format!("/{kind}s/"))); if kind == "video" { let copy = cotton_store::driver::Driver::open(&path).unwrap(); assert_eq!(copy.get("SELECT content_type FROM cotton_videos WHERE key = ?", &[rusqlite::types::Value::Text(key.clone())]).unwrap().unwrap().text("content_type"), Some(mime)); assert!(copy.get("SELECT id FROM cotton_documents WHERE storage_path = ?", &[rusqlite::types::Value::Text(key.clone())]).unwrap().is_none()); } assert!(std::path::Path::new(row.local_path.as_deref().expect("a path")).is_file(), "the phone keeps its bytes"); handle.client().sync_now().expect("a pass"); let told = object.taken.lock().expect("the acts").iter().any(|act| act["args"]["data"].get("media_waiting").is_some()); assert!(told, "the drain's counts reach the device row: {:?}", object.taken.lock().expect("the acts"));}/// RULE: a phone with no object (Rigby, `sync: false`, never `personal.connect`) runs no drain.#[test]fn a_phone_with_no_object_runs_no_drain() { let (_dir, handle) = phone(); assert!(handle.client().media_drain_status().is_none()); assert!(handle.client().pictures_sweep().is_none());}/// RULE: a phone's own database, which no object fills, holds the columns its kit's definitions add to an engine's table, so a write the kit offers lands before backup — an event's kind, chosen from its picture.#[test]fn a_local_database_holds_the_columns_its_kit_adds_and_an_events_kind_lands() { let (_dir, handle) = phone(); started_here(&handle); let made = crate::methods::dispatch( &handle, "records.create", &json!({"table": "event", "data": {"title": "An invented outing", "starts_at": "2026-11-02T10:00:00Z", "ends_at": "2026-11-02T11:00:00Z"}}), ) .expect("an event"); let id = 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}")); let updated = crate::methods::dispatch(&handle, "records.update", &json!({"table": "event", "id": id, "patch": {"kind": "walk"}})) .expect("the kind is written on the phone's own database"); assert_eq!(updated["change"]["after"]["kind"], "walk", "{updated}"); let got = crate::methods::dispatch(&handle, "records.get", &json!({"table": "event", "id": id})).expect("read back"); assert_eq!(got["data"]["kind"], "walk", "{got}");}/// This phone starts its own database, as a fresh install of Cotton does/// before anyone signs in (`workspace.startLocal`); answers its id.fn started_here(handle: &CottonHandle) -> String { crate::methods::dispatch(handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); let layout = handle.client().layout().clone(); let mine = cotton_client::connection::ConnectionFile::at(layout.connection_json()).read().expect("a connection"); assert_eq!(mine.mode, cotton_client::connection::ConnectionMode::Local, "a local start"); 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()}/// RULE: a phone that started its own database and made nothing in it yet (only the shell and its genesis tools) backs up by connecting: the object's copy is made and connected as a sign-in makes it, and only then is the local database removed, its folder with it (owner, 1 Nov 2026).#[test]fn a_fresh_local_database_gives_way_to_the_objects_copy_once_it_is_connected() { let (_dir, handle) = phone(); let local = started_here(&handle); // What the app writes for itself as it opens (1 Nov 2026 walk: a fresh // Cotton counted its own usage rows as "2 rows you made"). crate::methods::dispatch(&handle, "usage.record", &json!({"id": "invented-open", "kind": "view_opened", "tool": "todos", "view": "tool/todos"})) .expect("an open is counted"); let layout = handle.client().layout().clone(); let unsent = cotton_client::unsent::unsent_changes(&layout.replica(&local)).expect("unsent"); assert!(unsent.iter().any(|change| change.table == "cotton_usage"), "the app's own row waits unsent: {unsent:?}"); assert_eq!(made_rows(&layout.replica(&local)).expect("counted"), 0, "a fresh start holds nothing a person made: {unsent:?}"); let answer = call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); assert_eq!(answer["databaseId"], DATABASE); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.base_url.as_str(), mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Remote, "https://cotton.example.com", Some(DATABASE))); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); assert!(!layout.replica(&local).exists(), "the empty local database is gone"); assert!(!layout.replica(&local).parent().expect("a folder").exists(), "with its folder"); assert!(layout.replica(DATABASE).exists());}/// RULE: Stop backing up keeps the copy as this phone's local database — it is the person's data — and dials the object no more; signing in again with the same number connects the same copy, its rows still there, with no request.#[test]fn stopping_backup_keeps_the_copy_local_and_signing_in_again_connects_it() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let path = handle.client().layout().replica(DATABASE); let devices = |path: &std::path::Path| -> i64 { rusqlite::Connection::open(path).expect("the copy").query_row("SELECT COUNT(*) FROM cotton_devices", [], |row| row.get(0)).expect("a count") }; let held = devices(&path); assert!(held > 0, "the copy holds this phone's row"); let kept = call_with(&handle, "personal.standLocal", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("stood local"); assert_eq!(kept, json!({"databaseId": DATABASE})); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.base_url.as_str(), mine.workspace_id.as_deref()), (cotton_client::connection::ConnectionMode::Local, "", Some(DATABASE)), "the copy stands local"); assert!(handle.client().object_door().is_none(), "no door to the object"); assert!(handle.client().media_drain_status().is_none(), "no drain sends captures up"); assert_eq!(devices(&path), held, "the copy is kept whole"); handle.client().attach_now().expect("the copy opens as the local database"); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); handle.client().detach(); let offline = ScriptedExchange::new([]); let again = call_with(&handle, "personal.connect", &ask(), Arc::clone(&offline) as Arc<dyn Exchange>).expect("connected again"); assert_eq!(again["databaseId"], DATABASE); assert_eq!(offline.calls(), 0, "its own copy needs no request"); let mine = connection_of(&handle).expect("a connection"); assert_eq!((mine.mode, mine.base_url.as_str()), (cotton_client::connection::ConnectionMode::Remote, "https://cotton.example.com")); assert_eq!(devices(&path), held, "the same copy");}/// RULE: Remove from this phone deletes the copy — its folder and the connection — so the next start makes a fresh local database; it is the person's own destructive act, asked first on the screen.#[test]fn removing_from_this_phone_deletes_the_copy_and_a_fresh_start_follows() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let layout = handle.client().layout().clone(); let removed = call_with(&handle, "personal.remove", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("removed"); assert_eq!(removed, json!({"removed": DATABASE})); assert!(!layout.replica(DATABASE).exists()); assert!(connection_of(&handle).is_none(), "no connection is left"); let fresh = started_here(&handle); assert_ne!(fresh, DATABASE, "a new local database");}/// Home's sync card as the core serves it to this phone: the record the/// served Home's `device` part names, its `session` and whether a card is/// dealt as `device.facts` reads it, and the acts it offers opened.fn sync_card(handle: &CottonHandle) -> (serde_json::Value, serde_json::Value, bool, Vec<String>) { use cotton_core::definitions::board::THIS_DEVICE_KEY; let catalogue = crate::methods::dispatch(handle, "definitions.catalogue", &json!({})).expect("the catalogue"); let parts = catalogue["boards"]["home"]["definition"]["parts"].as_array().cloned().unwrap_or_default(); let named = parts.iter().find(|part| part["kind"] == "device").map(|part| part[THIS_DEVICE_KEY].clone()).unwrap_or_default(); let Some(id) = named.as_str() else { return (named, serde_json::Value::Null, false, Vec::new()) }; let facts = crate::methods::dispatch(handle, "device.facts", &json!({"deviceId": id})).expect("this device's facts"); let acts = crate::methods::dispatch(handle, "shell.opened", &json!({"table": "device", "id": id})).expect("this device's acts"); let acts = acts["acts"].as_array().into_iter().flatten().filter_map(|act| act["id"].as_str().map(str::to_string)).collect(); (named, facts["data"]["session"].clone(), facts["data"]["@card"].is_object(), acts)}/// RULE: Erase on a signed-in phone leaves what a fresh install has before its first sign-in: Home's sync card names this device's own record in the fresh local database, dealt as a card, signed out, offering Sign in, Share ink and Erase.////// WHY: Cotton 348's walk — after the sync card's Erase, Home said "Nothing/// here yet" with no card, so there was no Sign in on Home; the only way back/// was Settings › Backup.#[test]fn an_erased_phone_shows_the_sync_card_a_fresh_install_does() { let (_installed_dir, installed) = phone(); started_here(&installed); let fresh = sync_card(&installed); assert!(fresh.0.is_string(), "a fresh install's Home names this device: {fresh:?}"); assert_eq!((&fresh.1, fresh.2), (&json!("signed_out"), true), "{fresh:?}"); assert_eq!(fresh.3, ["sign_in", "share_ink", "erase_here"]); let (_erased_dir, erased) = phone(); call_with(&erased, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); call_with(&erased, "personal.remove", &json!({}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("removed"); started_here(&erased); assert_eq!(sync_card(&erased), fresh, "an erased phone is a fresh install");}/// RULE (owner, 2 Nov 2026): the deck's counter says "25 todos sending"/// while a tool's writes wait to go up: This Device's live read says what/// each table is doing by the object's name for it — this phone's queue told/// by its own table — and names no table that is settled.#[test]fn this_devices_facts_say_each_tables_writes_sending_by_the_objects_name() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let progress = handle.client().sync_progress().expect("a phone on the object keeps its passes"); let replica = handle.client().layout().replica(DATABASE); let address = ObjectAddress::named("https://cotton.example.com", "personal").expect("an address"); let _made = cotton_client::transport::object::ObjectTransport::new( address, ScriptedExchange::new([]), "synthetic-credential".into(), cotton_client::transport::object::ObjectTables::personal(), replica, Vec::new(), ) .reporting_to(Arc::clone(&progress)); let id = handle.client().self_device_id().expect("this device's id"); let facts = crate::methods::dispatch(&handle, "device.facts", &json!({"deviceId": id})).expect("this device's facts"); assert!(facts["data"]["sync_table_progress"].is_object(), "{}", facts["data"]); assert_eq!(facts["data"]["sync_table_progress"].get("todo"), None, "no todo queued, none moving: {}", facts["data"]); assert!(facts["live"].as_array().is_some_and(|live| live.contains(&json!("sync_table_progress")))); // Two todo writes waiting to go up, as the mint queues them. handle.client().with_writer(|file| { for n in 0..2 { file.driver.run( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes) VALUES (?, 'create', 'invented', 'cotton_todos', ?, '0', 1, '2026-11-02T00:00:00Z', x'00')", &[rusqlite::types::Value::Text(format!("op-{n}")), rusqlite::types::Value::Text(format!("t-{n}"))], ).map_err(|why| why.to_string())?; } Ok(()) }).expect("queued"); assert_eq!( handle.client().with_file(|file| cotton_store::outbox::pending_by_table(file.driver).map_err(|why| why.to_string())).expect("the queue"), vec![("cotton_todos".to_string(), 2)], ); let facts = crate::methods::dispatch(&handle, "device.facts", &json!({"deviceId": id})).expect("this device's facts"); assert_eq!(facts["data"]["sync_table_progress"], json!({"todo": {"sending": 2}}), "{}", facts["data"]);}/// RULE: This device's record is read with its table's live read wherever it/// is read for drawing — `records.get` (the record a card opens on) and/// `records.list` (the cards a deck deals) carry the live columns and the card/// dealt over them, as `device.facts` (Home's sync card) does.////// WHY: Cotton 348's walk — the sync card opened from Home drew only its/// platform: the device's deck read the stored row, without the build and/// the sync rows its card names, opened and back in the deck.#[test]fn this_devices_record_reads_carry_its_live_read_and_the_card_dealt_over_it() { let (_dir, handle) = phone(); call_with(&handle, "personal.connect", &ask(), object("owner") as Arc<dyn Exchange>).expect("connected"); let progress = handle.client().sync_progress().expect("a phone on the object keeps its passes"); let replica = handle.client().layout().replica(DATABASE); let address = ObjectAddress::named("https://cotton.example.com", "personal").expect("an address"); let _made = cotton_client::transport::object::ObjectTransport::new( address, ScriptedExchange::new([]), "synthetic-credential".into(), cotton_client::transport::object::ObjectTables::personal(), replica, Vec::new(), ) .reporting_to(Arc::clone(&progress)); let id = handle.client().self_device_id().expect("this device's id"); let facts = crate::methods::dispatch(&handle, "device.facts", &json!({"deviceId": id})).expect("this device's facts"); let got = crate::methods::dispatch(&handle, "records.get", &json!({"table": "device", "id": id})).expect("this device's record"); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "device"})).expect("the devices"); let row = listed["records"].as_array().and_then(|rows| rows.iter().find(|row| row["id"] == json!(id))).expect("this device listed"); assert!(facts["data"]["sync_table_progress"].is_object(), "{}", facts["data"]); for data in [&got["data"], &row["data"]] { assert_eq!(data["sync_table_progress"], facts["data"]["sync_table_progress"], "{data}"); assert_eq!(data["sync_rows_done"], facts["data"]["sync_rows_done"], "{data}"); assert_eq!(data["sync_rows_total"], facts["data"]["sync_rows_total"], "{data}"); assert_eq!(data["@card"], facts["data"]["@card"], "the card is dealt over the live columns: {data}"); }}/// `local`'s copy as an earlier build left it mid-move: `cotton_todos` one/// column short and the file stamped one schema below this build, the move's/// first step run (as the open before this one ran it) and its kit stamp/// gone, so the next attach keeps the kit again. Whenever the kit stamp is/// written, `_kept_while_moving` says whether the move was still under way./// Answers the column the move puts back. Opens are held while the file is/// made so, as an update holds them, and the start's own background work (its/// index rebuild) ends first, so nothing else opens or writes the file/// meanwhile: the voice-words timer's tick, late on a loaded box, read the/// copy, attached it and ran the move under the test. The test's own/// `attach_now` lets opens go again.fn left_mid_move(handle: &CottonHandle, local: &str) -> String { use cotton_store::migrate::SCHEMA_VERSION; detach_for_update(handle); handle.client().settle_moves_for_tests(); let db = cotton_store::driver::Driver::open(handle.client().layout().replica(local)).expect("the copy"); let columns = db.all("SELECT name, \"notnull\" AS nn FROM pragma_table_info('cotton_todos') ORDER BY cid", &[]).expect("columns"); let last = columns.last().and_then(|row| row.text("name")).expect("a last column").to_string(); let dropped = columns.iter() .filter(|row| row.int("nn") == Some(0)) .filter_map(|row| row.text("name").map(str::to_string)) .filter(|name| *name != last && !name.starts_with('_')) .find(|name| db.exec(&format!("ALTER TABLE cotton_todos DROP COLUMN \"{name}\"")).is_ok()) .expect("a column of cotton_todos can be taken away"); db.exec(&format!("PRAGMA user_version = {}", SCHEMA_VERSION - 1)).expect("the stamp"); cotton_store::shape_move::move_step(&db).expect("the move's first step"); let left = cotton_store::shape_move::left(&db).expect("the move").expect("a move under way"); assert!(left.begun && left.holds("cotton_todos"), "{left:?}"); db.exec(&format!( "DELETE FROM _kit_keep WHERE key = '{key}'; CREATE TABLE _kept_while_moving (moving INTEGER NOT NULL); CREATE TRIGGER kit_stamped AFTER INSERT ON _kit_keep WHEN NEW.key = '{key}' BEGIN INSERT INTO _kept_while_moving SELECT count(*) FROM sqlite_master WHERE name = '{moving}'; END;", key = cotton_tools::kit_keep::KIT_VERSION, moving = cotton_store::shape_move::MOVE_TABLE, )) .expect("the kit stamp gone and its writing watched"); db.checkpoint_truncate().expect("a checkpoint"); dropped}/// RULE: a phone's own database left mid-move by an earlier open attaches/// with its move finished first and its kit kept after (coordinator, 2 Nov/// 2026: open, finish the move, keep, serve): the kit stamp is written once/// no move is under way, and the copy is whole at this build's schema.#[test]fn a_local_database_left_mid_move_finishes_its_move_before_its_kit_is_kept() { let (_dir, handle) = phone(); let local = started_here(&handle); let dropped = left_mid_move(&handle, &local); handle.client().attach_now().expect("the copy attaches"); assert!(cotton_client::moves::left(&local).is_none(), "the move is finished by the attach"); let db = cotton_store::driver::Driver::open(handle.client().layout().replica(&local)).expect("the copy"); let kept: Vec<Option<i64>> = db.all("SELECT moving FROM _kept_while_moving", &[]).expect("the watch").iter().map(|row| row.int("moving")).collect(); assert_eq!(kept, vec![Some(0)], "the kit is kept once, after the move"); assert_eq!(cotton_store::migrate::current_version(&db).expect("the stamp"), cotton_store::migrate::SCHEMA_VERSION); assert!(cotton_store::shape_move::left(&db).expect("the move").is_none()); let columns = db.all("SELECT name FROM pragma_table_info('cotton_todos')", &[]).expect("columns"); assert!(columns.iter().any(|row| row.text("name") == Some(dropped.as_str())), "the moved table is whole: {dropped}"); assert!(cotton_client::bootstrap::not_moved::why(handle.client().layout(), &local).is_none());}/// RULE: a phone's own database whose move stops at the attach is served as/// it is, at its stored schema, written down as not moved and its kit not/// kept: no object holds it to make it again from (coordinator, 2 Nov 2026).#[test]fn a_local_database_whose_move_stops_is_served_unkept_at_its_stored_schema() { let (_dir, handle) = phone(); let local = started_here(&handle); left_mid_move(&handle, &local); a_step_that_cannot_run(&handle, &local); handle.client().attach_now().expect("the copy is served"); assert!(cotton_client::moves::left(&local).is_some(), "the move stopped where it was"); assert!(cotton_client::bootstrap::not_moved::why(handle.client().layout(), &local).is_some(), "written down as not moved"); let db = cotton_store::driver::Driver::open(handle.client().layout().replica(&local)).expect("the copy"); assert_eq!(cotton_store::migrate::current_version(&db).expect("the stamp"), cotton_store::migrate::SCHEMA_VERSION - 1); assert!(db.all("SELECT moving FROM _kept_while_moving", &[]).expect("the watch").is_empty(), "no kit is kept over a half-moved copy"); let stamp = db.get("SELECT value FROM _kit_keep WHERE key = ?", &[rusqlite::types::Value::Text(cotton_tools::kit_keep::KIT_VERSION.into())]).expect("the kit stamp"); assert!(stamp.is_none(), "the kit stamp stays unwritten"); let workspaces = db.get("SELECT count(*) AS n FROM cotton_workspaces", &[]).expect("a moved table reads").and_then(|row| row.int("n")); assert_eq!(workspaces, Some(1));}/// Make the next step `local`'s move has left one that cannot run. Answers/// the step and its body, to put back.fn a_step_that_cannot_run(handle: &CottonHandle, local: &str) -> (i64, String) { let db = cotton_store::driver::Driver::open(handle.client().layout().replica(local)).expect("the copy"); let moving = cotton_store::shape_move::MOVE_TABLE; let next = db .get(&format!("SELECT step, body FROM \"{moving}\" WHERE step = (SELECT min(step) FROM \"{moving}\" WHERE step > 0)"), &[]) .expect("the steps left") .expect("a step left"); let step = next.int("step").expect("its number"); let body = next.text("body").expect("its body").to_string(); db.exec(&format!("UPDATE \"{moving}\" SET body = 'not a step' WHERE step = {step}")).expect("a step that cannot run"); db.checkpoint_truncate().expect("a checkpoint"); (step, body)}/// RULE: a phone's own database whose move stopped opens again at the next/// attach and tries the steps left again, served unkept while the cause/// stands (coordinator, 3 Nov 2026: a phone-only copy keeps opening at every/// launch; a copy written down as not moved was refused at every open after).#[test]fn a_local_database_whose_move_stopped_opens_again_and_tries_again() { let (_dir, handle) = phone(); let local = started_here(&handle); left_mid_move(&handle, &local); a_step_that_cannot_run(&handle, &local); handle.client().attach_now().expect("the copy is served"); // The steps left run on the thread the attach starts: wait for it, or // the note is read before the step that writes it has run. handle.client().settle_moves_for_tests(); let client = handle.client(); let layout = client.layout(); assert!(cotton_client::bootstrap::not_moved::why(layout, &local).is_some(), "written down as not moved"); detach_for_update(&handle); let note = format!("{}{}", layout.replica(&local).display(), cotton_client::bootstrap::not_moved::NOT_MOVED_SUFFIX); std::fs::remove_file(¬e).expect("the note taken away, to see the next try write it"); handle.client().attach_now().expect("a copy whose move stopped opens again"); handle.client().settle_moves_for_tests(); assert!(cotton_client::bootstrap::not_moved::why(layout, &local).is_some(), "the move was tried again and stopped again"); assert!(cotton_client::moves::left(&local).is_some(), "still where it was"); let db = cotton_store::driver::Driver::open(layout.replica(&local)).expect("the copy"); assert_eq!(cotton_store::migrate::current_version(&db).expect("the stamp"), cotton_store::migrate::SCHEMA_VERSION - 1); assert!(db.all("SELECT moving FROM _kept_while_moving", &[]).expect("the watch").is_empty(), "no kit is kept over a half-moved copy");}/// RULE: once the cause of a stopped move is gone, the next attach finishes/// the move and only then keeps the kit (coordinator, 3 Nov 2026).#[test]fn a_local_database_whose_move_stopped_finishes_and_keeps_its_kit_once_the_cause_is_gone() { let (_dir, handle) = phone(); let local = started_here(&handle); let dropped = left_mid_move(&handle, &local); let (step, body) = a_step_that_cannot_run(&handle, &local); handle.client().attach_now().expect("the copy is served"); // The steps left run on the thread the attach starts: wait for it, or // the note is read before the step that writes it has run (rust-main // 9296 on the loaded box). handle.client().settle_moves_for_tests(); let client = handle.client(); let layout = client.layout(); assert!(cotton_client::bootstrap::not_moved::why(layout, &local).is_some(), "written down as not moved"); detach_for_update(&handle); { let db = cotton_store::driver::Driver::open(layout.replica(&local)).expect("the copy"); db.run( &format!("UPDATE \"{}\" SET body = ? WHERE step = ?", cotton_store::shape_move::MOVE_TABLE), &[rusqlite::types::Value::Text(body), rusqlite::types::Value::Integer(step)], ) .expect("the step put back"); db.checkpoint_truncate().expect("a checkpoint"); } handle.client().attach_now().expect("the copy attaches"); handle.client().settle_moves_for_tests(); assert!(cotton_client::moves::left(&local).is_none(), "the move is finished"); assert!(cotton_client::bootstrap::not_moved::why(layout, &local).is_none(), "nothing more to explain"); let db = cotton_store::driver::Driver::open(layout.replica(&local)).expect("the copy"); assert_eq!(cotton_store::migrate::current_version(&db).expect("the stamp"), cotton_store::migrate::SCHEMA_VERSION); let kept: Vec<Option<i64>> = db.all("SELECT moving FROM _kept_while_moving", &[]).expect("the watch").iter().map(|row| row.int("moving")).collect(); assert_eq!(kept, vec![Some(0)], "the kit is kept once, after the move"); let columns = db.all("SELECT name FROM pragma_table_info('cotton_todos')", &[]).expect("columns"); assert!(columns.iter().any(|row| row.text("name") == Some(dropped.as_str())), "the moved table is whole: {dropped}");}// ── a copy stuck on one page ────────────────────────────────────────────────/// A connected phone over the garden object, its copy marked so a copy made/// again is told from it, every later page failing with `status`.fn stuck_phone(status: u16) -> (tempfile::TempDir, CottonHandle, Arc<Served>) { let (dir, handle) = phone_for_update(); let object = the_garden(); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); mark(&handle, "invented_marker"); *object.stuck_page.lock().expect("the stuck page") = Some(status); (dir, handle, object)}fn mark(handle: &CottonHandle, marker: &str) { let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); copy.execute_batch(&format!("CREATE TABLE {marker} (x)")).expect("a marker");}fn marked(handle: &CottonHandle, marker: &str) -> bool { let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); copy.query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = ?1", [marker], |row| row.get::<_, i64>(0)).expect("a count") == 1}/// Three passes, each failing on the page after the first.fn three_failed_passes(handle: &CottonHandle) { for pass in 0..3 { assert!(handle.client().sync_now().is_err(), "pass {pass} fails on its page"); }}/// Wait for the heal's own thread to make the copy again and open it. The/// heal rebuilds the whole kit; a debug build with the a_copy tests running/// side by side on a loaded box takes past a minute (5 Nov 2026), so the wait/// is three.fn made_again(handle: &CottonHandle) { let progress = handle.client().sync_progress().expect("the passes' progress"); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180); while progress.state().copy_remade_at.is_none() || handle.client().attached_database().is_none() { assert!(std::time::Instant::now() < deadline, "the copy was not made again"); std::thread::sleep(std::time::Duration::from_millis(20)); }}/// RULE (owner's phone, 2 Nov 2026: one page asked every 30 s for a day; a fresh copy on the same build caught up): a copy whose passes fail on one page for one reason three passes running while the object answers is made again from the object — a new file, the device row told why it stalled and that the copy was made again, and the next pass asking from nothing.#[test]fn a_copy_stuck_on_one_page_three_passes_running_is_made_again_from_the_object() { let (_dir, handle, object) = stuck_phone(422); three_failed_passes(&handle); made_again(&handle); assert!(!marked(&handle, "invented_marker"), "the copy is a new file"); let asked_before = object.asked.lock().expect("the pages asked").len(); *object.stuck_page.lock().expect("the stuck page") = None; handle.client().sync_now().expect("the copy made again catches up"); let asked = object.asked.lock().expect("the pages asked").clone(); assert!(asked[asked_before].starts_with("/v1/sync?since=0"), "the next pass asks from nothing: {:?}", &asked[asked_before..]); let taken = object.taken.lock().expect("the acts").clone(); let device = |key: &str| taken.iter().filter(|act| act["act"] == "update" && act["args"]["id"] == "invented-phone-row").filter_map(|act| act["args"]["data"].get(key).cloned()).collect::<Vec<_>>(); assert!(device("stalled_why").iter().any(|why| why.as_str().is_some_and(|why| why.contains("cannot take"))), "the row says why: {taken:?}"); assert!(device("copy_remade_at").iter().any(serde_json::Value::is_string), "the row says the copy was made again: {taken:?}"); assert_eq!(device("stalled_why").last(), Some(&serde_json::Value::Null), "and the page that landed cleared why: {taken:?}");}/// RULE: a phone that cannot reach the object is offline, not stuck: three passes failing with no answer leave the copy as it is.#[test]fn a_copy_that_reaches_nothing_three_passes_running_is_not_made_again() { let (_dir, handle, _object) = stuck_phone(0); three_failed_passes(&handle); assert!(handle.client().sync_now().is_err()); let progress = handle.client().sync_progress().expect("the passes' progress"); assert_eq!(progress.stuck(), None); assert_eq!(progress.state().copy_remade_at, None); assert!(marked(&handle, "invented_marker"), "the copy is kept");}/// RULE (incident, 21 Nov 2026: the Worker answered 500 to every sync of a big object for hours): an object failing is never the copy stuck on its page — a pass that stops mid-way because the object's definitions answered 500 (its page holds rows only they place), three passes running, leaves the copy as it is, never made again into an empty one.#[test]fn a_copy_whose_object_fails_mid_pass_three_passes_running_is_not_made_again() { let (_dir, handle) = phone_for_update(); let object = the_garden(); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); mark(&handle, "invented_marker"); object.later_page_unplaced.store(true, std::sync::atomic::Ordering::SeqCst); *object.definitions_fail.lock().expect("the definitions' status") = Some(500); for pass in 0..4 { assert!(handle.client().sync_now().is_err(), "pass {pass} stops on its second page"); } let progress = handle.client().sync_progress().expect("the passes' progress"); assert_eq!(progress.stuck(), None, "the object failing is not the copy stuck"); std::thread::sleep(std::time::Duration::from_millis(200)); assert_eq!(progress.state().copy_remade_at, None); assert!(marked(&handle, "invented_marker"), "the copy is kept");}/// RULE (live, 21 Nov 2026: a phone making its copy again sent `create group_member` again and again, each refused 409 duplicate_id, the object holding it already): Notes files a note into its # groups only over a copy that holds what the object holds. While the first pull runs, a note whose groups have not come yet is listed and left unfiled (no member made again, no second group of a name the object holds); once the pull ends, the next list files what is truly unfiled.#[test]fn a_copy_on_its_first_pull_files_no_note_until_it_holds_the_objects_groups() { let (_dir, handle) = phone_for_update(); let object = the_garden(); *object.sync_fails.lock().expect("the sync's status") = Some(500); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected: the copy is made before any page"); assert_eq!(notes_list(&handle)["copy"], "bringing"); assert!(!crate::phone::notes::files_now(&handle), "no note is filed over a copy still on its first pull"); *object.sync_fails.lock().expect("the sync's status") = None; handle.client().sync_now().expect("the object answers"); assert_eq!(notes_list(&handle)["copy"], "held"); assert!(crate::phone::notes::files_now(&handle), "the pull ended: notes are filed");}/// shell.home once its gate has opened the copy (the open runs off the call: the first answers wait).fn home_open(handle: &CottonHandle) -> serde_json::Value { for _ in 0..500 { let home = crate::methods::dispatch(handle, "shell.home", &json!({})).expect("shell.home"); if home["gate"]["stage"] == "open" { return home; } std::thread::sleep(std::time::Duration::from_millis(20)); } panic!("the home's gate never opened");}/// Where a list's or a record's answer says the copy stands.fn notes_list(handle: &CottonHandle) -> serde_json::Value { crate::methods::dispatch(handle, "notes.list", &json!({"view": "all"})).expect("notes.list")}/// RULE (incident, 21 Nov 2026: a phone making its copy again during the outage showed Notes' empty list and "That note is no longer here", and Chat's "No chats yet"): while a signed-in copy's first pull has not ended, an empty list says its things are on their way ("bringing"), and once a pass has failed (the object answered 500) that Cotton could not be reached just now ("unreached"); a note not found is `not_here_yet` in those words, never gone; shell.home's `bringing` says which. The loop waits on its ladder. Once a pass lands, the list says it is truly empty ("held") and a note not found is gone.#[test]fn a_copy_whose_first_pull_fails_says_cotton_could_not_be_reached_never_that_nothing_is_here() { let (_dir, handle) = phone_for_update(); let object = the_garden(); *object.sync_fails.lock().expect("the sync's status") = Some(500); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected: the copy is made before any page"); let list = notes_list(&handle); assert_eq!(list["copy"], "bringing", "{list}"); assert_eq!(list["empty"], "Loading your data…"); assert!(handle.client().sync_now().is_err(), "the object answers 500"); let unreached = "Cotton could not be reached just now. Your things come to this phone once it answers."; let list = notes_list(&handle); assert_eq!(list["copy"], "unreached", "{list}"); assert_eq!(list["empty"], unreached); let chats = crate::methods::dispatch(&handle, "chat.list", &json!({})).expect("chat.list"); assert_eq!(chats["copy"], "unreached", "{chats}"); assert_eq!(chats["words"]["empty"], unreached); let open = crate::methods::dispatch(&handle, "notes.open", &json!({"id": "an-invented-note", "cursor": 0})).unwrap_err(); assert_eq!(open.code, crate::phone::copy_standing::NOT_HERE_YET, "{}", open.message); assert_eq!(open.message, unreached); let home = home_open(&handle); assert_eq!(home["bringing"]["state"], "unreached", "{home}"); assert_eq!(home["bringing"]["words"], unreached); *object.sync_fails.lock().expect("the sync's status") = None; handle.client().sync_now().expect("the object answers again"); let list = notes_list(&handle); assert_eq!(list["copy"], "held", "{list}"); assert_eq!(list["empty"], "No notes yet. Tap the round button to write one."); let gone = crate::methods::dispatch(&handle, "notes.open", &json!({"id": "an-invented-note", "cursor": 0})).unwrap_err(); assert_eq!(gone.code, "not_found", "a held copy says a note it lacks is gone"); let home = home_open(&handle); assert!(home["bringing"].is_null(), "{home}");}/// RULE (big invented account on the emulator, 21 Nov 2026: a new phone's first pull of 2,800 sealed notes ended in five seconds with every note parked for want of the key; Notes said "No notes yet" and the loading line was gone while the phone asked for the recovery code): a copy whose rows have come but wait for the account's key is still bringing the person's things. Its empty list says so, and shell.home says "Loading your data…", with no figure since no pass is counting. Once the key is held the copy holds them, and the line goes.#[test]fn a_copy_whose_rows_wait_for_the_key_is_still_bringing_them() { let (_dir, handle) = phone_for_update(); let object = the_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("the first pull ends"); assert_eq!(notes_list(&handle)["copy"], "held"); // The pull parked a sealed note for want of the key, as a new phone's does before the person gives it. let replica = handle.client().layout().replica(DATABASE); let parked = cotton_client::seal::Note::Parked { table: "note".into(), id: "an-invented-note".into(), code: cotton_client::seal::SEAL_KEY_MISSING.into(), reason: "seal_key_missing: no key for the data key of this database (this device holds none yet)".into(), row: json!({"table": "note", "id": "an-invented-note"}), at: "2026-11-21T10:00:00.000Z".into(), }; cotton_client::seal::write_notes(&rusqlite::Connection::open(&replica).expect("the copy"), &[parked]).expect("parked"); let list = notes_list(&handle); assert_eq!(list["copy"], "bringing", "{list}"); assert_eq!(list["empty"], "Loading your data…", "never \"No notes yet\" over notes that wait for the key"); let home = home_open(&handle); assert_eq!(home["bringing"]["words"], "Loading your data…", "{home}"); assert!(home["bringing"]["percent"].is_null(), "no pass is counting: {home}"); handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::mint()); assert_eq!(notes_list(&handle)["copy"], "held", "the key held, the next pass opens them: the copy holds them"); assert!(home_open(&handle)["bringing"].is_null());}/// RULE (incident, 21 Nov 2026: Account's Last error read "the business did not answer"): a connect the object answers 500 says on the Account card that Cotton could not be reached just now, in the kit's words; the Worker's own words stay in the log.#[test]fn a_connect_the_object_answers_500_says_cotton_could_not_be_reached_never_the_workers_words() { let (_dir, handle) = phone(); let failing = ScriptedExchange::new([Reply::json(500, WORKER_FAILED)]); let refused = call_with(&handle, "personal.connect", &ask(), failing as Arc<dyn Exchange>).unwrap_err(); assert_eq!(refused.code, "internal_error"); 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.starts_with("Cotton could not be reached just now. Nothing here is lost."), "{card}"); assert!(!said.contains("did not answer"), "never the Worker's words: {card}");}/// RULE: a copy is made again for a stuck page at most once a launch: one that stalls again after it is left alone and keeps saying why.#[test]fn a_copy_made_again_this_launch_is_not_made_again() { let (_dir, handle, _object) = stuck_phone(422); three_failed_passes(&handle); made_again(&handle); mark(&handle, "invented_second_marker"); three_failed_passes(&handle); let progress = handle.client().sync_progress().expect("the passes' progress"); assert!(progress.stuck().is_some(), "the copy made again is stuck again"); assert!(handle.client().sync_now().is_err()); std::thread::sleep(std::time::Duration::from_millis(200)); assert!(marked(&handle, "invented_second_marker"), "and is left alone"); assert!(progress.state().stalled_why.is_some(), "and keeps saying why");}/// A probe of a real object (coordinator, 3 Nov 2026): connects a fresh copy/// to the object `COTTON_PROBE_SERVER` names, as the bearer in the file/// `COTTON_PROBE_CREDENTIAL_FILE`, and runs passes until one fails three/// times alike or the copy catches up, printing each pass's answer. Never/// run by the gate; it reaches the network.#[test]#[ignore]fn probe_a_real_object_until_a_pass_fails() { let server = std::env::var("COTTON_PROBE_SERVER").expect("COTTON_PROBE_SERVER"); let database = std::env::var("COTTON_PROBE_DATABASE").expect("COTTON_PROBE_DATABASE"); let credential = std::fs::read_to_string(std::env::var("COTTON_PROBE_CREDENTIAL_FILE").expect("COTTON_PROBE_CREDENTIAL_FILE")).expect("the credential file").trim().to_string(); let keep = std::env::var("COTTON_PROBE_KEEP_DIR").expect("COTTON_PROBE_KEEP_DIR"); std::fs::create_dir_all(&keep).unwrap(); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: keep.clone(), 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(cotton()), }) .expect("an open core"); /// The real wire for every call but `GET /v1/me`, which an owner token /// cannot answer (no device): the probe says it is the owner itself. #[derive(Debug)] struct ProbeExchange; impl Exchange for ProbeExchange { 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> { cotton_client::transport::SocketExchange.send_stream(origin, request, body, length, ceiling) } 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> { if request.method == "GET" && request.path.starts_with("/v1/me") { let me = ScriptedExchange::new([Reply::ok(&json!({"person": {"id": "probe-owner", "role": "owner"}, "version": 1}).to_string())]); return me.send(origin, request, ceiling); } // COTTON_PROBE_SINCE_ONE: the pass from nothing asks since=1, so the // object serves it in plain change order, as the Worker before // 4c307aaba2 served every pass (the order the owner's copy filled in). if std::env::var("COTTON_PROBE_SINCE_ONE").is_ok() && request.method == "GET" && request.path.contains("/v1/sync?since=0") { let path = request.path.replacen("since=0", "since=1", 1); eprintln!("[probe] asking {path}"); let rewritten = cotton_client::transport::http1::Http1Request { method: request.method, path: &path, authority: request.authority, headers: request.headers.clone(), body: request.body }; return cotton_client::transport::SocketExchange.send(origin, &rewritten, ceiling); } cotton_client::transport::SocketExchange.send(origin, request, ceiling) } } let exchange: Arc<dyn Exchange> = Arc::new(ProbeExchange); let ask = json!({"server": server, "databaseId": database, "credential": credential, "windows": {"message": 90}, "deviceName": "Probe mac-c"}); let started = std::time::Instant::now(); let connected = call_with(&handle, "personal.connect", &ask, Arc::clone(&exchange)); eprintln!("[probe] connect after {:?}: {:?}", started.elapsed(), connected.as_ref().map(|v| v.to_string()).map_err(|e| format!("{e:?}"))); connected.expect("connected"); let client = handle.client(); let mut same = 0u32; let mut last_error = String::new(); for pass in 1..=400 { let at = std::time::Instant::now(); match client.sync_now() { Ok(answer) => { same = 0; let behind = answer.get("behind").and_then(Value::as_bool).unwrap_or(false); eprintln!("[probe] pass {pass} ok in {:?}: pulled {} pushed {} behind {behind} rows {}", at.elapsed(), answer.get("pulled").and_then(Value::as_u64).unwrap_or(0), answer.get("pushed").and_then(Value::as_u64).unwrap_or(0), answer.get("rows").map(|v| v.to_string()).unwrap_or_default()); if !behind { eprintln!("[probe] caught up after {:?}", started.elapsed()); return; } } Err(error) => { eprintln!("[probe] pass {pass} FAILED in {:?}: {error}", at.elapsed()); if error == last_error { same += 1 } else { same = 0; last_error = error } if same >= 2 { eprintln!("[probe] the same failure three passes running; stopping after {:?}", started.elapsed()); return; } std::thread::sleep(std::time::Duration::from_secs(2)); } } }}/// The object a phone signs in to with twenty tools: Books and nineteen/// others, and a made table beside the Books kit's.fn twenty_tools() -> Arc<Served> { let mut tools = vec![served_tool("books", "Books")]; tools.extend((1..20).map(|n| served_tool(&format!("made_{n:02}"), &format!("Made {n}")))); let book: serde_json::Value = serde_json::from_slice(cotton_core::kit::table_file("book").expect("the kit's book table")).expect("JSON"); Served::new(json!([served_table("garden_bed"), book]), json!(tools), json!([]), "e1")}/// Cotton Books' fan: its kit's one tool, beside the shell's Bin.const BOOKS_FAN: [&str; 2] = ["bin", "books"];fn fan_of(handle: &CottonHandle) -> Vec<String> { let db = cotton_store::driver::Driver::open(handle.client().layout().replica(DATABASE)).expect("the copy"); cotton_tools::home_arrangement::tools(&db, DATABASE, None, true).expect("the fan's tools read")}fn books_ask() -> serde_json::Value { json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "credential": "synthetic-credential", "deviceName": "An invented phone"})}/// RULE (coordinator, 5 Nov 2026: Cotton Books on the owner's phone drew his whole Cotton and synced every table): an app keeps to the kit its manifest names — of twenty tools the object serves, Books draws Books alone, holds no table its kit does not name, and asks the object for its kit's tables only; Cotton, naming no kit, draws all twenty and asks for every table.#[test]fn an_app_keeps_to_its_kit_on_the_whole_object() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, books()); let object = twenty_tools(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), BOOKS_FAN, "the first paint is the kit's"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("a pass that finds the copy matching"); assert_eq!(fan_of(&handle), BOOKS_FAN, "and every pass keeps it"); let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); let held = |id: &str| copy.query_row("SELECT COUNT(*) FROM cotton_table_definitions WHERE id = ?1", [id], |row| row.get::<_, i64>(0)).expect("a count"); assert_eq!((held("garden_bed"), held("book")), (0, 1), "a table the kit does not name stays on the object"); let asked = object.asked.lock().expect("the pages asked").clone(); let tables_of = |path: &str| -> Vec<String> { path.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').map(str::to_string).collect() }; let pulls: Vec<&String> = asked.iter().filter(|path| path.contains("since=0&")).collect(); // A fresh copy fills with the app's own tables first (launch-fast, 20 Nov 2026), then pulls the tables it left // whole, the rest since its cursor (22 Nov 2026: never the whole kit again from the start). let first = tables_of(pulls.first().expect("a first fill")); assert!(first.iter().any(|table| table == "book") && first.iter().any(|table| table == "seal_key"), "the app's own tables come first: {first:?}"); assert!(!first.iter().any(|table| table == "media" || table == "device"), "the whole object's pictures and the shell's tables wait: {first:?}"); assert_eq!(pulls.len(), 1, "never from the start again: {asked:?}"); let left = asked.iter().find(|path| path.contains("again=")).unwrap_or_else(|| panic!("the pass after the fill asks the tables it left again: {asked:?}")); for table in ["media", "device"] { assert!(left.split("again=").nth(1).is_some_and(|again| again.split('&').next().unwrap_or_default().split(',').any(|named| named == table)), "{table} comes whole: {left}"); } let whole = tables_of(left); for table in ["book", "highlight", "record_group", "group_member", "media", "photo", "face_settings", "device"] { assert!(whole.iter().any(|held| held == table), "{table} is pulled: {whole:?}"); } assert!(!whole.iter().any(|table| table == "garden_bed" || table == "todo" || table == "message"), "nothing else is: {whole:?}"); drop(copy); drop(handle); let (_cotton_dir, cotton) = phone(); let object = twenty_tools(); call_with(&cotton, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); cotton.client().sync_now().expect("a pass"); let fan = fan_of(&cotton); assert!(fan.iter().any(|tool| tool == "books") && (1..20).all(|n| fan.contains(&format!("made_{n:02}"))), "Cotton draws all twenty: {fan:?}"); assert!(object.asked.lock().expect("the pages asked").iter().all(|path| !path.contains("tables=")), "Cotton asks for every table");}/// RULE (launch-fast, 20 Nov 2026: Cotton Story showed no scripts for minutes on the first open after an update): a copy of this very kit pulled before the kit gained a table is kept, every row on screen, and its next pass pulls again from the start, so the rows written before its cursor still come down; it is never made again.#[test]fn a_copy_of_this_kit_pulled_before_it_gained_a_table_is_kept_and_pulled_again_from_the_start() { let dir = tempfile::tempdir().expect("a temp container"); let object = twenty_tools(); let handle = phone_in(&dir, books()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); // Past its first fill (which owes the next pass the tables it left, whole), as a copy in use is. handle.client().sync_now().expect("the pass after the first fill"); let path = handle.client().layout().replica(DATABASE); detach_for_update(&handle); // The mark an earlier Books build left: the kit before it gained its latest tables. std::fs::write(format!("{}{}", path.display(), cotton_client::transport::object::COPY_KIT_SUFFIX), "books book,media").expect("the earlier mark"); rusqlite::Connection::open(&path).expect("the copy").execute_batch("CREATE TABLE invented_sentinel (x)").expect("a sentinel"); object.asked.lock().expect("the pages asked").clear(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); let kept: i64 = rusqlite::Connection::open(&path).expect("the copy") .query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = 'invented_sentinel'", [], |row| row.get(0)).expect("a count"); assert_eq!(kept, 1, "the copy is kept, never made again"); assert_eq!(cotton_client::transport::object::copy_kit(&path), cotton_core::kit::AppKit::copy_mark(cotton_core::kit::AppKit::named("books").as_ref()), "marked as the kit ships"); assert_eq!(fan_of(&handle), BOOKS_FAN, "the fan draws from the kept copy at once"); handle.client().sync_now().expect("a pass"); let asked = object.asked.lock().expect("the pages asked").clone(); let first = asked.iter().find(|path| path.contains("since=")).expect("a first page"); // The tables the kit gained come whole, the rest since the cursor: never the whole object again (21 Nov 2026). let gained: Vec<String> = cotton_core::kit::AppKit::named("books").expect("Books").pulled().into_iter().filter(|table| table != "book" && table != "media").collect(); let again: Vec<&str> = first.split("again=").nth(1).expect("the pass asks some tables again").split('&').next().unwrap_or_default().split(',').collect(); assert!(first.contains("since=3&") && !again.is_empty() && again.iter().all(|table| gained.iter().any(|gained| gained == table)), "the pass asks gained tables whole (those this copy places) and the rest since its cursor: {first}"); let taken = object.taken.lock().expect("the acts").clone(); assert!(!taken.iter().any(|act| act["args"]["data"]["copy_remade_at"].is_string()), "nothing says the copy was made again: {taken:?}"); // Once they came, nothing is owed: the next pass asks since its cursor alone. object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("the next pass"); let next = object.asked.lock().expect("the pages asked").iter().find(|path| path.contains("since=")).cloned().expect("a page"); assert!(next.contains("since=3&") && !next.contains("again="), "nothing more is owed: {next}");}/// RULE (the coordinator's review of COMMS WITHOUT MAIL, 27 Nov 2026): a kit that only lets tables go (Comms' kit losing/// its eight mail tables) keeps the copy AND its cursor: the copy is marked as the kit ships and its next pass asks/// since its cursor alone, never every table from the start again on a copy of several gigabytes.#[test]fn a_kit_that_only_lets_tables_go_keeps_its_cursor() { let dir = tempfile::tempdir().expect("a temp container"); let object = twenty_tools(); let handle = phone_in(&dir, books()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("the pass after the first fill"); let path = handle.client().layout().replica(DATABASE); detach_for_update(&handle); // The mark an earlier build left: this kit's tables and two more it has since let go. let shipped = cotton_core::kit::AppKit::copy_mark(cotton_core::kit::AppKit::named("books").as_ref()); let (id, tables, _) = cotton_core::kit::AppKit::read_copy_mark(&shipped); std::fs::write(format!("{}{}", path.display(), cotton_client::transport::object::COPY_KIT_SUFFIX), format!("{id} {},email,email_thread", tables.join(","))).expect("the earlier mark"); object.asked.lock().expect("the pages asked").clear(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); assert_eq!(cotton_client::transport::object::copy_kit(&path), shipped, "marked as the kit ships"); handle.client().sync_now().expect("a pass"); let asked = object.asked.lock().expect("the pages asked").clone(); let first = asked.iter().find(|path| path.contains("since=")).expect("a first page"); assert!(first.contains("since=3&") && !first.contains("again="), "since its cursor alone, nothing again: {first}");}/// RULE (21 Nov 2026): a kit that gained a table, its copy's pass asking an object that cannot carry tables again (a Worker before `again=`), pulls again from the start as before: nothing the cursor went past is skipped.#[test]fn a_kit_that_gained_a_table_pulls_from_the_start_from_an_object_that_cannot_carry_tables_again() { let dir = tempfile::tempdir().expect("a temp container"); let object = twenty_tools(); let handle = phone_in(&dir, books()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); handle.client().sync_now().expect("the pass after the first fill"); let path = handle.client().layout().replica(DATABASE); detach_for_update(&handle); std::fs::write(format!("{}{}", path.display(), cotton_client::transport::object::COPY_KIT_SUFFIX), "books book,media").expect("the earlier mark"); object.old_worker.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("a pass"); let asked = object.asked.lock().expect("the pages asked").clone(); assert!(asked.iter().any(|path| path.contains("again=")), "it asked: {asked:?}"); assert!(asked.iter().any(|path| path.contains("since=0&")), "and, not carried, pulled from the start: {asked:?}");}/// RULE (5 Nov 2026): a copy pulled for the whole object (an earlier Books build, or Cotton's) is made again on the app's kit at its next connect, unsent writes sent first, through the path a copy another build wrote takes; one pulled for this kit is kept.#[test]fn a_copy_pulled_for_another_kit_is_made_again_on_this_one() { let dir = tempfile::tempdir().expect("a temp container"); let object = twenty_tools(); let whole = phone_in(&dir, cotton()); call_with(&whole, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected as the whole object"); whole.client().sync_now().expect("a pass"); assert!(fan_of(&whole).len() >= 20); let path = whole.client().layout().replica(DATABASE); assert_eq!(cotton_client::transport::object::copy_kit(&path), "whole"); whole.client().set_runtime(None); whole.client().set_after_pass(Arc::new(|| {})); detach_for_update(&whole); drop(whole); let handle = phone_in(&dir, books()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); assert_eq!(cotton_client::transport::object::copy_kit(&path), cotton_core::kit::AppKit::copy_mark(cotton_core::kit::AppKit::named("books").as_ref()), "the copy is the kit's now"); assert_eq!(fan_of(&handle), BOOKS_FAN, "made again on the kit, not filtered over the old copy"); handle.client().sync_now().expect("a pass"); let taken = object.taken.lock().expect("the acts").clone(); assert!(taken.iter().any(|act| act["args"]["data"]["copy_remade_at"].is_string()), "the device row says the copy was made again: {taken:?}"); detach_for_update(&handle); rusqlite::Connection::open(&path).expect("the copy").execute_batch("CREATE TABLE invented_sentinel (x)").expect("a sentinel"); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the next launch"); let kept: i64 = rusqlite::Connection::open(&path).expect("the copy") .query_row("SELECT COUNT(*) FROM sqlite_master WHERE name = 'invented_sentinel'", [], |row| row.get(0)).expect("a count"); assert_eq!(kept, 1, "a copy pulled for this kit is kept"); assert_eq!(fan_of(&handle), BOOKS_FAN);}/// RULE (Cotton Data, CONTRACT row 7): with Keep everything chosen on this device, Data's copy is the whole object/// with no window; switched off, it is made again on Data's kit and the rows it filled leave this phone.#[test]fn keep_everything_makes_datas_copy_the_whole_object_and_off_makes_it_small_again() { let dir = tempfile::tempdir().expect("a temp container"); let object = twenty_tools(); let mut data = books(); data["kit"] = json!("data"); let handle = phone_in(&dir, data); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); let path = handle.client().layout().replica(DATABASE); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected on Data's kit"); let small = cotton_core::kit::AppKit::copy_mark(cotton_core::kit::AppKit::named("data").as_ref()); assert_eq!(cotton_client::transport::object::copy_kit(&path), small); detach_for_update(&handle); std::fs::write(handle.client().layout().root().join("data-keep.json"), r#"{"on":true}"#).expect("the choice"); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected on mobile data"); assert_eq!(cotton_client::transport::object::copy_kit(&path), small, "Wi-Fi only: the whole copy waits for Wi-Fi"); detach_for_update(&handle); let mut on_wifi = books_ask(); on_wifi["unmetered"] = json!(true); call_with(&handle, "personal.connect", &on_wifi, Arc::clone(&object) as Arc<dyn Exchange>).expect("connected on Wi-Fi"); assert_eq!(cotton_client::transport::object::copy_kit(&path), "whole", "the whole object"); object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("a pass"); let asked = object.asked.lock().expect("the pages asked").clone(); assert!(asked.iter().all(|p| !p.contains("tables=") && !p.contains("window=")), "every table, no window: {asked:?}"); // The room guard stops only the fill (ANDROID READY 1 core fault 3): this copy has come whole, so under 2 GB free // its sync goes on and the pass ends well. A fill stopped for room: `transport::object`'s // the_room_guard_stops_only_the_fill_never_the_writes_or_the_sync_after_it. *crate::phone::data_app::TEST_FREE.lock().unwrap() = Some(1_200_000_000); object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("short of room, the sync of a whole copy ends well"); let asked = object.asked.lock().expect("the pages asked").clone(); assert!(asked.iter().any(|p| p.contains("since=")), "a whole copy keeps syncing under 2 GB free: {asked:?}"); *crate::phone::data_app::TEST_FREE.lock().unwrap() = Some(50_000_000_000); object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("a pass with room"); assert!(object.asked.lock().expect("the pages asked").iter().any(|p| p.contains("since=")), "with room the pass pulls again"); *crate::phone::data_app::TEST_FREE.lock().unwrap() = None; detach_for_update(&handle); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("back on mobile data"); assert_eq!(cotton_client::transport::object::copy_kit(&path), "whole", "once started it stays whole on any network"); detach_for_update(&handle); std::fs::write(handle.client().layout().root().join("data-keep.json"), r#"{"on":false}"#).expect("the choice"); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected small again"); assert_eq!(cotton_client::transport::object::copy_kit(&path), small, "made again on Data's kit");}/// Cotton Cinemas' manifest, as the app sends it.fn cinemas() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/cinemas/flavour.json")).expect("Cinemas' manifest")}/// The object a phone signs in to as a fresh number's: the whole personal kit, every tool and table, its Home naming the tools that hold no rows.fn the_whole_kit() -> Arc<Served> { let mut tools = Vec::new(); let mut tables: Vec<serde_json::Value> = Vec::new(); for id in cotton_core::kit::ids() { let package = cotton_core::kit::package(id).expect("a kit tool").expect("the package reads").package; for table in &package.tables { if !tables.iter().any(|held| held["id"] == json!(table.id)) { tables.push(json!(table)); } } tools.push(json!(package.tool)); } // The tables the apps' kits name that no tool's package carries (Books' // and Cinemas' face_settings): the object is made from the same kit files // (apps/business/src/kits.ts), so it serves them too — every app kit's. let over_personal = |json: &str| serde_json::from_str::<serde_json::Value>(json).expect("a kit.json")["tables"].as_array().is_some_and(|tables| !tables.is_empty() && tables.iter().all(|table| table.as_str().is_some_and(|table| table.starts_with("personal/")))); for kit in cotton_core::kit::APP_KITS.iter().filter(|(_, json)| over_personal(json)).filter_map(|(id, _)| cotton_core::kit::AppKit::named(id)) { for id in &kit.tables { let file = cotton_store::manifest_dir().join(format!("../cotton-core/kits/personal/tables/{id}.json")); let table: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap_or_else(|error| panic!("{}: {error}", file.display()))).expect("a kit table"); if !tables.iter().any(|held| held["id"] == json!(id)) { tables.push(table); } } } let empty: Vec<&str> = cotton_core::kit::ids(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan", "empty": empty}]}); Served::new(json!(tables), json!(tools), json!([home]), "w1")}/// RULE (6 Nov 2026: Cinemas Dev signed in to an object Cotton Dev made was seen drawing no tool): an app signed in to a fresh number's object — the whole personal kit, every tool empty — draws its own kit's tool whole, at the first paint and after a pass: Cinemas on its views, nothing of Cotton's beside it.#[test]fn cinemas_signed_in_to_the_whole_kit_draws_cinemas() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, cinemas()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), ["bin", "cinemas"], "the copy holds the kit's tool alone"); let keys = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect() }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); assert_eq!(keys(&first), ["cinemas"], "Cinemas is the fan: {first}"); assert_eq!(first["opens"], json!({"tier": "views", "tool": "cinemas", "view": "films"})); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(keys(&after), ["cinemas"], "and after a pass: {after}");}/// The pull that names the whole kit. A fresh copy fills with the app's own/// tables first and the next pass pulls the tables it left whole (launch-fast,/// 20 Nov 2026): a pass more is asked until that pull has been, and its first/// page answered.fn whole_pull(handle: &CottonHandle, object: &Served) -> String { let names_the_kit = |path: &&String| path.contains("since=") && path.split("tables=").nth(1).is_some_and(|tables| tables.split('&').next().unwrap_or_default().split(',').any(|table| table == "device")); for _ in 0..4 { if let Some(pull) = object.asked.lock().expect("the pages asked").iter().filter(names_the_kit).last() { return pull.clone(); } handle.client().sync_now().expect("a pass"); } panic!("no pull named the whole kit: {:?}", object.asked.lock().expect("the pages asked"));}/// Cotton Notes' manifest, as the app sends it.fn notes() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/notes/flavour.json")).expect("Notes' manifest")}/// RULE (Cotton Notes, 11 Nov 2026): Notes signed in to a fresh number's object — the whole personal kit — draws the Notebook alone and opens on its views, at the first paint and after a pass, and its pulls ask the object for the notes kit's tables and the shell's only: the note and what it links, never a todo, a message or a book.#[test]fn notes_signed_in_to_the_whole_kit_draws_the_notebook_and_pulls_its_kit() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, notes()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), ["bin", "notebook"], "the copy holds the kit's tool alone"); let keys = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect() }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); assert_eq!(keys(&first), ["notebook"], "the Notebook is the fan: {first}"); assert_eq!(first["opens"], json!({"tier": "views", "tool": "notebook", "view": "notes:all"})); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(keys(&after), ["notebook"], "and after a pass: {after}"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); let kit = cotton_core::kit::AppKit::named("notes").expect("the notes kit ships"); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); for never in ["todo", "message", "book", "thought", "event"] { assert!(!tables.contains(&never), "{never} stays on the object: {pull}"); } // RULE (owner, 21 Nov 2026): Words keeps what the assistant wrote: its memory, the memories' project links, and of // the documents only the web pages (`only`), never a statement or a receipt. assert!(["memory", "project_link", "document"].iter().all(|table| tables.contains(table)), "{pull}"); assert!(pull.contains("&only=document.mime:text%2Fhtml"), "of the documents, the web pages alone: {pull}");}/// Cotton Messages' manifest, as the app sends it.fn messages() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/messages/flavour.json")).expect("Messages' manifest")}/// RULE (Cotton Messages, 11 Nov 2026): Messages signed in to a fresh number's object — the whole personal kit — draws Messages alone and opens on All, at the first paint and after a pass, and its pulls ask the object for the messages kit's tables and the shell's only: threads, messages and what they link, never an email, a note or a book.#[test]fn messages_signed_in_to_the_whole_kit_draws_messages_and_pulls_its_kit() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, messages()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); // The recordings' tool is held folded (chat DECISIONS "Recordings", 23 Nov 2026): kept, never drawn as a tile. assert_eq!(fan_of(&handle), ["bin", "meetings", "messages"], "the copy holds the kit's tools"); let keys = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect() }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); assert_eq!(keys(&first), ["messages"], "Messages is the fan: {first}"); assert_eq!(first["opens"], json!({"tier": "views", "tool": "messages", "view": "all"})); let views = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"][0]["views"].as_array().expect("views").iter().map(|view| view["id"].as_str().expect("an id").to_string()).collect() }; // The recordings' views stand folded inside Messages' own (Comms draws its own Calls, never these views). let held = ["account", "all", "cotton", "whatsapp", "sms", "instagram", "starred", "devices", "recent", "meetings", "memos", "on_phone"]; assert_eq!(views(&first), held, "the Agents view is Developer's: {first}"); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(keys(&after), ["messages"], "and after a pass: {after}"); assert_eq!(views(&after), held, "and after a pass: {after}"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); let kit = cotton_core::kit::AppKit::named("messages").expect("the messages kit ships"); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); // Mail is Cotton Post's (COMMS WITHOUT MAIL, d0dcfeeace): Comms pulls none of it, and no window for it. assert!(!pull.contains("window=email"), "no mail window: {pull}"); for never in ["book", "event", "transaction", "session", "project", "email", "email_thread", "email_draft", "email_account"] { assert!(!tables.contains(&never), "{never} stays on the object: {pull}"); } // RULE (owner, 23 Nov 2026; chat DECISIONS "Recordings"): Comms keeps the recordings, and the to-dos and notes // they become (Add to to-dos, Save as note), so it pulls them. for kept in ["meetings_meeting", "meetings_line", "meetings_speaker", "meetings_action", "todo", "note"] { assert!(tables.contains(&kept), "{kept} is Comms' now: {pull}"); } // The blocked list You's Blocked row counts and its page lists (one list with Post's): pulled, so it says the truth. assert!(tables.contains(&"blocked_sender"), "Comms pulls the blocked list: {pull}");}/// Cotton People's manifest, as the app sends it.fn people() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/people/flavour.json")).expect("People's manifest")}/// RULE (Cotton People, 11 Nov 2026): People signed in to a fresh number's object — the whole personal kit — holds People and Birthdays but draws People alone, opening on All, with Birthdays' Birthday wishes and Everyone among People's views after its own, at the first paint and after a pass; a deck of Birthday wishes reads as People's; and its pulls ask the object for the people kit's tables and the shell's only: the person and what People owns, never a todo, a message or a note.#[test]fn people_signed_in_to_the_whole_kit_draws_birthdays_as_peoples_views() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, people()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), ["bin", "birthdays", "people"], "the copy holds the kit's tool and the one it folds"); let drawn = |answer: &serde_json::Value| -> (Vec<String>, Vec<String>) { let tiles = answer["tiles"].as_array().expect("tiles"); let keys = tiles.iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect(); let views = tiles.iter().find(|tile| tile["key"] == "people").map(|tile| tile["views"].as_array().expect("People's views").iter().map(|view| view["id"].as_str().expect("an id").to_string()).collect()).unwrap_or_default(); (keys, views) }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); let (keys, views) = drawn(&first); assert_eq!(keys, ["people"], "People is the fan, Birthdays no tile of its own: {first}"); assert_eq!(views, ["account", "all", "a_to_z", "wishes", "everyone"], "Birthdays' views after People's own: {first}"); assert_eq!(first["opens"], json!({"tier": "views", "tool": "people", "view": "all"})); crate::methods::dispatch(&handle, "records.create", &json!({"table": "person", "data": {"full_name": "Invented Friend", "birthday": "1990-11-20", "own_birthdays__wish": true}, "timezone": "UTC"})).expect("a person made here"); let wishes = crate::methods::dispatch(&handle, "shell.deck", &json!({"table": "person", "view": "people/wishes", "timezone": "UTC", "today": "2026-11-11"})).expect("People's Birthday wishes deal"); let cards = wishes["cards"].as_array().expect("cards"); assert_eq!(cards.iter().map(|card| card["slots"]["title"].clone()).collect::<Vec<_>>(), ["Invented Friend"], "the person wished is dealt: {wishes}"); assert_eq!((&cards[0]["face"], &cards[0]["slots"]["wishes"]), (&json!("birthday"), &json!(true)), "in Birthdays' face, its switch on: {wishes}"); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(drawn(&after), (keys, views), "and after a pass: {after}"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); let kit = cotton_core::kit::AppKit::named("people").expect("the people kit ships"); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); for never in ["todo", "message", "note", "book", "event"] { assert!(!tables.contains(&never), "{never} stays on the object: {pull}"); }}/// Cotton Calendar's manifest, as the app sent it: Days took its identity (20 Nov 2026) and its folder left the tree; the calendar kit stays.fn calendar() -> serde_json::Value { serde_json::from_str(r#"{"genesis":"personal","flavour":"calendar","name":"Cotton Calendar","ground":"kitchenTile","databases":"single","database":"personal","business":{"server":{"real":"https://cottondb.com","dev":"https://dev.example.invalid"}},"fan":{"home":false,"tools":false,"opens":"calendar"},"kit":"calendar"}"#).expect("Calendar's manifest")}/// RULE (Cotton Calendar, 11 Nov 2026): Calendar signed in to a fresh number's object — the whole personal kit — draws the Calendar tool alone and opens on Today, at the first paint and after a pass, and its pulls ask the object for the calendar kit's tables and the shell's only: the event, its attendees and what it links, never mail, a todo, a note or a book.#[test]fn calendar_signed_in_to_the_whole_kit_draws_the_calendar_and_pulls_its_kit() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, calendar()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), ["bin", "calendar"], "the copy holds the kit's tool alone"); let keys = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect() }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); assert_eq!(keys(&first), ["calendar"], "the Calendar is the fan: {first}"); assert_eq!(first["opens"], json!({"tier": "views", "tool": "calendar", "view": "today"})); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(keys(&after), ["calendar"], "and after a pass: {after}"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); let kit = cotton_core::kit::AppKit::named("calendar").expect("the calendar kit ships"); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); for never in ["email_thread", "meeting", "todo", "message", "book", "note"] { assert!(!tables.contains(&never), "{never} stays on the object: {pull}"); }}/// Cotton Photos' manifest, as the app sends it.fn photos() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/photos/flavour.json")).expect("Photos' manifest")}/// RULE (Cotton Photos, 12 Nov 2026): Photos signed in to a fresh number's object — the whole personal kit — draws the Photos tool alone and opens on its default view, at the first paint and after a pass, and its pulls ask the object for the photos kit's tables and the shell's only: the library, its albums and what a print names, never a chat, a mail, a note or a book.#[test]fn photos_signed_in_to_the_whole_kit_draws_photos_and_pulls_its_kit() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, photos()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), ["bin", "photos"], "the copy holds the kit's tool alone"); let keys = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect() }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); assert_eq!(keys(&first), ["photos"], "Photos is the fan: {first}"); let tool: serde_json::Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tools/photos/manifest.json")).expect("the Photos tool"); let default = tool["views"].as_array().unwrap().iter().find(|view| view["is_default"] == true).expect("Photos opens on a view")["id"].clone(); assert_eq!(first["opens"], json!({"tier": "views", "tool": "photos", "view": default})); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(keys(&after), ["photos"], "and after a pass: {after}"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); let kit = cotton_core::kit::AppKit::named("photos").expect("the photos kit ships"); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); for never in ["thread", "message", "email_thread", "note", "book", "todo"] { assert!(!tables.contains(&never), "{never} stays on the object: {pull}"); }}/// What a phone of `manifest` signed in to the whole kit sends the object for/// a row it makes in `table`, with the data key held: every act it posted/// for that table, and the whole of what it posted, as text./// The phone holds the person's data key (synthetic): what a copy needs to/// send rows of a table the rule seals, todos among them (e2e rulings R1).fn holds_the_data_key(handle: &CottonHandle, object: &Arc<Served>) { use base64::Engine as _; object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); object.serves_now.store(true, std::sync::atomic::Ordering::SeqCst); handle.client().sync_now().expect("a first pass, which reads the seal keys"); let key = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9u8; 32]); crate::methods::dispatch(handle, "seal.useKey", &json!({"key": key})).expect("the data key held");}/// RULE (e2e rulings R3, 15 Nov 2026): a phone whose object holds its todos sealed is the writer of record for a repeating todo's occurrences: the object cannot read a series' words to copy them, so the launch pass mints here (ids derived from the series and the moment, so two phones make one). A copy whose todos are not sealed (a Mac serves it) mints nothing (launch_outbox_tests).#[test]fn a_phone_whose_object_seals_its_todos_mints_their_occurrences() { let dir = tempfile::tempdir().expect("a temp container"); let manifest: serde_json::Value = serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/days/flavour.json")).expect("Days' manifest"); let handle = phone_in(&dir, manifest); let object = the_whole_kit(); { let mut definitions = object.definitions.lock().expect("the definitions"); for table in definitions["tables"].as_array_mut().expect("tables") { if table["id"] == json!("todo") || table["id"] == json!("todo_recurrence") { *table = cotton_core::seal::rule::ruled(table); } } } call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); let pass = crate::methods::dispatch(&handle, "write", &json!({"tool": "materialize_todo_recurrences", "args": {"timezone": "Asia/Kolkata"}})).expect("the launch pass"); assert_eq!(pass["answer"]["mints"], json!(true), "{pass}");}/// Cotton Health's manifest, as the app sends it.fn health_app() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/health/flavour.json")).expect("Health's manifest")}/// RULE (Cotton Health, 12 Nov 2026): Health signed in to a fresh number's object — the whole personal kit — draws the Health tool alone and opens on Today, at the first paint and after a pass, and its pulls ask the object for the health kit's tables and the shell's only: the day's numbers, workouts, measurements and the vault's rows, never a chat, a mail, a note or a journal page.#[test]fn health_signed_in_to_the_whole_kit_draws_health_and_pulls_its_kit() { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, health_app()); let object = the_whole_kit(); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); assert_eq!(fan_of(&handle), ["bin", "health"], "the copy holds the kit's tool alone"); let keys = |answer: &serde_json::Value| -> Vec<String> { answer["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key").to_string()).collect() }; let first = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan at the first paint"); assert_eq!(keys(&first), ["health"], "Health is the fan: {first}"); assert_eq!(first["opens"], json!({"tier": "views", "tool": "health", "view": "today"})); handle.client().sync_now().expect("a pass"); let after = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan after a pass"); assert_eq!(keys(&after), ["health"], "and after a pass: {after}"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); let kit = cotton_core::kit::AppKit::named("health").expect("the health kit ships"); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); for table in ["health_day", "health_workout", "health_measurement"] { assert!(tables.contains(&table), "{table} is pulled: {pull}"); } for never in ["thread", "message", "email_thread", "note", "journal_entry", "todo"] { assert!(!tables.contains(&never), "{never} stays on the object: {pull}"); }}/// Cotton Keys' manifest, as the app sends it.fn keys_app() -> serde_json::Value { serde_json::from_str(include_str!("../../../../apps/cotton/App/Flavours/keys/flavour.json")).expect("Keys' manifest")}/// RULE (owner, 11 Nov 2026): Passwords folds into Cotton Keys as a second tool. Keys signed in to a fresh number's object draws Keys and Passwords, fans one tier of views with Passwords' on it, and pulls Passwords' tables beside the passkeys. A Keys copy pulled before (marked with the kit's tables as they were) is kept at its next launch and pulled again from the start on the kit as it ships (launch-fast, 20 Nov 2026: made again, a copy stood empty until the whole object came down), so the passwords written before its cursor arrive too: add-only, nothing of the copy's own lost.#[test]fn keys_draws_passwords_and_a_copy_pulled_before_them_pulls_again_from_the_start() { let dir = tempfile::tempdir().expect("a temp container"); let object = the_whole_kit(); let handle = phone_in(&dir, keys_app()); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); let mut held = fan_of(&handle); held.sort(); assert_eq!(held, ["bin", "keys", "passwords"], "the copy holds the kit's tools alone"); let fan = crate::methods::dispatch(&handle, "shell.fan", &json!({})).expect("the fan"); let keys: Vec<&str> = fan["tiles"].as_array().expect("tiles").iter().map(|tile| tile["key"].as_str().expect("a key")).collect(); // One tier of views, no tools tier (owner, 11 Nov 2026): Passwords' views stand on Keys' tier. assert_eq!(keys, ["keys"], "one tier: {fan}"); assert_eq!(fan["opens"]["tier"], "views", "{fan}"); assert!(fan["tiles"][0]["views"].as_array().unwrap().iter().any(|view| view["id"] == "logins" && view["read"]["table"] == "secret"), "Passwords' Logins is a view: {fan}"); let kit = cotton_core::kit::AppKit::named("keys").expect("the keys kit ships"); // The connect starts the copy's first pass on the loop's own thread; // a pass asked here is that pass, or one after it, so a pull is asked // before the pages are read (a loaded box ran the loop's pass late). handle.client().sync_now().expect("a pass"); let pull = &whole_pull(&handle, &object); let tables: Vec<&str> = pull.split("tables=").nth(1).expect("the pull names its tables").split('&').next().unwrap_or_default().split(',').collect(); assert_eq!(tables, kit.pulled(), "the kit's tables and the shell's: {pull}"); assert!(tables.contains(&"secret") && tables.contains(&"passkey"), "{pull}"); // The copy as a Keys build before Passwords marked it. let path = handle.client().layout().replica(DATABASE); let before: Vec<String> = kit.pulled().into_iter().filter(|table| table != "secret").collect(); std::fs::write(format!("{}{}", path.display(), cotton_client::transport::object::COPY_KIT_SUFFIX), format!("keys {}", before.join(","))).expect("the old mark"); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); detach_for_update(&handle); drop(handle); let handle = phone_in(&dir, keys_app()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the launch after the update"); assert_eq!(cotton_client::transport::object::copy_kit(&path), cotton_core::kit::AppKit::copy_mark(Some(&kit)), "the copy is the kit's as it ships"); object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("a pass"); let taken = object.taken.lock().expect("the acts").clone(); assert!(!taken.iter().any(|act| act["args"]["data"]["copy_remade_at"].is_string()), "the copy is kept, never made again (launch-fast, 20 Nov 2026): {taken:?}"); let asked = object.asked.lock().expect("the pages asked").clone(); // The tables it gained come again whole beside the cursor (`again=`, d446b570b), never the whole object from since=0. assert!( asked.iter().any(|path| path.split("again=").nth(1).is_some_and(|rest| { let again: Vec<&str> = rest.split('&').next().unwrap_or_default().split(',').collect(); again.contains(&"secret") && !again.contains(&"placement_proposal") })), "and the passwords' tables pulled again from their start, so what was written before its cursor arrives: {asked:?}" ); let mut held = fan_of(&handle); held.sort(); assert_eq!(held, ["bin", "keys", "passwords"]);}/// RULE (Cotton Cinemas 1.0 (2), 6 Nov 2026: the owner's lists counted on their tiles and said "Films could not be read" when opened): signed in to the object, a list an assistant made there (record_group and group_member rows, brought by sync) and a list made on the phone each open as a deck of their members, in Books, Cinemas, Notes, Calendar and People, by the name the fan's views tier gives them (Music left with TABLE DROP 1).#[test]fn signed_in_lists_open_as_decks_in_every_app_with_lists() { for (manifest, table, tool, data) in [ (books(), "book", "books", json!({"title": "Invented Dune", "author": "A. Writer"})), (cinemas(), "film", "cinemas", json!({"title": "Invented film", "kind": "film"})), (notes(), "note", "notebook", json!({"title": "Invented note", "body": "Invented words"})), (calendar(), "event", "calendar", json!({"title": "Invented event", "starts_at": "2026-11-20T10:00:00.000Z"})), (people(), "person", "people", json!({"full_name": "Invented Person"})), ] { let dir = tempfile::tempdir().expect("a temp container"); let handle = phone_in(&dir, manifest); let object = the_whole_kit(); let row = |table: &str, id: &str, data: serde_json::Value| json!({"table": table, "id": id, "version": 3, "owner": null, "data": data, "created_at": "2026-10-26T08:00:00.000Z", "updated_at": "2026-10-26T08:00:00.000Z"}); *object.rows.lock().expect("the rows") = json!([ row(table, "invented-synced-member", data.clone()), row("record_group", "invented-synced-list", json!({"table_id": table, "name": "Invented synced list", "position": 1})), row("group_member", "invented-synced-membership", json!({"group": "invented-synced-list", "record_id": "invented-synced-member", "place": 1})), ]); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": table, "data": data, "timezone": "Asia/Kolkata"})).expect("a record made here"); let member = made["id"].as_str().or_else(|| made["record"]["id"].as_str()).expect("its id").to_string(); let made = crate::methods::dispatch(&handle, "groups.create", &json!({"table": table, "name": "Invented list", "records": [member]})).expect("a list made here"); let here = made["group"]["id"].as_str().expect("its id").to_string(); let fan = crate::methods::dispatch(&handle, "shell.fan", &json!({"tool": tool, "timezone": "Asia/Kolkata"})).expect("the fan"); let tile = fan["tiles"].as_array().expect("tiles").iter().find(|tile| tile["key"] == tool).unwrap_or_else(|| panic!("no {tool} tile: {fan}")); for (group, held) in [(here.as_str(), member.as_str()), ("invented-synced-list", "invented-synced-member")] { let id = format!("group:{group}"); assert!(tile["views"].as_array().expect("views").iter().any(|view| view["id"] == id.as_str()), "{tool}'s tier holds {group}: {tile}"); let deck = crate::methods::dispatch(&handle, "shell.deck", &json!({"table": table, "view": format!("{tool}/{id}"), "timezone": "Asia/Kolkata"})) .unwrap_or_else(|error| panic!("{tool}: {group}'s deck reads: {error:?}")); let cards: Vec<&str> = deck["cards"].as_array().expect("cards").iter().map(|card| card["id"].as_str().expect("an id")).collect(); assert_eq!(cards, [held], "{tool}: {group}'s deck is its member: {deck}"); } }}// RULE (sealing plan L8): a sealed message's file comes down as the object// keeps it and opens on the phone with the file key its message carries; a// key no message here names, or bytes that do not open, are refused by name.#[test]fn a_sealed_messages_file_opens_with_the_file_key_its_message_carries() { use cotton_core::seal::file; let dir = tempfile::tempdir().unwrap(); let replica = dir.path().join("replica.db"); let key = file::object_key("00000000-0000-4000-8000-000000000001"); let fk = file::FileKey::random(); { let db = rusqlite::Connection::open(&replica).unwrap(); db.execute_batch("PRAGMA journal_mode = WAL; CREATE TABLE cotton_msg_messages (id TEXT PRIMARY KEY, media TEXT); CREATE TABLE cotton_stories (id TEXT PRIMARY KEY, media_key TEXT)").unwrap(); let media = serde_json::json!([{ "key": key, "contentType": "image/jpeg", "fileKey": fk.text() }]).to_string(); db.execute("INSERT INTO cotton_msg_messages (id, media) VALUES ('m1', ?1)", [media]).unwrap(); } let plain = b"synthetic picture bytes".repeat(5000); let raw = dir.path().join("download.sealed"); let mut sealed = Vec::new(); file::seal_file(&fk, &key, &mut &plain[..], &mut sealed).unwrap(); std::fs::write(&raw, &sealed).unwrap(); let dest = dir.path().join("download"); super::open_sealed_download(&replica, &key, &raw, &dest).unwrap(); assert_eq!(std::fs::read(&dest).unwrap(), plain); assert!(!raw.exists(), "the sealed bytes go once opened"); std::fs::write(&raw, &sealed).unwrap(); let other = file::object_key("00000000-0000-4000-8000-000000000001"); let refused = super::open_sealed_download(&replica, &other, &raw, &dest).unwrap_err(); assert_eq!(refused.status, Some(404), "{refused:?}"); let mut tampered = sealed.clone(); tampered[20] ^= 1; std::fs::write(&raw, &tampered).unwrap(); let refused = super::open_sealed_download(&replica, &key, &raw, &dest).unwrap_err(); assert!(refused.reason.starts_with("seal_does_not_open"), "{refused:?}");}// RULE: a sealed story's picture opens on the phone// with the file key its table's blind key derives from the object key; with// no data key held it waits, refused by name, and writes nothing.#[test]fn a_sealed_storys_picture_opens_with_the_key_the_data_key_derives() { use cotton_client::seal::HeldDataKeys; use cotton_core::seal::{blind_key, file, DataKey}; let database = "00000000-0000-4000-8000-000000000001"; let dir = tempfile::tempdir().unwrap(); let replica = dir.path().join("replica.db"); let key = file::object_key(database); { let db = rusqlite::Connection::open(&replica).unwrap(); db.execute_batch("PRAGMA journal_mode = WAL; CREATE TABLE cotton_msg_messages (id TEXT PRIMARY KEY, media TEXT); CREATE TABLE cotton_stories (id TEXT PRIMARY KEY, media_key TEXT)").unwrap(); db.execute("INSERT INTO cotton_stories (id, media_key) VALUES ('s1', ?1)", [&key]).unwrap(); } let dk = DataKey::from_bytes([5; 32]); let fk = file::derived_key(&blind_key(&dk, database, "story").unwrap(), &key); let plain = b"synthetic story picture".repeat(4000); let mut sealed = Vec::new(); file::seal_file(&fk, &key, &mut &plain[..], &mut sealed).unwrap(); let raw = dir.path().join("download.sealed"); let dest = dir.path().join("download"); let keys = HeldDataKeys::new(); let stories = super::StoryKeys { keys: std::sync::Arc::clone(&keys), database: database.into() }; std::fs::write(&raw, &sealed).unwrap(); let waits = super::open_sealed_download_with(&replica, Some(&stories), &key, &raw, &dest).unwrap_err(); assert!(waits.reason.starts_with(cotton_client::seal::SEAL_KEY_MISSING), "{waits:?}"); assert!(!dest.exists() || std::fs::read(&dest).unwrap().is_empty()); keys.hold(database, &dk); std::fs::write(&raw, &sealed).unwrap(); super::open_sealed_download_with(&replica, Some(&stories), &key, &raw, &dest).unwrap(); assert_eq!(std::fs::read(&dest).unwrap(), plain);}// SIGN-IN NEVER WAITS ON THE KEY IT BRINGS (17 Nov 2026).// An updated app over a copy an earlier build wrote, holding unsent rows and// no data key: the copy is made again at sign-in, its unsent rows go first,// sending a sealed row wants the key, and the key only reaches a phone whose// copy is connected. The rule: the sign-in connects; the earlier copy waits// whole beside it until the key is held; then its rows go sealed, and only// then is it let go. No row is dropped, none goes clear./// The Todos object: the garden with the real Todos package served, whose/// todo the seal rule seals (e2e rulings R1).fn the_todos_garden() -> Arc<Served> { let object = the_garden(); let todos = cotton_core::kit::package("todos").expect("the kit has Todos").expect("the package reads").package; { let mut definitions = object.definitions.lock().expect("the definitions"); definitions["tables"].as_array_mut().expect("tables").extend(todos.tables.iter().map(|table| json!(table))); definitions["tools"].as_array_mut().expect("tools").push(json!(todos.tool)); } object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); object.serves_now.store(true, std::sync::atomic::Ordering::SeqCst); object}fn unsent_todos(path: &std::path::Path) -> usize { cotton_client::unsent::unsent_changes(path).expect("the copy's unsent writes").into_iter().filter(|change| change.table == "cotton_todos").count()}fn todos_taken(object: &Served) -> Vec<serde_json::Value> { object.taken.lock().expect("the acts").iter().filter(|act| act["args"]["table"] == "todo" || act["args"]["rows"].as_array().is_some_and(|rows| rows.iter().any(|row| row["table"] == "todo"))).cloned().collect()}fn hold_key(handle: &CottonHandle) { use base64::Engine as _; let key = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9u8; 32]); crate::methods::dispatch(handle, "seal.useKey", &json!({"key": key})).expect("the data key held");}/// A phone whose copy an earlier build wrote, holding `todos` unsent todos/// (none if 0), signed out, and holding no data key: the app updated.fn updated_signed_out(todos: usize, key: bool) -> (tempfile::TempDir, CottonHandle, Arc<Served>) { let (dir, handle) = phone_for_update(); let object = the_todos_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the first sign-in"); handle.client().sync_now().expect("a first pass, which reads the seal keys"); for n in 0..todos { crate::methods::dispatch(&handle, "records.create", &json!({"table": "todo", "data": {"title": format!("An invented errand {n}")}})).expect("a todo"); } let _ = handle.client().sync_now(); let path = handle.client().layout().replica(DATABASE); assert_eq!(unsent_todos(&path), todos, "no key: every todo waits"); assert!(todos_taken(&object).is_empty(), "nothing went clear"); detach_for_update(&handle); { let copy = rusqlite::Connection::open(&path).expect("the copy"); written_by_a_build_whose_rise_rebuilds(©); } handle.client().set_placing(false); call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), ScriptedExchange::new([]) as Arc<dyn Exchange>).expect("signed out"); if key { handle.client().data_keys().hold(DATABASE, &cotton_core::seal::DataKey::from_bytes([9u8; 32])); } (dir, handle, object)}/// RULE: an updated app holding unsent rows in a copy an earlier build wrote, and no data key, signs in: the sign-in connects a copy of this build, the earlier copy waits whole with every unsent row, nothing goes clear and nothing is written down as lost; once the key is held the next pass sends them sealed, and only then is the earlier copy let go.#[test]fn unsent_rows_and_no_key_sign_in_then_go_sealed_once_the_key_is_held() { let (_dir, handle, object) = updated_signed_out(2, false); let path = handle.client().layout().replica(DATABASE); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the sign-in connects with no key"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION, "the copy is this build's"); assert_eq!(handle.client().attached_database().as_deref(), Some(DATABASE)); let waiting = crate::phone::personal_object::waiting_copy(handle.client().layout(), DATABASE); assert!(waiting.exists(), "the earlier copy waits beside it"); assert_eq!(unsent_todos(&waiting), 2, "every unsent row waits in it"); assert!(todos_taken(&object).is_empty(), "nothing went clear"); assert!(cotton_client::unsent::discarded(handle.client().layout(), DATABASE).is_empty(), "nothing was lost"); handle.client().sync_now().expect("a pass with no key pulls, and the earlier copy still waits"); assert!(waiting.exists()); hold_key(&handle); handle.client().sync_now().expect("the pass once the key is held"); let taken = todos_taken(&object); let creates: Vec<_> = taken.iter().filter(|act| act["act"] == "create").collect(); assert_eq!(creates.len(), 2, "each todo once: {taken:?}"); assert!(creates.iter().all(|act| act["args"]["data"]["sealed_enc"].as_str().is_some_and(|text| text.starts_with("s1:")) && act["args"]["data"].get("title").is_none()), "sealed, never clear: {taken:?}"); assert!(!waiting.exists(), "the earlier copy is let go once the object holds its rows"); assert!(cotton_client::unsent::discarded(handle.client().layout(), DATABASE).is_empty(), "nothing was lost");}/// RULE: the same updated app already holding the data key signs in as before: its earlier copy's unsent rows go up sealed before it goes, during the sign-in, and no copy is left waiting.#[test]fn unsent_rows_and_the_key_held_go_sealed_at_sign_in() { let (_dir, handle, object) = updated_signed_out(2, true); let path = handle.client().layout().replica(DATABASE); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the sign-in"); let taken = todos_taken(&object); let creates: Vec<_> = taken.iter().filter(|act| act["act"] == "create").collect(); assert_eq!(creates.len(), 2, "each todo once, at the sign-in: {taken:?}"); assert!(creates.iter().all(|act| act["args"]["data"]["sealed_enc"].as_str().is_some_and(|text| text.starts_with("s1:")) && act["args"]["data"].get("title").is_none()), "sealed: {taken:?}"); assert!(!crate::phone::personal_object::waiting_copy(handle.client().layout(), DATABASE).exists(), "nothing waits"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION); assert!(cotton_client::unsent::discarded(handle.client().layout(), DATABASE).is_empty(), "nothing was lost");}/// RULE: an updated app with no unsent rows and no data key signs in as before: its earlier copy is made again and nothing waits or goes up.#[test]fn no_unsent_rows_and_no_key_sign_in_with_nothing_waiting() { let (_dir, handle, object) = updated_signed_out(0, false); let path = handle.client().layout().replica(DATABASE); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the sign-in"); assert_eq!(stamp(&rusqlite::Connection::open(&path).expect("the copy")), cotton_store::migrate::SCHEMA_VERSION); assert!(!crate::phone::personal_object::waiting_copy(handle.client().layout(), DATABASE).exists(), "nothing waits"); assert!(todos_taken(&object).is_empty()); handle.client().sync_now().expect("a pass");}/// RULE: a send that stops half way loses nothing and can be tried again: a sign-in whose object stops answering keeps the earlier copy where it was, every row in it, and a second sign-in connects; once the key is held, a pass whose object stops answering keeps the waiting copy whole with every row and writes nothing down as lost; the next pass that reaches the object sends each row once, sealed, and lets the copy go.#[test]fn a_send_stopped_half_way_keeps_every_row_waiting_and_is_tried_again() { let (_dir, handle, object) = updated_signed_out(2, false); let path = handle.client().layout().replica(DATABASE); let waiting = crate::phone::personal_object::waiting_copy(handle.client().layout(), DATABASE); // THE SIGN-IN STOPS: the object stops answering after its definitions. object.pages.store(false, std::sync::atomic::Ordering::SeqCst); *object.restores_left.lock().expect("the restores left") = Some(0); object.acts.store(false, std::sync::atomic::Ordering::SeqCst); let first = call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>); // However it ends, nothing is lost: the earlier copy is where it was or waits whole. let held = if waiting.exists() { waiting.clone() } else { path.clone() }; assert_eq!(unsent_todos(&held), 2, "every row still waits ({first:?})"); assert!(todos_taken(&object).is_empty(), "nothing went clear"); object.pages.store(true, std::sync::atomic::Ordering::SeqCst); *object.restores_left.lock().expect("the restores left") = None; object.acts.store(true, std::sync::atomic::Ordering::SeqCst); if first.is_err() { call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the sign-in tried again"); } assert!(waiting.exists(), "the earlier copy waits for the key"); // THE KEY ARRIVES AND THE SEND STOPS HALF WAY. hold_key(&handle); object.acts.store(false, std::sync::atomic::Ordering::SeqCst); let _ = handle.client().sync_now(); assert!(waiting.exists(), "the waiting copy is kept"); assert_eq!(unsent_todos(&waiting), 2, "every row still waits in it"); assert!(cotton_client::unsent::discarded(handle.client().layout(), DATABASE).is_empty(), "nothing was written down as lost"); // TRIED AGAIN. object.acts.store(true, std::sync::atomic::Ordering::SeqCst); handle.client().sync_now().expect("the pass that reaches the object"); let creates: Vec<_> = todos_taken(&object).into_iter().filter(|act| act["act"] == "create").collect(); let ids: std::collections::BTreeSet<String> = creates.iter().filter_map(|act| act["args"]["id"].as_str().map(str::to_string)).collect(); assert_eq!(ids.len(), 2, "both todos went: {creates:?}"); assert!(creates.iter().all(|act| act["args"]["data"]["sealed_enc"].as_str().is_some_and(|text| text.starts_with("s1:"))), "sealed: {creates:?}"); assert!(!waiting.exists(), "let go once the object holds them"); assert!(cotton_client::unsent::discarded(handle.client().layout(), DATABASE).is_empty(), "nothing was lost");}/// An exchange that holds the first `/v1/me` until the test lets it go: a connect in flight, stopped where it waits on the object.struct HeldAtMe { object: Arc<Served>, reached: std::sync::Mutex<Option<std::sync::mpsc::Sender<()>>>, release: std::sync::Mutex<std::sync::mpsc::Receiver<()>>,}impl Exchange for HeldAtMe { 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> { if request.path.starts_with("/v1/me") { if let Some(reached) = self.reached.lock().expect("the signal").take() { reached.send(()).expect("the test waits"); self.release.lock().expect("the release").recv().expect("the test lets it go"); } } self.object.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> { self.object.send_stream(origin, request, body, length, ceiling) }}impl std::fmt::Debug for HeldAtMe { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("HeldAtMe") }}/// What the Account card says, as the phones read it.fn card_of(handle: &CottonHandle) -> (serde_json::Value, serde_json::Value) { let card = crate::methods::dispatch(handle, "shell.account", &json!({})).expect("shell.account"); (crate::phone::tool_acts::account_status(&handle.client()), card)}/// `trouble`: whether the card says this phone cannot reach its database, or `None` where either may stand.fn assert_still_signed_in(handle: &CottonHandle, when: &str, trouble: Option<bool>) { let (status, card) = card_of(handle); assert_eq!(status["signed_in"], json!(true), "{when}: still signed in: {status} {card}"); if let Some(trouble) = trouble { assert_eq!(card["trouble"], json!(trouble), "{when}: no trouble while it simply runs: {card}"); } let acts: Vec<&str> = card["actions"].as_array().expect("the acts").iter().filter_map(|act| act["id"].as_str()).collect(); assert!(!acts.contains(&crate::phone::tool_acts::ACCOUNT_SIGN_IN), "{when}: no Sign in: {card}"); let signed_out = cotton_core::rules::shell_lines::resolve("boot", "account.tile.signed_out", &[], &[]).expect("the signed-out line"); assert_ne!(card["line"], json!(signed_out), "{when}: the glance is not signed out: {card}");}/// RULE (owner's iPhone, Chat build 14, 21 Nov 2026: while the copy was made again after the update, the Account card offered Sign in and said Cotton could not be reached): a phone signed in stays signed in while its copy is connected or made again, and after a connect that did not take and left it standing on its copy — never offered Sign in; no trouble while a connect simply runs, its glance "Loading your data…".#[test]fn a_signed_in_phone_stays_signed_in_while_its_copy_is_made_again() { let (_dir, handle) = phone_for_update(); let object = the_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the first launch"); assert_still_signed_in(&handle, "signed in", Some(false)); // The update: the old app's copy is held while the new build's replaces it, at 141 (a rise that rebuilds, still made again since 0ba6610e78). detach_for_update(&handle); copy_written_at_141(&handle.client().layout().replica(DATABASE)); assert_still_signed_in(&handle, "while the copy is put in place", Some(false)); // The new launch's connect does not take (the object out of reach), and the phone stands on its copy, as the iPhone does after one. *object.definitions_fail.lock().expect("the failing status") = Some(500); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect_err("the object out of reach"); call_with(&handle, "personal.standLocal", &json!({}), Arc::clone(&object) as Arc<dyn Exchange>).expect("standing on its copy"); assert!(!handle.client().signed_in(), "the record says local now"); // The copy is still being put in place (the update's placing): whether that is said as trouble is not this rule's. assert_still_signed_in(&handle, "after a connect that did not take", None); *object.definitions_fail.lock().expect("the failing status") = None; // The next connect, stopped on the object while it makes the copy again. let (reached, waiting) = std::sync::mpsc::channel(); let (release, released) = std::sync::mpsc::channel(); let held = Arc::new(HeldAtMe { object: Arc::clone(&object), reached: std::sync::Mutex::new(Some(reached)), release: std::sync::Mutex::new(released) }); std::thread::scope(|scope| { let connecting = scope.spawn(|| call_with(&handle, "personal.connect", &ask(), Arc::clone(&held) as Arc<dyn Exchange>)); waiting.recv().expect("the connect reaches the object"); assert_still_signed_in(&handle, "while the connect runs", Some(false)); let loading = cotton_core::rules::shell_lines::resolve("boot", "home.bringing", &[], &[]).expect("the loading line"); assert_eq!(card_of(&handle).1["line"], json!(loading), "the glance says the data is on its way"); release.send(()).expect("let it go"); connecting.join().expect("the connect's thread").expect("the launch after the update"); }); assert!(handle.client().signed_in(), "connected again"); assert_still_signed_in(&handle, "once the copy is made again", Some(false)); // Signed out, it is signed out. call_with(&handle, "personal.standLocal", &json!({"signedOut": true}), Arc::clone(&object) as Arc<dyn Exchange>).expect("signed out"); assert_eq!(crate::phone::tool_acts::account_status(&handle.client())["signed_in"], json!(false), "Sign out signs out");}/// RULE (TRIM 3, coordinator, 21 Nov 2026): a copy keeps only the last 7 days of its Bin; the rest is listed from the object (`seal.bin`, opened here, the copy's own binned rows left out) and restored there (`seal.restoreBinned`: the clear bin mark cleared, as any restore goes up), so a restore works from a copy without the row. Invented rows.#[test]fn a_bin_beyond_the_copy_lists_from_the_object_and_restores_there() { let (_dir, handle) = phone(); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let object = Served::new(json!([served_table("garden_bed")]), json!([served_tool("notebook", "Journal")]), json!([home]), "e1"); object.pages.store(false, std::sync::atomic::Ordering::SeqCst); assert_eq!(crate::methods::dispatch(&handle, "seal.bin", &json!({"tables": ["project"]})).expect_err("not on the object yet").code, "not_attached"); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); let binned = |id: &str| json!({"table": "project", "id": id, "version": 4, "owner": null, "data": {"name": "An invented project", "trashed_at": "2026-11-01T09:00:00.000Z"}, "created_at": "2026-10-01T09:00:00.000Z", "updated_at": "2026-11-01T09:00:00.000Z"}); *object.bin.lock().expect("the bin") = json!([binned("p-old-1"), binned("p-old-2")]); let listed = crate::methods::dispatch(&handle, "seal.bin", &json!({"tables": ["project"], "limit": 50})).expect("the Bin beyond the copy"); let ids: Vec<&str> = listed["rows"].as_array().expect("rows").iter().filter_map(|row| row["id"].as_str()).collect(); assert_eq!(ids, ["p-old-1", "p-old-2"], "{listed}"); assert_eq!(listed["rows"][0]["row"]["name"], "An invented project"); assert_eq!(listed["more"], false); assert!(object.asked.lock().expect("asked").iter().any(|path| path.starts_with("/v1/bin?tables=project&limit=50")), "{:?}", object.asked.lock().unwrap()); assert_eq!(crate::methods::dispatch(&handle, "seal.bin", &json!({"tables": ["bad table"]})).expect_err("a name is checked").code, "bad_request"); crate::methods::dispatch(&handle, "seal.restoreBinned", &json!({"table": "project", "id": "p-old-2"})).expect("restored on the object"); let acts = object.taken.lock().expect("the acts").clone(); assert!(acts.iter().any(|act| *act == json!({"act": "update", "args": {"table": "project", "id": "p-old-2", "data": {"trashed_at": null}}})), "{acts:?}");}/// RULE (coordinator, 21 Nov 2026, the hand walk of a trim): Cotton Dev lands invented messages in its own copy as a pull lands the object's rows, makes their receipts whole again as a build before 151 left them, and the in-place trim then walks them; the real Cotton refuses it by name.#[test]fn cotton_dev_invents_a_served_copy_the_trim_then_walks() { 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::Dev, manifest: Some(cotton()), }) .expect("an open core"); let home = json!({"format_version": 1, "id": "home", "parts": [{"kind": "tools", "face": "fan"}]}); let object = Served::new(json!([served_table("garden_bed")]), json!([served_tool("notebook", "Journal")]), json!([home]), "e1"); object.pages.store(false, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); let invent = |request: serde_json::Value| crate::methods::dispatch(&handle, "developer.inventServedCopy", &request).expect("invented"); assert_eq!(invent(json!({ "count": 500 }))["held"], 500); assert_eq!(invent(json!({ "from": 500, "count": 500 }))["held"], 1000); let count = |sql: &str| handle.client().with_file(|file| Ok(file.driver.get(sql, &[]).unwrap().and_then(|row| row.int("n")).unwrap_or(-1))).unwrap(); assert_eq!(count("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE id LIKE 'dev-message-%'"), 1000); assert!(count("SELECT COUNT(*) AS n FROM _writes WHERE implied IS NOT NULL") >= 1000, "landed as this build lands a pull"); while invent(json!({ "whole": true }))["wholeAgain"].as_u64() != Some(0) {} assert_eq!(count("SELECT COUNT(*) AS n FROM _writes WHERE implied IS NOT NULL"), 0, "whole, as before 151"); crate::phone::trim::carry(&handle.client()); assert!(count("SELECT COUNT(*) AS n FROM _writes WHERE implied IS NOT NULL") >= 1000, "the trim walked them in place"); assert_eq!(count("SELECT COUNT(*) AS n FROM _outbox"), 0, "nothing to send"); let (_real_dir, real) = phone(); assert_eq!(crate::methods::dispatch(&real, "developer.inventServedCopy", &json!({})).expect_err("the real Cotton").code, "not_dev");}/// RULE (seen on emulator-5554, 22 Nov 2026, Comms on an invented account of 110,001 emails): a search of mail whose/// reach past the phone's window the object refuses says so in the kit's words at the foot of the Mail tab, never the/// Worker's ("internal_error: the business did not answer").#[test]fn a_mail_search_the_object_refuses_says_so_in_the_kits_words() { let (_dir, handle) = phone(); let object = Served::new(json!([]), json!([]), json!([]), "e1"); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); *object.blind_fails.lock().expect("the failing status") = Some(500); let page = crate::methods::dispatch(&handle, "chat.mail", &json!({"text": "ferry"})).expect("a search answers"); let older = page["older"].as_str().unwrap_or_default().to_string(); let offline = cotton_core::rules::shell_lines::resolve("chat", "app.mail.older_offline", &[], &[]).expect("the kit's line"); assert_eq!(older, offline, "{page} asked {:?}", object.asked.lock().unwrap());}/// RULE (MAIL ALL ON PHONE, 24 Nov 2026, after COMMS WITHOUT MAIL d0dcfeeace): mail is Cotton Post's, whose kit keeps/// every mail whole with no window, so the account's `mail_all` switch has nothing to widen on a Comms phone: heard/// and kept beside the cursor, it pulls nothing again at the next launch (no `again=`, never the whole object).#[test]fn an_account_switched_to_all_mail_pulls_nothing_again_on_comms() { let dir = tempfile::tempdir().expect("a temp container"); let object = the_whole_kit(); object.serves_now.store(true, std::sync::atomic::Ordering::SeqCst); *object.features.lock().expect("the features") = json!(["mail_all"]); let handle = phone_in(&dir, messages()); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); let path = handle.client().layout().replica(DATABASE); assert_eq!(cotton_client::transport::object::account_features(&path), ["mail_all"], "the copy keeps the account's switch"); let mark = cotton_client::transport::object::copy_kit(&path); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); detach_for_update(&handle); drop(handle); let handle = phone_in(&dir, messages()); handle.client().set_runtime(None); handle.client().set_after_pass(Arc::new(|| {})); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); call_with(&handle, "personal.connect", &books_ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("the next launch"); object.asked.lock().expect("the pages asked").clear(); handle.client().sync_now().expect("a pass"); assert_eq!(cotton_client::transport::object::copy_kit(&path), mark, "the mark is unchanged: no mail table to keep whole"); let asked = object.asked.lock().expect("the pages asked").clone(); assert!(!asked.iter().any(|path| path.contains("since=0&") || path.contains("again=") || path.contains("email")), "nothing pulled again, no mail asked: {asked:?}"); drop(handle);}/// The record a first fill keeps of the tables it left for the next pass (`object.passed`), as a copy whose first/// pull ended before its late tables came holds it.fn owe_after_first_fill(handle: &CottonHandle, tables: &[&str]) { let replica = handle.client().layout().replica(DATABASE); let record = format!("h0000.000000:~first-fill,{}", tables.join(",")); rusqlite::Connection::open(&replica) .expect("the copy") .execute("INSERT INTO _cursors (author_device_id, hlc_seen, updated_at) VALUES (?1, ?2, '2026-11-26T10:00:00.000Z') ON CONFLICT (author_device_id) DO UPDATE SET hlc_seen = excluded.hlc_seen", rusqlite::params![cotton_client::transport::object::PASSED_KEY, record]) .expect("the record written");}/// RULE (FIRST SYNC STATES, coordinator 26 Nov 2026: Post said "No mail here yet. Add an account" and "0 mails" while/// 280,000 rows were still coming): while a copy's first pull runs, every app's home, list and count answers say its/// things are coming (`firstSync`, with Account's count in `seen`), never empty or zero, and a table whose definition/// has not come is `not_here_yet`; once the pull ends and the first fill owes nothing, they say their own words.#[test]fn every_home_says_its_things_are_coming_while_the_first_pull_runs() { let (_dir, handle) = phone_for_update(); let object = the_garden(); *object.sync_fails.lock().expect("the sync's status") = Some(500); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected: the copy is made before any page"); let call = |method: &str, request: serde_json::Value| crate::methods::dispatch(&handle, method, &request); let loading = "Loading your data…"; let home = call("mail.home", json!({})).expect("mail.home"); assert_eq!((home["empty"].clone(), home["firstSync"]["state"].clone()), (json!(loading), json!("bringing")), "{home}"); assert!(home["firstSync"]["seen"]["state"].is_string(), "Account's count rides beside: {home}"); let you = call("mail.you", json!({})).expect("mail.you"); assert_eq!(you["card"]["count"], you["firstSync"]["seen"]["line"], "never 0 mails: the count Account says ({you})"); assert!(!you.to_string().contains("0 mails"), "{you}"); for (method, request, path) in [ ("mail.list", json!({}), vec!["empty"]), ("mail.senders", json!({}), vec!["empty"]), ("mail.files", json!({}), vec!["empty"]), ("mail.accounts", json!({}), vec!["empty"]), ("vault.items", json!({}), vec!["empty", "title"]), ("secrets.people", json!({}), vec!["empty", "title"]), ("shell.today", json!({}), vec!["empty"]), ("data.lately", json!({}), vec!["empty"]), ] { let answer = call(method, request).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message)); let said = path.iter().fold(&answer, |slot, key| &slot[*key]); assert_eq!(said, loading, "{method} says its things are coming: {answer}"); assert_eq!(answer["firstSync"]["state"], "bringing", "{method}"); } let notes = call("notes.list", json!({"view": "all"})).expect("notes.list"); assert_eq!((notes["empty"].clone(), notes["count_words"].clone()), (json!(loading), notes["firstSync"]["seen"]["line"].clone()), "never 0 notes: {notes}"); for method in ["mail.side", "notes.fan", "chat.list", "cinemas.home", "cinemas.you", "data.tables", "groups.list", "shell.fan"] { let answer = call(method, json!({})).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message)); assert_eq!(answer["firstSync"]["state"], "bringing", "{method}: {answer}"); } for method in ["notes.side", "story.list", "health.people", "health.reports"] { if let Err(refused) = call(method, json!({})) { assert_eq!(refused.code, crate::phone::copy_standing::NOT_HERE_YET, "{method}: {}", refused.message); assert_eq!(refused.message, loading, "{method}"); } } *object.sync_fails.lock().expect("the sync's status") = None; handle.client().sync_now().expect("the first pull ends"); let home = call("mail.home", json!({})).expect("mail.home"); assert!(home["firstSync"].is_null(), "over: {home}"); assert_eq!(home["empty"], "No mail here yet. Add an account to bring it in.", "a whole copy with no mail says so"); let notes = call("notes.list", json!({"view": "all"})).expect("notes.list"); assert!(notes["firstSync"].is_null(), "{notes}");}/// RULE (FIRST SYNC STATES): a copy whose first pull has ended while its first fill still owes Post's mail tables (a/// kit's late tables come in the pass after) is still in Post's first sync: its homes say the mail is coming. Owing/// only the pictures keeps no list loading, and once a pass has carried what it left, Post's homes say their own words.#[test]fn post_says_its_mail_is_coming_while_its_late_tables_are_owed() { let (_dir, handle) = phone_for_update(); let object = the_garden(); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("the first pull ends"); let call = |method: &str| crate::methods::dispatch(&handle, method, &json!({})).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message)); assert!(call("mail.home")["firstSync"].is_null()); owe_after_first_fill(&handle, &["email", "email_thread", "media"]); let home = call("mail.home"); assert_eq!((home["empty"].clone(), home["firstSync"]["state"].clone()), (json!("Loading your data…"), json!("bringing")), "{home}"); let you = call("mail.you"); assert_eq!(you["card"]["count"], you["firstSync"]["seen"]["line"], "{you}"); assert!(!you.to_string().contains("0 mails"), "{you}"); // Accounts and Domains are not "None yet" while his mail is coming (launch-ios, the owner's find 2), and Sync says // the one line every app says (find 3). The first sync is said once, on the card: the rows carry a dash, never the // sentence, and Storage is titled Storage (the owner, 26 Nov 2026). let row = |you: &serde_json::Value, id: &str| you["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap().iter()).find(|r| r["id"] == id).cloned().unwrap(); assert_eq!(row(&you, "accounts")["value"], "—", "{you}"); assert_eq!(row(&you, "domains")["value"], "—", "{you}"); assert_eq!(row(&you, "storage")["title"], "Storage", "{you}"); assert!(!you["groups"].to_string().contains("Loading your data"), "never on a row: {you}"); assert_eq!(row(&you, "sync")["value"], you["firstSync"]["seen"]["line"], "{you}"); assert_eq!(call("mail.domains")["empty"], "Loading your data…"); // Mail on screen while the first sync goes on: the rows fill from what the phone holds. let workspace = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(serde_json::json!(ctx.workspace_id))).unwrap(); handle .client() .with_writer(|file| { let ws = [rusqlite::types::Value::Text(workspace.as_str().unwrap().to_string())]; file.driver .run("INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) VALUES ('et-held', ?, 'key-held', 'Held', '2026-11-26T10:00:00.000Z', '2026-11-26T10:00:00.000Z', 1, '2026-11-26T10:00:00.000Z', '2026-11-26T10:00:00.000Z')", &ws) .map_err(|e| format!("thread: {e}"))?; file.driver .run( "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, from_name, recipients, sent_at, body, snippet, attachments, unread, account, in_inbox, created_at) VALUES ('e-held', ?, 'et-held', 'x-held', 'Held', 'asha@invented.example', 'Asha', '[]', '2026-11-26T10:00:00.000Z', 'Held.', 'Held.', '[]', 0, 'mira@invented.example', 1, '2026-11-26T10:00:00.000Z')", &ws, ) .map(|_| ()) .map_err(|e| format!("mail: {e}")) }) .expect("a mail here"); let you = call("mail.you"); assert_eq!(you["card"]["count"], "1 mail", "{you}"); assert_eq!(row(&you, "accounts")["value"], "mira@invented.example", "{you}"); assert_eq!(row(&you, "domains")["value"], "—", "no account row yet: its domains are not known, never \"None\" ({you})"); assert_eq!(row(&you, "storage")["title"], "1 mail", "{you}"); handle.client().with_writer(|file| file.driver.run("DELETE FROM cotton_emails WHERE id = 'e-held'", &[]).and_then(|_| file.driver.run("DELETE FROM cotton_email_threads WHERE id = 'et-held'", &[])).map(|_| ()).map_err(|e| e.to_string())).expect("gone"); owe_after_first_fill(&handle, &["media"]); assert!(call("mail.home")["firstSync"].is_null(), "only the pictures owed"); // His mail has come: a real zero says its own words, and a none is a none. let you = call("mail.you"); assert_eq!(you["card"]["count"], "No mail yet", "{you}"); assert_eq!(row(&you, "accounts")["value"], "None yet", "{you}"); assert!(notes_list(&handle)["firstSync"].is_null(), "the pictures keep no list loading");}// ── RESTORE 2: the server put back to an earlier time ─────────────────────────────────────────────────────────────const G1: &str = "AAAAAAAAAAAAAAAAAAAAAA";const G2: &str = "BBBBBBBBBBBBBBBBBBBBBB";const RESTORED_TO: &str = "2026-11-20T08:00:00.000Z";fn generation_held(handle: &CottonHandle) -> Option<String> { let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); copy.query_row("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?1", [cotton_client::transport::object::GENERATION_KEY], |row| row.get(0)).ok()}/// A change this copy holds that never went (bytes no build reads: it stays whatever happens).fn unsent_change(handle: &CottonHandle) { let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); copy.execute_batch( "INSERT INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, sig) \ VALUES ('before-the-restore', 'change', 'synthetic-author', 'cotton_garden_bed', 'bed-invented', '0000000000001:0000:x', 1, '2026-11-21T09:00:00.000Z', X'00FF', NULL)", ) .expect("an unsent change");}/// RULE (RESTORE 2, phone 2 to 5): a pass that meets a new generation folds nothing of it and the copy is set aside/// through the one function, marked as from before the restore with its unsent change listed (never sent), and made/// again from the server; the Sync page says one plain line while it is, its first sync asks from nothing and holds/// the new generation, and the line goes once it has caught up.#[test]fn a_server_put_back_sets_the_copy_aside_and_makes_it_again_from_nothing() { let (_dir, handle) = phone_for_update(); let object = the_garden(); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); *object.generation.lock().expect("the generation") = Some(G1.into()); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass under G1"); assert_eq!(generation_held(&handle), Some(format!("g{G1}"))); mark(&handle, "invented_marker"); unsent_change(&handle); // The server is put back. *object.generation.lock().expect("the generation") = Some(G2.into()); *object.restored_to.lock().expect("the restored time") = Some(RESTORED_TO.into()); let asked_before = object.asked.lock().expect("the pages asked").len(); assert!(handle.client().sync_now().is_err(), "the pass stops on the new generation"); made_again(&handle); assert!(!marked(&handle, "invented_marker"), "the copy is a new file"); let layout = handle.client().layout().clone(); let kept = cotton_client::copy_keep::kept(&layout, Some(DATABASE)); assert_eq!(kept.len(), 1, "the copy is kept aside"); assert_eq!(kept[0].state.before_restore.as_deref(), Some(RESTORED_TO), "marked as from before the restore"); let listed = cotton_client::copy_keep::kept_changes(&layout, DATABASE); assert!(listed.iter().any(|change| change.op_id == "before-the-restore"), "its unsent change is listed: {listed:?}"); let said = crate::methods::shell_account::sync_said(&handle.client()); assert!(said["title"].as_str().is_some_and(|title| title.starts_with("Your Cotton was put back to how it was on ")), "one plain line: {said}"); handle.client().sync_now().expect("the new copy's first sync"); let asked = object.asked.lock().expect("the pages asked").clone(); let first = asked[asked_before..].iter().filter(|path| path.starts_with("/v1/sync")).nth(1).expect("the new copy's first page"); assert!(first.starts_with("/v1/sync?since=0"), "the new copy asks from nothing: {:?}", &asked[asked_before..]); assert_eq!(generation_held(&handle), Some(format!("g{G2}")), "it holds the new generation"); let said = crate::methods::shell_account::sync_said(&handle.client()); assert!(!said["title"].as_str().unwrap_or_default().contains("put back"), "the line goes once it has caught up: {said}"); assert!(cotton_client::copy_keep::kept_changes(&layout, DATABASE).iter().any(|change| change.op_id == "before-the-restore"), "still listed, never sent"); assert!(!asked.iter().any(|path| path.starts_with("refused")), "nothing was posted against the old generation");}/// RULE (RESTORE 2): a post refused `generation_moved` does the same: the change stays in the copy set aside, listed,/// and the copy is made again.#[test]fn a_post_refused_generation_moved_sets_the_copy_aside_and_makes_it_again() { let (_dir, handle) = phone_for_update(); let object = the_garden(); object.names_device.store(true, std::sync::atomic::Ordering::SeqCst); // Its pages say now, so a write made now goes out. object.serves_now.store(true, std::sync::atomic::Ordering::SeqCst); *object.generation.lock().expect("the generation") = Some(G1.into()); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass under G1"); mark(&handle, "invented_marker"); // A write the server refuses as made against another generation (its pages still say none moved). *object.generation.lock().expect("the generation") = Some(G2.into()); crate::methods::dispatch(&handle, "records.create", &json!({"table": "garden_bed", "data": {"label": "An invented bed"}})).expect("a write here"); assert!(handle.client().sync_now().is_err(), "the pass stops on the refused post"); made_again(&handle); assert!(!marked(&handle, "invented_marker"), "the copy is a new file"); let layout = handle.client().layout().clone(); let kept = cotton_client::copy_keep::kept(&layout, Some(DATABASE)); assert_eq!(kept.len(), 1, "the copy holding the write is kept aside"); assert!(kept[0].state.before_restore.is_some(), "marked as from before the restore"); assert!(!cotton_client::copy_keep::kept_changes(&layout, DATABASE).is_empty(), "the write is listed"); assert!(object.asked.lock().expect("the pages asked").iter().any(|path| path.starts_with("refused /v1/act")), "the post was refused: {:?} {:?}", object.asked.lock().unwrap(), object.taken.lock().unwrap());}/// RULE (RESTORE 2): an account held still is retried quietly: a change waits queued, nothing is parked, the copy is/// never made again, and the Sync page says one plain line until the account answers.#[test]fn an_account_held_still_waits_quietly_with_one_plain_line() { let (_dir, handle) = phone_for_update(); let object = the_garden(); object.serves_now.store(true, std::sync::atomic::Ordering::SeqCst); *object.generation.lock().expect("the generation") = Some(G1.into()); call_with(&handle, "personal.connect", &ask(), Arc::clone(&object) as Arc<dyn Exchange>).expect("connected"); handle.client().sync_now().expect("a pass"); mark(&handle, "invented_marker"); object.frozen.store(true, std::sync::atomic::Ordering::SeqCst); crate::methods::dispatch(&handle, "records.create", &json!({"table": "garden_bed", "data": {"label": "An invented bed"}})).expect("a write here"); for _ in 0..4 { assert!(handle.client().sync_now().is_err(), "the pass waits"); } let said = crate::methods::shell_account::sync_said(&handle.client()); assert_eq!(said["title"], "Cotton is paused for a moment · your changes will sync by themselves", "{said}"); let copy = rusqlite::Connection::open(handle.client().layout().replica(DATABASE)).expect("the copy"); let parked: i64 = copy.query_row("SELECT COUNT(*) FROM _parked", [], |row| row.get(0)).expect("a count"); assert_eq!(parked, 0, "nothing parked"); std::thread::sleep(std::time::Duration::from_millis(200)); assert!(marked(&handle, "invented_marker"), "the copy is never made again for it"); object.frozen.store(false, std::sync::atomic::Ordering::SeqCst); handle.client().sync_now().expect("it answers again"); let said = crate::methods::shell_account::sync_said(&handle.client()); assert_ne!(said["title"], "Cotton is paused for a moment · your changes will sync by themselves", "the line goes");}