//! What a device of the person's own writes, and how it is stamped. //! //! EVERY FIXTURE IS SYNTHETIC. The file here is a fresh workspace at the //! build's own schema version, with one //! row in it and nothing that resembles anybody. //! //! These run on BOTH builds on purpose: the Mac's window and the phone share //! this body, and a test that only ran on one of them would be a guard on half //! the callers. use super::*; use cotton_store::create::create_workspace; use cotton_store::driver::Driver; use cotton_store::meta::Meta; use rusqlite::types::Value as SqlValue; use serde_json::Map; const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111"; const OWNER: &str = "owner-synthetic"; const DEVICE: &str = "device:00000000000000000000000000"; /// THIS device's own key — what its row in `cotton_devices` is held under, /// and what the owner actor of every write here is resolved from. const KEY: &str = "synthetic-phone-key"; /// A clock that does not move, so the HLC and the `queued_at` are assertable. #[derive(Debug)] struct FixedClock; impl cotton_tools::clock::Clock for FixedClock { fn now(&self) -> chrono::DateTime { "2026-09-09T04:05:06Z".parse().expect("a fixed instant") } } /// Bytes from a counter, never the operating system's generator: a suite that /// cannot say which bytes were drawn can only assert the shape. #[derive(Debug)] struct SeededRandom(std::sync::Mutex); impl cotton_tools::random::Random for SeededRandom { fn fill(&self, out: &mut [u8]) { let mut next = self.0.lock().expect("the counter"); for byte in out.iter_mut() { *byte = *next; *next = next.wrapping_add(1); } } } fn seeded(path: &std::path::Path) -> Driver { let db = Driver::open(path).expect("a file opens"); create_workspace( &db, &Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: DEVICE.to_string(), last_server_seq: 0, last_hlc: None, }, ) .expect("a fresh file"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)", &[ SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text("Synthetic".to_string()), SqlValue::Text(OWNER.to_string()), SqlValue::Text("2026-09-01T00:00:00.000Z".to_string()), ], ) .expect("the workspace row"); // THIS DEVICE'S ROW, approved: a write at the screen is asked by the owner // at this device, and a key with no row in the file cannot author one. db.run( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \ approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)", &[ SqlValue::Text(device_row()), SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(KEY.to_string()), SqlValue::Text("A synthetic phone".to_string()), SqlValue::Text("2026-09-01T00:00:00.000Z".to_string()), SqlValue::Text("self".to_string()), SqlValue::Text("2026-09-01T00:00:00.000Z".to_string()), SqlValue::Text("2026-09-01T00:00:00.000Z".to_string()), ], ) .expect("this device's row"); db } /// The id of this device's row — the one approval of [`KEY`] in this file. fn device_row() -> String { cotton_tools::devices::approval_row_id(WORKSPACE, KEY, "2026-09-01T00:00:00.000Z") } /// The file's author, `_meta.author_id` — minted on its first write and the /// stamp of every op it mints after. fn file_author(db: &Driver) -> String { db.get("SELECT author_id FROM _meta", &[]) .expect("a read") .and_then(|row| row.text("author_id").map(str::to_string)) .expect("a file that has written holds its author") } fn input<'a>(clock: &'a FixedClock) -> WriteInput<'a> { WriteInput { workspace_id: WORKSPACE, identity: crate::fixture::identity(), owner_id: OWNER, device_id: DEVICE, device_key: Some(KEY), clock, random: Arc::new(SeededRandom(std::sync::Mutex::new(1))), vault: None, // A REPLICA: this module is how a device writes over the copy it // holds and into its outbox, and every test here is that path. held: Some(cotton_tools::rails::FileHeld::Replica), unserved: false, kit: None, tool_signer: None, } } /// One integer out of a one-row, one-column answer. fn count(db: &Driver, sql: &str) -> i64 { match db .all(sql, &[]) .expect("the query runs") .first() .and_then(|row| row.get("n").cloned()) .expect("a value") { SqlValue::Integer(n) => n, other => panic!("{sql} answered {other:?} rather than a count"), } } fn args(pairs: &[(&str, Value)]) -> Map { pairs .iter() .map(|(key, value)| ((*key).to_string(), value.clone())) .collect() } #[test] fn a_write_is_asked_by_the_owner_at_this_device_and_stamped_with_the_file_s_author() { // THE WHOLE OF THE DIFFERENCE from an assistant's write (design P3): the // write is asked by `Actor::Owner` of THIS DEVICE'S row, never a job or a // token, so a tap reads as the owner's own in their history. The op is // stamped with the FILE's author (`_meta.author_id`) like every op this // file mints — never `server:`, and never a role. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; let (created, ops) = run_tool( &db, "create_todo", &args(&[("title", json!("Water the plants"))]), &input(&clock), ) .expect("the todo is written"); let author = file_author(&db); assert!(author.starts_with("device:"), "the file's author is a device: {author}"); assert!(!ops.is_empty(), "a create mints at least one op"); for op in &ops { assert_eq!(op.device_id, author, "every op is stamped with the file's author"); } // An UPDATE too, not only a create: the version history that an update // writes is the row an assistant's write would be told apart by, and both // kinds of write have to carry the same stamp. let id = created["id"] .as_str() .expect("the new todo's id") .to_string(); let (_updated, updates) = run_tool( &db, "update_todo", &args(&[ ("id", json!(id)), ("title", json!("Water the plants tonight")), ]), &input(&clock), ) .expect("the todo is updated"); assert!(!updates.is_empty()); for op in &updates { assert_eq!(op.device_id, author); } // And the ACTOR: the owner, at the row this device's key holds. let mut asked_by = String::new(); run_with_ctx(&db, &input(&clock), &mut |ctx| { asked_by = ctx.writer().map_err(|failure| failure.to_string())?.actor().to_string(); Ok(Value::Null) }) .expect("a body that writes nothing"); assert_eq!(asked_by, format!("owner:{}", device_row())); } #[test] fn a_device_with_no_row_in_the_file_cannot_author_a_write_but_still_reads() { // A key with no live row — a device before its approval arrives, or one // with no identity at all — is REFUSED, never handed a job actor: a write // the file cannot attribute to one of the owner's devices is not the // owner's. Its reads still run. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; for key in [Some("a-key-nobody-approved"), None] { let mut stranger = input(&clock); stranger.device_key = key; let error = write_through_outbox( &db, "create_todo", &args(&[("title", json!("Not mine to write"))]), &stranger, ) .expect_err("a refusal"); assert_eq!(error, NO_DEVICE_ROW, "{key:?}"); let (listed, ops) = read_tool(&db, "list_todos", &Map::new(), &stranger) .expect("a read runs without a device row"); assert!(ops.is_empty()); assert!(listed.is_object(), "{listed}"); } assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM cotton_todos"), 0); assert_eq!(count(&db, "SELECT COUNT(*) AS n FROM _outbox"), 0); } #[test] fn a_write_leaves_no_audit_row_because_a_person_is_not_an_assistant() { // `cotton_mcp_audit` answers "what did an assistant do in my database", and // a person pressing a button is not an entry in it. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; run_tool( &db, "create_todo", &args(&[("title", json!("Book the tickets"))]), &input(&clock), ) .expect("the todo is written"); assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_mcp_audit"), 0, "nothing a device of the owner's writes is audited" ); } #[test] fn the_row_and_its_op_land_together_and_nothing_waits_on_a_server() { // A row folded into a replica with no op beside it is a write that can // never leave the device. The transaction is what stops that: the row and // the outbox entry are both there when the call returns — and the call // returns without a server having been asked anything, because there is // no server in this function's reach at all. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; let answer = write_through_outbox( &db, "create_todo", &args(&[("title", json!("Call the plumber"))]), &input(&clock), ) .expect("the write lands with nobody to push to"); assert_eq!(answer["rail"], json!("client")); assert!(answer["queued"].as_u64().expect("a count") >= 1); assert!( answer["answer"]["id"].is_string(), "the tool's own answer is NESTED, so a handler cannot shadow the outbox's words" ); assert!( count(&db, "SELECT COUNT(*) AS n FROM _outbox") >= 1, "the op is waiting for the loop rather than lost" ); } #[test] fn the_answer_names_the_tables_that_moved_so_a_screen_can_redraw() { // Design P5: the replica IS the cache, so invalidation is not an expiry — // it is this list. It comes from the ops the write MINTED, never from // re-reading `_ops`, which is the same rule the pull half holds and for the // same reason it had to be written down. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; let answer = write_through_outbox( &db, "create_todo", &args(&[("title", json!("Take the cat to the vet"))]), &input(&clock), ) .expect("the write lands"); let tables: Vec<&str> = answer["tables"] .as_array() .expect("a list of tables") .iter() .filter_map(Value::as_str) .collect(); assert!( tables.contains(&"cotton_todos"), "a created todo moved cotton_todos; got {tables:?}" ); } #[test] fn a_table_touched_twice_is_named_once() { let ops = [ ("cotton_todos", "a"), ("cotton_links", "b"), ("cotton_todos", "c"), ] .map(|(table, row)| { // A retract names no column, so the case needs no row's worth of them. let db = cotton_store::driver::Driver::open_in_memory().expect("opens"); cotton_store::migrate::migrate_store(&db).expect("migrates"); cotton_store::wire::op_of_change( &db, &cotton_store::mint::Change::retract(table, row), &format!("1700000000000:0000:{DEVICE}"), DEVICE, &cotton_store::actor::Actor::device_job( cotton_store::actor::JobName::named("test").expect("a job name"), ), row.to_string(), ) .expect("the receipt") }); assert_eq!( tables_touched(&ops), vec!["cotton_todos".to_string(), "cotton_links".to_string()], "once each, in the order they were written" ); } #[test] fn the_envelope_has_no_push_word_because_the_push_is_the_loops() { // `pushed` and `notPushed` were the envelope's words while a write ran its // own round trip under the replica lock. Whether the op has LEFT is the // sync loop's fact now (`SyncStatus::pending`), and a word here would be // one the write cannot truthfully fill — so there is none, and a screen // that once read "not pushed" off a write has nothing to read. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; let answer = write_through_outbox( &db, "create_todo", &args(&[("title", json!("Renew the passport"))]), &input(&clock), ) .expect("the write lands"); let mut words: Vec<&str> = answer .as_object() .expect("the envelope") .keys() .map(String::as_str) .collect(); words.sort_unstable(); // `rows` names the rows the write touched, for the data event (7d0b7ba3dd): no push word either. assert_eq!(words, vec!["answer", "queued", "rail", "rows", "tables"]); } #[test] fn a_tool_nobody_implements_is_refused_by_name_before_anything_is_written() { let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; let error = run_tool(&db, "levitate", &args(&[]), &input(&clock)).expect_err("a refusal"); assert!(error.contains("levitate"), "{error}"); } #[test] fn a_capability_a_device_cannot_supply_is_refused_out_loud() { // `documents`, `media`, `statements` and `meaning` are `None` in a device's // ToolServices (design P3). That is already every handler's contract; this // is the proof that a phone actually meets the refusing side of it rather // than half-working. let dir = tempfile::tempdir().expect("a temp dir"); let db = seeded(&dir.path().join("life.db")); let clock = FixedClock; let error = run_tool( &db, "request_document_upload", &args(&[ ("filename", json!("scan.pdf")), ("contentType", json!("application/pdf")), ("size", json!(1024)), ]), &input(&clock), ) .expect_err("a refusal, not a half-written row"); assert!( !error.is_empty(), "the refusal carries a sentence a screen can draw" ); assert_eq!( count(&db, "SELECT COUNT(*) AS n FROM cotton_documents"), 0, "a refused capability writes nothing" ); } // ── one answer shape, held by a sweep ─────────────────────────────────────── /// Every non-test source under `src/phone/` and `src/methods/`, as /// (path-ish name, text). /// /// The RUNTIME manifest directory, through the shared helper — never the /// compile-time constant, which a cached CI test binary carries from a checkout /// that has been deleted (`cotton_store::manifest`). fn method_sources() -> Vec<(String, String)> { let root = cotton_store::manifest::manifest_dir().join("src"); let mut out: Vec<(String, String)> = Vec::new(); for folder in ["phone", "methods"] { let before = out.len(); let dir = root.join(folder); let entries = std::fs::read_dir(&dir) .unwrap_or_else(|error| panic!("{} cannot be read ({error})", dir.display())); for entry in entries { let path = entry.expect("a directory entry").path(); let Some(name) = path.file_name().and_then(|name| name.to_str()) else { continue; }; // Test code by name, as cotton-store's raw-write guard reads it: `_tests.rs`, and a // `_bench.rs` measure a `_tests.rs` pulls in by path (shell_list_bench.rs writes its // synthetic rows with write_rows and answers nothing to any app). if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name.ends_with("_bench.rs") { continue; } let text = std::fs::read_to_string(&path) .unwrap_or_else(|error| panic!("{} cannot be read ({error})", path.display())); out.push((format!("{folder}/{name}"), text)); } // Refuse an empty sweep without pinning this module's file names or count. assert!(out.len() > before, "{} answered no sources", dir.display()); } out.sort(); out } /// RULE: A phone method lifts its own answer out of the write envelope so callers decode the declared shape rather than silently losing the saved result. /// /// [`own_answer`] states the rule and this is what holds it. A method that /// writes rows and hands the envelope straight back is not a compile error and /// not a red test anywhere else: the app decodes what it declared, gets a shape /// with none of its keys in it, and either throws or silently reads empty /// strings. Every one of those had shipped at once — `capture.avatar` threw, /// `capture.media` never linked a brand document, `settings.city` forgot the /// city it had just saved, `settings.voiceTerm` deleted a row it had just /// resolved to, and `meetings.create` made every meeting landing a route with /// no id (the walk of 15 Sep 2026). /// /// A FILE-level sweep, which is coarser than a call site and is what can be /// checked without parsing Rust: a source that writes rows must also lift the /// body's answer out. That is enough to catch the regression this exists for — /// a new method written beside the others, forgetting — and the exceptions /// below are each a written reason rather than a name on a list. #[test] fn every_method_that_writes_rows_answers_its_own_shape() { /// Sources that call `write_rows` and deliberately do NOT lift, each with /// the reason it does not. const LIFTS_ELSEWHERE: &[(&str, &str)] = &[ ( "phone/database_appearance.rs", "writes rows only in its test fixture (`appear`), the way MCP \ names a database: no method here writes, since the app never sets \ a database's name or look (owner, 16 Oct 2026).", ), ( "phone/settings_writes.rs", "all five settings writes share ONE call site, which lifts", ), ( "methods/keys.rs", "`keys.set` never hands the envelope on and never reads a field out of it either: the writer's answer is DISCARDED, and the hint is read back off the row so it cannot differ from what `keys.list` draws a moment later. There is nothing here to lift.", ), ( "methods/vault.rs", "the Mac's three lift by hand and RE-ANSWER: `vault.place` reads the body's id out and adds whether the file landed, `vault.unplace` answers `{id, removed}` of its own, and `vault.importDashlane` answers the importer's counts. None of the three hands an envelope on, and none of them can say so with this word.", ), ( "phone/joined_places.rs", "its two writes keep which places this person joined and answer \ nothing of the body's: each drops the envelope whole and hands \ back `()`, so there is no shape for the app to decode.", ), ( "phone/owner_face.rs", "it is no method: the sync pass carries Me's name and picture to \ the owner's person in each shared database and drops the envelope \ whole, answering only which databases it wrote, so there is no \ shape for the app to decode.", ), ( "phone/databases.rs", "`databases.create` writes the maker's person into the database it \ just made and drops that envelope whole: what it answers \ (`databaseId`, the name, the founding) is built from the made \ database, never from a write's body.", ), ( "phone/catalogue.rs", "`definitions.catalogue` files one Feedback note per definition it \ drew from the shipped copy and drops that envelope whole: what it \ answers is the resolved catalogue, never a write's body.", ), ( "phone/shell_player.rs", "its one write is a play's report (`write_listen`: the listen row, \ the song's and album's counts), whose envelope it drops whole and \ answers `()`: what `shell.player` answers is the queue it holds, \ built after the write, never a write's body.", ), ( "phone/person_key.rs", "its one write keeps this copy's person key (`person.keep`), whose \ envelope it drops whole: `ensure` answers `()` once the key is \ published, never a write's body.", ), ( "phone/sites.rs", "its writes keep the synced `site` table in step with the phone's \ own book (`step`: a put per site this phone holds newer, a removal kept \ as a row) and drop each envelope whole: what every `sites.*` method \ answers is built from the book, never a write's body.", ), ( "phone/health.rs", "`health.land` writes HealthKit's batch in chunks and drops each \ chunk's envelope whole: what it answers is the counts it put and \ removed and what it planned, never a write's body.", ), ( "phone/health_app.rs", "Cotton Health's writes (`apply`, the PDF's `keep_pdf`) drop each \ envelope whole: `apply` answers the ids of the rows it made and \ `keep_pdf` nothing, and each health.* method builds its own \ answer (an outcome and its toast, a person's id), never a \ write's body.", ), ( "phone/vault_carry.rs", "the vault carry writes each row it carries and drops the envelope whole: \ it answers its own counts (written, sealed again, linked, unopened), \ never a write's body.", ), ( "phone/contacts_io.rs", "`contacts.import` writes each card's note and drops the envelope whole: \ it answers its own counts (read, made, photos, notes, groups), never a \ write's body.", ), ( "methods/host_storage_floor.rs", "`host.setStorageFloor` drops each write's envelope whole and \ answers this Mac's floor read again after the write, with its undo.", ), ]; let mut swept = 0; for (name, text) in method_sources() { if !text.contains(".write_rows(") && !text.contains(".write_rows_with_vault(") { continue; } swept += 1; if LIFTS_ELSEWHERE.iter().any(|(named, _)| *named == name) { continue; } assert!( text.contains("own_answer") || text.contains("strip_envelope"), "{name} writes rows and never lifts the body's answer out of the envelope — see \ `authoring::own_answer`. The app decodes what a method ANSWERS, and `{{answer, \ rail, queued, …}}` carries none of the keys its shape declares." ); } assert!( swept > 0, "no sources were found to write rows; the answer-shape sweep is empty" ); } /// RULE: A device exports tool packages with its existing pairing key through the same authoring context; imported definitions and removal travel in its outbox. #[test] fn tool_packages_use_the_device_signer_and_the_authoring_outbox() { use base64::{engine::general_purpose::STANDARD, Engine}; use cotton_core::definitions::package::{decode_package, encode_unsigned_package, ToolPackage}; use cotton_core::definitions::{ builtin_table_definitions, ToolAuthor, ToolDefinition, ToolPicture, }; use cotton_tools::mcp::dispatch::ToolSigner; let dir = tempfile::tempdir().unwrap(); let db = seeded(&dir.path().join("packages.sqlite")); let mut table = builtin_table_definitions()[0].clone(); table.id = "synthetic_table".into(); table.builtin = false; // A link holding several records is an engine's to answer: a made table has none. table.columns.retain(|column| column.multiple != Some(true)); // …and so its page cannot place one (the todo page places its `people`). let kept: Vec = table.columns.iter().map(|c| c.key.clone()).collect(); for section in &mut table.page { if let Some(columns) = section.columns.as_mut() { columns.retain(|key| kept.contains(key)); } } table.engine = None; // A command runs an engine verb: a made table has none. table.commands = None; // …and so no mark drawn on its card binds one (todo's check is done). table.marks = None; // …and its page's parts name the commands and the `people` it no longer has. table.parts = None; // …and its storage is derived from its columns: a shipped table's SQL // declarations are the build's, never an imported package's. table.tables = None; let package = ToolPackage { board: None, tool: ToolDefinition { views: Vec::new(), id: "synthetic_tool".into(), name: "Synthetic tool".into(), purpose: None, picture: Some(ToolPicture::Asset("synthetic".into())), card_stock: None, fan_tile: None, tables: vec![table.id.clone()], search: Vec::new(), contributes: Vec::new(), instructions: "Synthetic instructions".into(), automations: vec![], engines: Vec::new(), reserve: None, acts: vec![], server: None, lists: None, author: ToolAuthor { device: "unknown".into(), name: "Synthetic".into(), }, signature: None, unknown: Default::default(), fallbacks: Vec::new(), unavailable: Vec::new(), }, tables: vec![table], pictures: Default::default(), samples: Default::default(), }; let clock = FixedClock; let mut input = input(&clock); let identity = Arc::new(cotton_client::DeviceIdentity::from_secret(&[42; 32]).unwrap()); let device_key = identity.device_id(); input.tool_signer = Some(ToolSigner { author: ToolAuthor { device: device_key.clone(), name: "Synthetic device".into(), }, sign: Arc::new(move |payload| Ok(identity.sign(payload))), }); let unsigned = encode_unsigned_package(&package).unwrap(); let imported = write_through_outbox( &db, "import_tool", json!({"bytes": STANDARD.encode(unsigned)}) .as_object() .unwrap(), &input, ) .unwrap(); assert!(imported["queued"].as_u64().unwrap() > 0); let signer = input.tool_signer.take(); let refused = run_tool( &db, "export_tool", json!({"tool_id":"synthetic_tool"}).as_object().unwrap(), &input, ) .unwrap_err(); assert!(refused.contains("no signing key"), "{refused}"); input.tool_signer = signer; let (exported, ops) = run_tool( &db, "export_tool", json!({"tool_id":"synthetic_tool"}).as_object().unwrap(), &input, ) .unwrap(); assert!( ops.is_empty(), "export signs bytes without writing definitions" ); let signed = decode_package( &STANDARD .decode(exported["bytes"].as_str().unwrap()) .unwrap(), ) .unwrap(); assert_eq!(signed.package.tool.author.device, device_key); assert_eq!(signed.signature, cotton_core::definitions::package::Signature::SignedBy { key: device_key.clone() }); let (listed, _) = run_tool(&db, "list_tools", &Map::new(), &input).unwrap(); assert_eq!(listed["tools"].as_array().unwrap().len(), 1); let removed = write_through_outbox( &db, "remove_tool", json!({"tool_id":"synthetic_tool"}).as_object().unwrap(), &input, ) .unwrap(); assert!(removed["queued"].as_u64().unwrap() > 0); let (listed, _) = run_tool(&db, "list_tools", &Map::new(), &input).unwrap(); assert!(listed["tools"].as_array().unwrap().is_empty()); assert_eq!(listed["table_definitions"][0]["orphaned"], true); } /// RULE: A member's screen writes and reads as its member device, never as the owner; the replica queues its real member receipt for sync. #[test] fn a_members_screen_writes_as_the_member_device() { let dir = tempfile::tempdir().unwrap(); let db = seeded(&dir.path().join("life.db")); db.run("UPDATE cotton_devices SET person_key = 'synthetic-member' WHERE id = ?", &[SqlValue::Text(device_row())]).unwrap(); let clock = FixedClock; let write_input = input(&clock); assert_eq!(owner_actor(&db, &write_input).unwrap().to_wire(), format!("member:{}", device_row())); let mut read_actor = String::new(); read_with_ctx(&db, &write_input, &mut |ctx| { read_actor = ctx.writer().unwrap().actor().to_string(); Ok(Value::Null) }).unwrap(); assert_eq!(read_actor, format!("member:{}", device_row())); write_through_outbox(&db, "create_todo", &args(&[("title", json!("From a member"))]), &write_input).unwrap(); assert!(count(&db, "SELECT COUNT(*) AS n FROM _outbox") > 0); assert!(count(&db, "SELECT COUNT(*) AS n FROM _writes WHERE actor LIKE 'member:%'") > 0); } /// A clock stopped at an instant of the test's choosing, so two files can /// write at a known order. #[derive(Debug)] struct At(&'static str); impl cotton_tools::clock::Clock for At { fn now(&self) -> chrono::DateTime { self.0.parse().expect("an instant") } } /// The Mac's own key: a second device of the owner's, approved in both files. const MAC_KEY: &str = "synthetic-mac-key"; /// [`input`] at `clock` for the device holding `key`, with random bytes of its /// own — each file mints an author of its own. fn input_at<'a>(clock: &'a At, key: &'a str, seed: u8) -> WriteInput<'a> { WriteInput { clock, device_key: Some(key), random: Arc::new(SeededRandom(std::sync::Mutex::new(seed))), ..input(&FixedClock) } } /// A file of the owner's held by the device whose key is `own`, holding the /// Mac's approved row beside the phone's: each file's author is minted for /// its own device, as on a real phone and a real Mac. fn seeded_with_mac(path: &std::path::Path, own: &str) -> Driver { let db = seeded(path); db.run("UPDATE _meta SET device_id = ?", &[SqlValue::Text(own.to_string())]).expect("this file's device"); let at = "2026-09-01T00:00:00.000Z"; db.run( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \ approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)", &[ SqlValue::Text(cotton_tools::devices::approval_row_id(WORKSPACE, MAC_KEY, at)), SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(MAC_KEY.to_string()), SqlValue::Text("A synthetic Mac".to_string()), SqlValue::Text(at.to_string()), SqlValue::Text("self".to_string()), SqlValue::Text(at.to_string()), SqlValue::Text(at.to_string()), ], ) .expect("the Mac's row"); db } fn todo_column(db: &Driver, id: &str, column: &str) -> Option { db.get(&format!("SELECT {column} AS v FROM cotton_todos WHERE id = ?"), &[SqlValue::Text(id.to_string())]) .expect("a read") .and_then(|row| row.text("v").map(str::to_string)) } /// Everything a file would hand a peer: its outbox, as the exchange reads it /// — each write and the author fact that names who wrote it. fn outbox(db: &Driver) -> Vec { cotton_store::exchange::exchange_request(db, WORKSPACE, None, &mut cotton_store::exchange::Handover::shut()) .expect("a request") .request .ops } /// The phone's file and the Mac's: the todo is made on the Mac, the phone /// ticks it, the Mac edits it in its app, and each file then folds what the /// other wrote. fn tick_and_edit(phone_at: &'static str, mac_at: &'static str) -> (Driver, Driver, String, tempfile::TempDir) { let dir = tempfile::tempdir().expect("a temp dir"); let phone = seeded_with_mac(&dir.path().join("phone.db"), KEY); let mac = seeded_with_mac(&dir.path().join("mac.db"), MAC_KEY); let birth = At("2026-09-09T04:00:00Z"); let (created, _) = run_tool(&mac, "create_todo", &args(&[("title", json!("Pay rent"))]), &input_at(&birth, MAC_KEY, 1)) .expect("the todo is made on the Mac"); cotton_store::fold::fold_ops(&phone, &outbox(&mac)).expect("the phone receives it"); let id = created["id"].as_str().expect("an id").to_string(); // THE PHONE'S TICK: `update_todo { status: done }` through the app's // own write. let phone_clock = At(phone_at); run_tool(&phone, "update_todo", &args(&[("id", json!(id)), ("status", json!("done"))]), &input_at(&phone_clock, KEY, 101)) .expect("the tick is written on the phone"); // THE APP'S WRITE on the Mac: a rename, and the same column set otherwise. let mac_clock = At(mac_at); run_tool( &mac, "update_todo", &args(&[("id", json!(id)), ("title", json!("Pay rent today")), ("status", json!("dropped"))]), &input_at(&mac_clock, MAC_KEY, 1), ) .expect("the edit is written on the Mac"); let from_phone = outbox(&phone); let from_mac = outbox(&mac); cotton_store::fold::fold_ops(&mac, &from_phone).expect("the Mac receives the tick"); cotton_store::fold::fold_ops(&phone, &from_mac).expect("the phone receives the edit"); (phone, mac, id, dir) } /// RULE: a phone's tick and a Mac's edit of one todo resolve by the one fold rule (newest stamp per field) on every file. #[test] fn a_tick_and_an_edit_of_one_todo_resolve_by_the_one_rule() { // The tick is the later write: its status wins on both files, and the // Mac's rename — a column the tick never touched — survives beside it. let (phone, mac, id, _dir) = tick_and_edit("2026-09-09T04:05:02Z", "2026-09-09T04:05:01Z"); for (file, db) in [("phone", &phone), ("mac", &mac)] { assert_eq!(todo_column(db, &id, "status").as_deref(), Some("done"), "{file}: the later tick wins status"); assert_eq!(todo_column(db, &id, "title").as_deref(), Some("Pay rent today"), "{file}: the rename survives"); } // The app's edit is the later write: it wins status over the tick, on // both files — a tick is not privileged for having come from the phone. let (phone, mac, id, _dir) = tick_and_edit("2026-09-09T04:05:01Z", "2026-09-09T04:05:02Z"); for (file, db) in [("phone", &phone), ("mac", &mac)] { assert_eq!(todo_column(db, &id, "status").as_deref(), Some("dropped"), "{file}: the later edit wins status"); assert_eq!(todo_column(db, &id, "title").as_deref(), Some("Pay rent today"), "{file}: the rename holds"); } } /// RULE: A write that queued no op asks the sync loop for no pass; one that queued any, or an envelope that does not say, does. #[test] fn a_write_that_queued_nothing_carries_nothing() { let envelope = |queued: serde_json::Value| match queued_answer(serde_json::json!({}), &[]) { serde_json::Value::Object(mut answer) => { answer.insert("queued".into(), queued); answer } _ => unreachable!("the envelope is an object"), }; assert!(!carries(&envelope(serde_json::json!(0))), "an empty write wakes nothing"); assert!(carries(&envelope(serde_json::json!(1))), "a queued op is carried"); let mut silent = envelope(serde_json::json!(0)); silent.remove("queued"); assert!(carries(&silent), "an envelope that does not say is carried"); }