//! What a device holds after it starts a database on its own. use super::*; use crate::connection::read_connection; use crate::seams::{FixedClock, SeededRandom}; use chrono::{DateTime, Utc}; use cotton_store::driver::Driver; const DEVICE_KEY: &str = "Zm9yLXRlc3RzLW9ubHktbm90LWEtcmVhbC1rZXktMDAwMDAw"; fn at(instant: &str) -> FixedClock { FixedClock::new( DateTime::parse_from_rfc3339(instant) .expect("a literal instant") .with_timezone(&Utc), ) } fn a_layout(root: &tempfile::TempDir) -> Layout { Layout::new(root.path().join("CottonDB")) } fn started(layout: &Layout, name: Option<&str>) -> Result { let clock = at("2026-09-18T09:00:00.000Z"); let random = SeededRandom::new(7); start_local(StartLocal { layout, clock: &clock, random: &random, name, device_key_id: Some(DEVICE_KEY), device_name: "Asha's iPhone", platform: DevicePlatform::Ios, app_version: Some("1.0.0"), receipt_signer: cotton_store::signed::SignerSlot::default(), }) } fn count(db: &Driver, sql: &str) -> i64 { db.get(sql, &[]) .expect("a count") .and_then(|row| row.int("n")) .unwrap_or(0) } #[test] fn a_started_device_holds_a_replica_at_the_ordinary_client_address() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let started = started(&layout, Some("Home")).expect("a start"); assert_eq!(started.replica, layout.replica(&started.workspace_id)); assert!(started.replica.exists()); let db = Driver::open(&started.replica).expect("the replica"); let row = db .get("SELECT id, name FROM cotton_workspaces", &[]) .expect("a read") .expect("the workspace row"); assert_eq!(row.text("id"), Some(started.workspace_id.as_str())); assert_eq!(row.text("name"), Some("Home")); // The default calendar, or the first event has nowhere to go. assert_eq!( count( &db, "SELECT COUNT(*) AS n FROM cotton_collections WHERE kind = 'calendar'" ), 1 ); } #[test] fn the_connection_record_says_there_is_no_server_yet_and_names_the_workspace() { // `paired` — the boot gate's first question — is "does the record name a // workspace", so this is what makes the app open on the file instead of on // the Join screen. let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let started = started(&layout, None).expect("a start"); let stored = read_connection(&layout.connection_json()) .expect("a read") .expect("a record"); assert_eq!(stored.mode, ConnectionMode::Local); assert_eq!(stored.workspace_id.as_deref(), Some(started.workspace_id.as_str())); assert_eq!(stored.owner_id.as_deref(), Some(started.owner_id.as_str())); assert_eq!(stored.base_url, ""); assert!(!stored.mode.has_server()); } #[test] fn no_request_can_go_out_because_the_address_seam_answers_nothing() { use crate::transport::ServerAddress; let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); started(&layout, None).expect("a start"); let connection = ConnectionFile::at(layout.connection_json()); assert_eq!(connection.base_url(), None); } #[test] fn this_device_is_its_own_first_device_row_approved_by_nobody() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let started = started(&layout, None).expect("a start"); let db = Driver::open(&started.replica).expect("the replica"); let devices = cotton_tools::devices::FileDevices::new(&db) .list(&started.workspace_id) .expect("the device list"); assert_eq!(devices.len(), 1); assert_eq!(devices[0].device_id, DEVICE_KEY); assert_eq!(devices[0].name, "Asha's iPhone"); assert_eq!(devices[0].approved_by, SELF_APPROVER); assert!(devices[0].revoked_at.is_none()); } #[test] fn the_device_row_replicates_rather_than_sitting_in_this_file_alone() { // An unstamped row belongs to the `origin` author and reaches another // device only inside a whole-file copy — so a Mac adopting this phone's // database would adopt a device list with nothing in it. let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let started = started(&layout, None).expect("a start"); let db = Driver::open(&started.replica).expect("the replica"); assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_devices WHERE _hlc = ''"), 0 ); } #[test] fn a_device_with_no_key_yet_still_gets_a_database_and_no_invented_row() { // A device row keyed by anything but the real key is a row no server will // ever match, so a missing key writes none at all. let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let clock = at("2026-09-18T09:00:00.000Z"); let random = SeededRandom::new(7); let started = start_local(StartLocal { layout: &layout, clock: &clock, random: &random, name: None, device_key_id: None, device_name: "Asha's iPhone", platform: DevicePlatform::Ios, app_version: None, receipt_signer: cotton_store::signed::SignerSlot::default(), }) .expect("a start"); assert_eq!(started.device_id, None); let db = Driver::open(&started.replica).expect("the replica"); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_devices"), 0); } #[test] fn a_device_that_already_holds_a_database_is_refused_and_nothing_is_touched() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let first = started(&layout, None).expect("a start"); let again = started(&layout, None).expect_err("a refusal"); assert_eq!(again.code(), "already_started"); assert!(first.replica.exists()); let stored = read_connection(&layout.connection_json()) .expect("a read") .expect("a record"); assert_eq!(stored.workspace_id.as_deref(), Some(first.workspace_id.as_str())); } #[test] fn a_replica_with_no_connection_record_is_a_life_too_and_stops_a_second_start() { // A start interrupted between the file and the record. The file is a // person's writes; a second start over it would leave them where nothing // looks. let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let first = started(&layout, None).expect("a start"); std::fs::remove_file(layout.connection_json()).expect("the record"); let again = started(&layout, None).expect_err("a refusal"); assert_eq!(again.code(), "already_started"); assert!(first.replica.exists()); } #[test] fn a_name_longer_than_the_server_would_take_is_refused_before_anything_is_made() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let refused = started(&layout, Some(&"n".repeat(DATABASE_NAME_MAX + 1))) .expect_err("a refusal"); assert_eq!(refused.code(), "bad_request"); assert!(!layout.connection_json().exists()); assert!(!layout.client_dir().join("nothing").exists()); } #[test] fn two_starts_on_two_devices_mint_two_different_workspaces() { // The ids are MINTED, never derived: two phones started in the same second // must not collide, or the recovery merge would fold two unrelated lives. let one = tempfile::tempdir().expect("a temp dir"); let two = tempfile::tempdir().expect("a temp dir"); let left = start_local(StartLocal { layout: &a_layout(&one), clock: &at("2026-09-18T09:00:00.000Z"), random: &SeededRandom::new(1), name: None, device_key_id: Some(DEVICE_KEY), device_name: "one", platform: DevicePlatform::Ios, app_version: None, receipt_signer: cotton_store::signed::SignerSlot::default(), }) .expect("a start"); let right = start_local(StartLocal { layout: &a_layout(&two), clock: &at("2026-09-18T09:00:00.000Z"), random: &SeededRandom::new(2), name: None, device_key_id: Some(DEVICE_KEY), device_name: "two", platform: DevicePlatform::Ios, app_version: None, receipt_signer: cotton_store::signed::SignerSlot::default(), }) .expect("a start"); assert_ne!(left.workspace_id, right.workspace_id); } // ── a database made beside the personal one ──────────────────────────────── const MINE: &str = "6b1f2a3c-4d5e-4f60-8a71-b2c3d4e5f607"; fn made(layout: &Layout, name: &str) -> Result { let connection = ConnectionFile::at(layout.connection_json()); start_place(StartPlace { layout, connection: &connection, clock: &at("2026-10-04T09:00:00.000Z"), random: &SeededRandom::new(11), name, receipt_signer: cotton_store::signed::SignerSlot::default(), device_key_id: Some(DEVICE_KEY), device_name: "Asha's iPhone", platform: DevicePlatform::Ios, app_version: Some("1.0.0"), }) } /// Every replica file under the client folder — what a refusal must not leave. fn replicas(layout: &Layout) -> Vec { let Ok(entries) = std::fs::read_dir(layout.client_dir()) else { return Vec::new(); }; entries .filter_map(Result::ok) .map(|entry| entry.path().join("replica.db")) .filter(|path| path.exists()) .collect() } // RULE: A database made on a device with no network is a whole replica at once — a shared workspace row under its name, its first rows queued for the server — and the record holds it as a pending place. It is made with the shell only: no tool is written at creation (owner, 21 Oct 2026); each is added by hand. #[test] fn a_database_is_made_on_this_device_with_no_network() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); crate::test_support::write_record(&layout, MINE, ConnectionMode::Remote, &[]); let made = made(&layout, "Garden").expect("a database"); assert_ne!(made.id, MINE); assert_eq!(made.name, "Garden"); assert_eq!(made.replica, layout.replica(&made.id)); let db = Driver::open(&made.replica).expect("the replica"); let row = db .get("SELECT id, name, kind FROM cotton_workspaces", &[]) .expect("a read") .expect("the workspace row"); assert_eq!(row.text("id"), Some(made.id.as_str())); assert_eq!(row.text("name"), Some("Garden")); assert_eq!(row.text("kind"), Some("shared")); // A replica: its first rows wait in the outbox for the server. assert!(cotton_store::outbox::pending_count(&db).expect("the outbox") > 0); assert_eq!( count( &db, "SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_workspaces'" ), 1 ); let record = ConnectionFile::at(layout.connection_json()) .read_record() .expect("a record"); assert_eq!(record.mine.workspace_id.as_deref(), Some(MINE)); let place = record .places .iter() .find(|place| place.id == made.id) .expect("the place"); assert!(place.pending); assert!(place.available); assert_eq!(place.name.as_deref(), Some("Garden")); assert_eq!(place.toolkit, None); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_tool_definitions"), 0, "no tool is written at creation"); let tables: Vec = db.all("SELECT id FROM cotton_table_definitions ORDER BY id", &[]).unwrap().iter().map(|row| row.text("id").unwrap().to_string()).collect(); let mut shell: Vec = cotton_tools::presentation::SHELL_TABLES.map(str::to_string).to_vec(); shell.sort(); assert_eq!(tables, shell, "the shell's tables only"); } #[test] fn a_database_that_cannot_be_made_here_is_refused_and_leaves_nothing() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); // No personal database to make one beside. let refused = made(&layout, "Garden").expect_err("a refusal"); assert!(matches!(refused, StartLocalError::NoPersonal), "{refused:?}"); assert!(replicas(&layout).is_empty()); crate::test_support::write_record(&layout, MINE, ConnectionMode::Remote, &[]); for name in ["Personal", "personal", " PERSONAL "] { let refused = made(&layout, name).expect_err("a refusal"); assert!(matches!(refused, StartLocalError::ReservedName), "{name}: {refused:?}"); } let refused = made(&layout, " ").expect_err("a refusal"); assert!(matches!(refused, StartLocalError::BadName), "{refused:?}"); assert!(replicas(&layout).is_empty()); let record = ConnectionFile::at(layout.connection_json()) .read_record() .expect("a record"); assert!(record.places.is_empty()); } // RULE: genesis none refuses every Personal start before writing a file; a business install must wait for a join. #[test] fn genesis_none_never_founds_personal() { let root = tempfile::tempdir().unwrap(); let layout = a_layout(&root); cotton_core::genesis::Genesis::None.keep(layout.root()).unwrap(); let error = started(&layout, None).unwrap_err(); assert_eq!(error.code(), "no_personal_database_in_flavour"); assert_eq!(error.to_string(), "No personal database in this flavour."); assert!(held_workspaces(&layout, "").is_empty()); assert!(!layout.connection_json().exists()); assert!(!layout.files_dir().exists()); } // RULE: a database this device founds is born with its app's genesis set — // every package the manifest's `tools` names, installed as ordinary tool rows // through the import path, and nothing written for a compiled built-in — so a // fresh Rigby or Cotton opens on a fan with its tools rather than Home and // Tools alone (architect, 22 Oct 2026). A place made later gets the same set. #[test] fn a_founded_database_is_born_with_its_apps_genesis_tools() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); cotton_core::genesis::GenesisTools::checked(["people", "todos", "notebook", "calls"].map(str::to_string).to_vec()) .expect("a genesis set") .keep(layout.root()) .expect("kept"); let tools = |path: &std::path::Path| -> Vec { let db = Driver::open(path).expect("the replica"); db.all("SELECT id FROM cotton_tool_definitions ORDER BY id", &[]) .expect("a read") .iter() .map(|row| row.text("id").expect("an id").to_string()) .collect() }; let mine = started(&layout, None).expect("a database"); assert_eq!(tools(&mine.replica), ["notebook", "people", "todos"], "the packages, and no row for a built-in"); let place = made(&layout, "Garden").expect("a place"); assert_eq!(tools(&place.replica), ["notebook", "people", "todos"]); } /// Every shell definition row a file holds — Home's board, the themes and the /// shell's tables — by table and id, as written. fn shell_rows(db: &Driver) -> std::collections::BTreeMap<(String, String), String> { let mut rows = std::collections::BTreeMap::new(); for table in [ cotton_tools::presentation::BOARD_DEFINITIONS, cotton_tools::presentation::THEME_DEFINITIONS, cotton_tools::definitions::TABLE_DEFINITIONS, ] { for row in db.all(&format!("SELECT id, definition FROM {table} ORDER BY id"), &[]).expect("the shell reads") { let id = row.text("id").expect("an id").to_string(); if table == cotton_tools::definitions::TABLE_DEFINITIONS && !cotton_tools::presentation::SHELL_TABLES.contains(&id.as_str()) { continue; } rows.insert((table.to_string(), id), row.text("definition").expect("a definition").to_string()); } } rows } /// RULE: a database founded on the phone (`start_local`: Rigby's first open, Cotton's "Start new") carries the shell — Home's board, the themes and the shell's tables — and Home's board names the picture its tile prints before anyone is chosen as you. Without it the phone's Home tile was a blank cream square (homepicture lane, 22 Oct 2026). #[test] fn a_phone_founded_database_carries_the_shell() { let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); let phone_started = started(&layout, None).expect("the phone starts a database"); let phone = Driver::open(&phone_started.replica).expect("the phone's file opens"); // The cap's colour is assigned from the database's own id (`assign_caps`). let cap = (cotton_tools::presentation::THEME_DEFINITIONS.to_string(), "database".to_string()); let mut phone_shell = shell_rows(&phone); assert!(phone_shell.remove(&cap).is_some(), "the database holds its cap"); assert!(!phone_shell.is_empty(), "the phone's database holds a shell"); let home: serde_json::Value = serde_json::from_str( &phone_shell[&(cotton_tools::presentation::BOARD_DEFINITIONS.to_string(), "home".to_string())], ) .expect("Home's board reads"); assert!( home["picture"].as_str().is_some_and(|picture| !picture.is_empty()), "Home's board names the picture its tile prints: {home}" ); } /// Cotton's own manifest, as the bundle carries it. fn cottons_manifest() -> serde_json::Value { serde_json::from_str(include_str!("../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest reads") } /// RULE: Cotton opens and works before anyone signs in (owner, 1 Nov 2026): its manifest founds Personal beside the server it backs up to, and names no first-open choice (6 Nov 2026), so a fresh install founds its own Personal database on the phone exactly as Rigby's does, with no network. #[test] fn cottons_manifest_starts_its_own_database_on_the_phone() { let manifest = cottons_manifest(); assert_eq!(manifest["genesis"], "personal", "Cotton founds its own database"); assert!(manifest.get("first_open").is_none(), "and asks nothing on first open"); assert!(manifest["business"]["server"].is_object(), "and still names the server Backup signs in at"); let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); cotton_core::genesis::Genesis::of(Some(&manifest)).expect("a genesis").keep(layout.root()).expect("kept"); cotton_core::genesis::GenesisTools::of(Some(&manifest)).expect("Cotton's tools read").keep(layout.root()).expect("kept"); let mine = started(&layout, None).expect("Cotton starts locally"); let stored = read_connection(&layout.connection_json()).expect("a record").expect("present"); assert_eq!(stored.mode, ConnectionMode::Local, "no server until Backup"); assert!(stored.base_url.is_empty()); assert!(mine.replica.exists()); } /// RULE: the first paint of a local Cotton is whole — the genesis set its manifest names holds every tool the personal kit ships (the set every served object is given, `apps/business/src/kit_keep.ts`), so Books, Films, Music, Money, Memories and Machines are on the fan before backup as after it. Story is Cotton Story's (its own kit `story`), served to every object for an assistant but not on Cotton's own fan (17 Nov 2026); Meetings the same, Cotton Meetings' (its own kit `meetings`, c2a5f59e6, 17 Nov 2026). #[test] fn cottons_genesis_set_is_the_whole_personal_kit() { let manifest = cottons_manifest(); let genesis = cotton_core::genesis::GenesisTools::of(Some(&manifest)).expect("Cotton's tools read"); let mut packages: Vec<&str> = genesis.packages(); packages.sort_unstable(); let mut kit: Vec<&str> = cotton_core::kit::ids().into_iter().filter(|id| !["story", "meetings"].contains(id)).collect(); kit.sort_unstable(); assert_eq!(packages, kit, "Cotton's genesis packages are the personal kit's tools"); let root = tempfile::tempdir().expect("a temp dir"); let layout = a_layout(&root); genesis.keep(layout.root()).expect("kept"); let mine = started(&layout, None).expect("a database"); let db = Driver::open(&mine.replica).expect("the replica"); let installed: Vec = db .all("SELECT id FROM cotton_tool_definitions ORDER BY id", &[]) .expect("a read") .iter() .map(|row| row.text("id").expect("an id").to_string()) .collect(); assert_eq!(installed, kit, "every kit tool is installed at the start"); } #[test] fn a_fresh_local_start_is_stamped_and_its_first_keep_mints_nothing() { let root = tempfile::tempdir().unwrap(); let layout = a_layout(&root); let made = started(&layout, None).unwrap(); let db = Driver::open(&made.replica).unwrap(); let before = count(&db, "SELECT count(*) AS n FROM _writes"); let stamp = db.get("SELECT value FROM _kit_keep WHERE key = 'kit_version'", &[]).unwrap().unwrap(); let tools = cotton_core::genesis::GenesisTools::at(layout.root()).unwrap(); assert_eq!(cotton_tools::kit_keep::keep(&db, Utc::now(), Arc::new(cotton_tools::random::SystemRandom), &tools).unwrap(), 0); assert_eq!(count(&db, "SELECT count(*) AS n FROM _writes"), before); assert_eq!(db.get("SELECT value FROM _kit_keep WHERE key = 'kit_version'", &[]).unwrap().unwrap().text("value"), stamp.text("value")); } /// RULE: a phone's own database that an earlier build founded (Rigby 10's definitions, as that build wrote them) is kept at this kit and then takes every column its kept definitions add to an engine's table — the attach of a local database never stops on a column it cannot hold. #[test] fn an_earlier_builds_local_definitions_are_kept_and_their_columns_held() { let root = tempfile::tempdir().unwrap(); let layout = a_layout(&root); let manifest: serde_json::Value = serde_json::from_str(include_str!("../../../apps/cotton/Tests/Fixtures/Flavours/rigby.json")).unwrap(); let tools = cotton_core::genesis::GenesisTools::of(Some(&manifest)).unwrap(); tools.keep(layout.root()).unwrap(); let made = started(&layout, None).unwrap(); let db = Driver::open(&made.replica).unwrap(); let fixture = cotton_store::manifest_dir().join("../cotton-tools/tests/fixtures/rigby-10-kit"); for kit in ["personal", "shell"] { for entry in std::fs::read_dir(fixture.join(kit).join("tables")).unwrap() { let text = std::fs::read_to_string(entry.unwrap().path()).unwrap(); let id = serde_json::from_str::(&text).unwrap()["id"].as_str().unwrap().to_string(); db.run( "UPDATE cotton_table_definitions SET definition = ? WHERE id = ?", &[rusqlite::types::Value::Text(text), rusqlite::types::Value::Text(id)], ) .unwrap(); } } db.run("DELETE FROM _kit_keep", &[]).unwrap(); assert!(cotton_tools::kit_keep::keep(&db, Utc::now(), Arc::new(cotton_tools::random::SystemRandom), &tools).unwrap() > 0); let definitions: Vec = db .all("SELECT definition FROM cotton_table_definitions", &[]) .unwrap() .iter() .map(|row| serde_json::from_str(row.text("definition").unwrap()).unwrap()) .collect(); let added = crate::transport::object::hold_defined_columns(&db, &definitions).expect("every kept column is held"); assert!(added.iter().any(|column| column == "cotton_events.kind"), "{added:?}"); assert!(crate::transport::object::hold_defined_columns(&db, &definitions).unwrap().is_empty(), "a second hold adds nothing"); }