Cotton code
2673 lines · 158.9 KB · RustRaw
//! A sealed table through the transport, against a scripted object and a//! real copy (sealing plan §2.4, L3). No kit table is sealed yet, so every//! suite here invents one: `garden_note`, clear `noted_on`, sealed `body`//! and `mood`, with `body` blind-indexed. Synthetic rows only.use std::sync::{Arc, Mutex};use serde_json::{json, Map, Value};use super::*;use crate::seal::{HeldDataKeys, Sealer};use crate::sync::cycle::run_cycle_paged;use crate::test_support::{open_test_replica, WORKSPACE};use crate::transport::scripted::{Reply, ScriptedExchange};use crate::transport::RefusalAware as _;use cotton_core::definitions::seal::SealSpec;use cotton_core::seal::DataKey;const NOW: &str = "2026-11-11T10:00:00.000Z";const SECRET_WORDS: &str = "Pumpkin whispers beside the compost";const TABLE: &str = "garden_note";fn dk() -> DataKey {    DataKey::from_bytes([7; 32])}fn spec() -> SealSpec {    SealSpec { clear: vec!["noted_on".into()], blind: vec!["body".into()], blind_exact: Vec::new(), blind_bytes: Default::default() }}fn definition() -> Value {    json!({        "id": TABLE, "name": "Garden note", "plural": "Garden notes", "picture": null, "builtin": false, "engine": null,        "columns": [            {"key": "noted_on", "name": "Noted on", "type": "text"},            {"key": "body", "name": "Body", "type": "text"},            {"key": "mood", "name": "Mood", "type": "text"},            {"key": "keep_open", "name": "Keep open", "type": "bool"},        ],        "title": "body", "date": null, "project": null, "order": null,        "slip": {"title": "body", "subtitle": null, "trailing": null, "photo": null, "toggle": null},        "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["body"]}],        "instructions": "Invented for a test.",        "seal": {"clear": ["noted_on"], "blind": ["body"]},    })}fn page(rows: Value, version: i64) -> Reply {    Reply::ok(&json!({"version": version, "rows": rows, "server_time": NOW}).to_string())}fn served() -> Reply {    Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition()], "flavour": {}, "boards": [], "etag": "e1"}).to_string())}/// The object's answer to a `seal_many` act: each row taken or refused, in order.fn sealed_answer(oks: &[bool]) -> Reply {    let results: Vec<Value> = oks.iter().map(|ok| if *ok { json!({"ok": true}) } else { json!({"ok": false, "status": 409, "code": "version_mismatch"}) }).collect();    Reply::ok(&json!({"version": 99, "changed": [], "results": results}).to_string())}fn act_taken() -> Reply {    Reply::ok(r#"{"version": 99, "changed": []}"#)}fn served_row(id: &str, version: i64, data: Value) -> Value {    json!({"table": TABLE, "id": id, "version": version, "owner": null, "data": data, "created_at": NOW, "updated_at": NOW})}/// A row as the object stores it, sealed with `key` under `v`.fn stored(key: &DataKey, id: &str, v: u32, body: &str) -> Value {    let mut row = Map::new();    row.insert("noted_on".into(), json!("2026-11-10"));    row.insert("body".into(), json!(body));    row.insert("mood".into(), json!("calm"));    Value::Object(cotton_core::seal::seal_row(key, WORKSPACE, TABLE, id, v, &spec(), &row, None).expect("a sealed row"))}fn body(seen: &crate::transport::scripted::Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}struct Bed {    _dir: tempfile::TempDir,    layout: crate::layout::Layout,    replica: Arc<Mutex<crate::Replica>>,    held: Arc<HeldDefinitions>,    /// Whether a short pass has asked the definitions yet (`mail_pass_short`).    held_definitions_asked: std::sync::atomic::AtomicBool,}fn bed() -> Bed {    let (dir, layout, replica) = open_test_replica();    Bed { _dir: dir, layout, replica: Arc::new(Mutex::new(replica)), held: HeldDefinitions::new(), held_definitions_asked: Default::default() }}impl Bed {    fn transport(&self, exchange: &Arc<ScriptedExchange>, sealer: Option<Arc<Sealer>>) -> ObjectTransport {        let path = self.replica.lock().expect("the copy").path.clone();        let mut object = ObjectTransport::new(            ObjectAddress::named("https://cotton.example.com", "synthetic").expect("an address"),            Arc::clone(exchange) as Arc<dyn Exchange>,            "synthetic-credential".into(),            ObjectTables::personal(),            path,            Vec::new(),        )        .taking_definitions(Arc::clone(&self.held));        if let Some(sealer) = sealer {            object = object.sealing_with(sealer);        }        object.lend_file(Arc::clone(&self.replica) as Arc<dyn crate::sync::cycle::LendsFile + Send + Sync>);        object    }    fn pass(&self, object: &mut ObjectTransport) {        run_cycle_paged(&self.replica, object, WORKSPACE, NOW).expect("a pass");    }    /// A note written on this phone, queued for the object.    fn write(&self, id: &str, body: &str) {        let copy = self.replica.lock().expect("the copy");        let mut patch = Map::new();        patch.insert("workspace_id".into(), WORKSPACE.into());        patch.insert("noted_on".into(), "2026-11-11".into());        patch.insert("body".into(), body.into());        patch.insert("mood".into(), "glad".into());        patch.insert("created_at".into(), NOW.into());        patch.insert("updated_at".into(), NOW.into());        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(11)));        cotton_store::mint::mint(            &copy.driver,            &cotton_store::mint::Act {                actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")),                verb: "add_note".into(),                history: cotton_store::mint::History::None,                changes: vec![cotton_store::mint::Change::create("cotton_garden_note", id, patch)],            },            &cotton_store::mint::clock::writer_clock(&copy.driver, 1_762_000_000_000, &mut ids).expect("the copy's clock"),            &mut ids,            cotton_store::mint::Held::Replica,        )        .expect("a queued change");    }    fn body_of(&self, id: &str) -> Option<String> {        let copy = self.replica.lock().expect("the copy");        copy.driver            .get("SELECT body FROM cotton_garden_note WHERE id = ?", &[rusqlite::types::Value::Text(id.into())])            .expect("a read")            .and_then(|row| row.text("body").map(str::to_string))    }    fn parked(&self) -> Vec<crate::seal::ParkedRow> {        crate::seal::parked(self.replica.lock().expect("the copy").driver.connection()).expect("the parked rows")    }    fn sealed_state(&self, id: &str) -> Option<i64> {        let copy = self.replica.lock().expect("the copy");        copy.driver            .get("SELECT sealed FROM _seal WHERE tbl = ? AND row_id = ?", &[rusqlite::types::Value::Text(TABLE.into()), rusqlite::types::Value::Text(id.into())])            .expect("a read")            .and_then(|row| row.int("sealed"))    }    fn pending(&self) -> i64 {        cotton_store::outbox::pending_count(&self.replica.lock().expect("the copy").driver).expect("the outbox")    }}fn sealer_with(key: Option<DataKey>) -> (Arc<HeldDataKeys>, Arc<Sealer>) {    let keys = HeldDataKeys::new();    if let Some(key) = key {        keys.hold(WORKSPACE, &key);    }    let sealer = Sealer::new(WORKSPACE, Arc::clone(&keys) as Arc<dyn crate::seal::DataKeyStore>);    // This object holds the arrival key already (e2e rulings R2): no pass here hands it over.    sealer.learn(cotton_core::seal::arrival::ARRIVAL_ROW, json!({"pub": "an-arrival-key-the-object-holds"}).as_object().expect("a row"));    (keys, sealer)}/// RULE (e2e rulings R2): a device holding the DK hands the object its/// arrival key once, after it has read every seal key row and found none:/// the public half its DK derives, never anything that opens a row.#[test]fn a_device_holding_the_key_hands_the_object_its_arrival_key_once() {    let keys = HeldDataKeys::new();    let sealer = Sealer::new(WORKSPACE, Arc::clone(&keys) as Arc<dyn crate::seal::DataKeyStore>);    sealer.learned_all();    assert!(sealer.arrival_row().is_none(), "no key, nothing to hand over");    keys.hold(WORKSPACE, &dk());    let row = sealer.arrival_row().expect("the arrival key");    assert_eq!((row["table"].clone(), row["id"].clone()), (json!("seal_key"), json!("arrival")));    let public = cotton_core::seal::arrival::arrival_public(&dk(), WORKSPACE).expect("a public key");    assert_eq!(row["data"], json!({"pub": cotton_core::seal::share::key_text(&public)}));    assert!(sealer.arrival_row().is_none(), "once");    let held = Sealer::new(WORKSPACE, Arc::clone(&keys) as Arc<dyn crate::seal::DataKeyStore>);    held.learn("arrival", row["data"].as_object().expect("a row"));    held.learned_all();    assert!(held.arrival_row().is_none(), "an object that holds it is not asked again");}/// RULE (e2e rulings R2): a row the object sealed at arrival comes down/// opened with the secret the DK derives, is noted open, and the next sweep/// seals it again under the table's key, the blob only.#[test]fn a_row_sealed_at_arrival_opens_and_the_sweep_seals_it_under_the_table_key() {    let (_keys, sealer) = sealer_with(Some(dk()));    sealer.learned_all();    let public = cotton_core::seal::arrival::arrival_public(&dk(), WORKSPACE).expect("a public key");    let mut plain = Map::new();    plain.insert("noted_on".into(), json!("2026-11-10"));    plain.insert("body".into(), json!(SECRET_WORDS));    let data = cotton_core::seal::arrival::seal_arrival_with(&cotton_core::seal::Dek::from_bytes([8; 32]), &[1; 12], &[2; 32], &[3; 12], &public, WORKSPACE, TABLE, "n-9", &spec(), &plain).expect("sealed at arrival");    let row = served_row("n-9", 4, Value::Object(data));    let (opened, note) = crate::seal::unseal(Some(&sealer), Some(&spec()), &row, NOW).expect("a sealed table's row");    assert_eq!(opened.expect("opened")["data"]["body"], SECRET_WORDS);    assert!(matches!(note, crate::seal::Note::Open { ref id, version: 4, .. } if id == "n-9"), "noted open, for the sweep: {note:?}");    let other = Sealer::new(WORKSPACE, HeldDataKeys::new() as Arc<dyn crate::seal::DataKeyStore>);    let (none, parked) = crate::seal::unseal(Some(&other), Some(&spec()), &row, NOW).expect("a sealed table's row");    assert!(none.is_none() && matches!(parked, crate::seal::Note::Parked { ref code, .. } if code == "seal_key_missing"), "no key, parked by name: {parked:?}");}/// GUARD (sealing plan §8, every lane): no sealed column's plaintext is in/// what a write sends — not in `data`, not anywhere in the act's bytes.fn assert_no_plaintext(act: &crate::transport::scripted::Seen) {    let text = String::from_utf8_lossy(&act.body);    assert!(!text.contains("Pumpkin") && !text.contains(SECRET_WORDS), "a sealed body left in the clear: {text}");    let sent = body(act);    // One row's `data`, or each row of a `seal_many`.    let datas: Vec<Value> = match sent["args"]["rows"].as_array() {        Some(rows) => rows.iter().map(|r| r["data"].clone()).collect(),        None => vec![sent["args"]["data"].clone()],    };    for data in &datas {        let data = data.as_object().expect("the act's data");        for key in data.keys() {            assert!(                spec().clear.contains(key) || cotton_core::seal::row::RESERVED.contains(&key.as_str()),                "{key} is sealed and was in the act's data: {sent}"            );        }    }}/// RULE (sealing plan §2.4): a write to a sealed table goes up sealed under/// the table's version with its blind tokens, and the object's row comes/// back down opened into the copy's own columns.#[test]fn a_sealed_tables_write_goes_up_sealed_and_comes_back_down_opened() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    bed.write("n-1", SECRET_WORDS);    bed.pass(&mut object);    let act = exchange.nth(2);    let sent = body(&act);    assert_eq!(sent["act"], "create");    assert_eq!(sent["args"]["table"], TABLE);    assert_no_plaintext(&act);    let data = sent["args"]["data"].as_object().expect("the data").clone();    assert_eq!(data["noted_on"], "2026-11-11", "a clear column stays clear");    assert_eq!(data["seal_v"], 1);    assert!(data["sealed_enc"].as_str().is_some_and(|text| text.starts_with("s1:")));    assert!(data["dek_enc"].as_str().is_some_and(|text| text.starts_with("d1:")));    let blind: Vec<String> = serde_json::from_value(sent["args"]["blind"].clone()).expect("the blind tokens");    let bk = cotton_core::seal::blind_key(&dk(), WORKSPACE, TABLE).expect("a blind key");    let pumpkin = cotton_core::seal::blind::word_token(&bk, "body", "pumpkin").wire();    assert!(blind.contains(&pumpkin), "the body's words are blind tokens");    assert_eq!(bed.pending(), 0);    assert_eq!(bed.sealed_state("n-1"), Some(1), "the wrap is kept for the next edit");    // The object's row, as it stored it, comes back and opens.    let exchange = ScriptedExchange::new([page(json!([served_row("n-1", 2, Value::Object(data.clone()))]), 2), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS));    assert!(bed.parked().is_empty());    // An edit reuses the row's DEK, so a share of it keeps opening.    let dek = cotton_core::seal::row::dek_of(&dk(), WORKSPACE, TABLE, "n-1", &data).expect("the first DEK");    {        let copy = bed.replica.lock().expect("the copy");        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(12)));        let mut patch = Map::new();        patch.insert("body".into(), "A second secret".into());        cotton_store::mint::mint(            &copy.driver,            &cotton_store::mint::Act {                actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")),                verb: "edit_note".into(),                history: cotton_store::mint::History::None,                changes: vec![cotton_store::mint::Change::update("cotton_garden_note", "n-1", patch)],            },            &cotton_store::mint::clock::writer_clock(&copy.driver, 1_762_000_100_000, &mut ids).expect("the copy's clock"),            &mut ids,            cotton_store::mint::Held::Replica,        )        .expect("a queued edit");    }    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 2)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let edit = body(&exchange.nth(0));    assert_eq!((edit["act"].as_str(), edit["args"]["expect_version"].as_i64()), (Some("seal"), Some(2)), "kept only while the row is at the version read");    let edited = edit["args"]["data"].as_object().expect("the edit's data");    let again = cotton_core::seal::row::dek_of(&dk(), WORKSPACE, TABLE, "n-1", edited).expect("the edit's DEK");    assert_eq!(again.expose(), dek.expose(), "the edit kept the row's DEK");    assert_eq!(cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", edited).expect("opens")["body"], "A second secret");}/// RULE: a row that does not open is parked by name — never dropped, never/// folded blank — and opens on a later pass once the key is held.#[test]fn a_row_that_does_not_open_is_parked_by_name_and_opens_once_the_key_is_held() {    let bed = bed();    let alien = DataKey::from_bytes([9; 32]);    // No key on this device yet: the object's row parks as key-missing; a    // row sealed under a key this database never had parks as does-not-open.    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([        page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS)), served_row("n-2", 1, stored(&alien, "n-2", 1, "Elsewhere"))]), 1),        served(),    ]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1"), None, "nothing folds blank");    assert_eq!(bed.body_of("n-2"), None);    let parked = bed.parked();    assert_eq!(parked.iter().map(|row| (row.id.as_str(), row.code.as_str())).collect::<Vec<_>>(), vec![("n-1", "seal_key_missing"), ("n-2", "seal_key_missing")]);    assert!(parked[0].row["data"]["sealed_enc"].is_string(), "kept whole, as the object served it");    // The key arrives (the shell read it from its key store): the next pass    // opens what it can, and names what it cannot.    keys.hold(WORKSPACE, &dk());    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS));    let parked = bed.parked();    assert_eq!(parked.iter().map(|row| (row.id.as_str(), row.code.as_str())).collect::<Vec<_>>(), vec![("n-2", "seal_does_not_open")]);    assert_eq!(bed.body_of("n-2"), None);}/// RULE (12 Nov 2026): rows parked before the/// first vault open in a launch open on the very next pass, even one that/// goes on with a pull a time-boxed background slice stopped mid-way: the/// shell keeps no data key across launches, so a background pull parks them,/// and the key arrives only when the vault opens.#[test]fn rows_parked_before_the_key_open_on_the_next_pass_even_one_that_goes_on_mid_pull() {    let bed = bed();    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS))]), 1), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.parked().len(), 1, "no key in the background: parked");    // A background slice stopped the next pull mid-way: the copy holds a page.    {        let copy = bed.replica.lock().expect("the copy");        assert!(cotton_store::cursors::advance_cursor(&copy.driver, CURSOR_KEY, &page_cursor(0, 1, 1, "mid"), NOW).expect("the cursor"));    }    // The vault opens: the key is held, and the pass that goes on from that page opens the row.    keys.hold(WORKSPACE, &dk());    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert_eq!(exchange.nth(0).path, "/v1/sync?cursor=mid", "the pass went on mid-pull");    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS), "opened on the first pass after the key");    assert!(bed.parked().is_empty());}/// RULE (dev, 24 Nov 2026: a first pull of 100,000 invented mails parked/// 172,013 rows, the key opened, the fold that took them failed, and the copy/// held none of them and parked none): a parked row has no other copy, so its/// park goes only once the row stands in the copy. A row the fold refuses/// keeps its park, and the next pass opens and folds it.#[test]fn a_row_the_fold_refuses_after_the_key_stays_parked_for_the_next_pass() {    let bed = bed();    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([        page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS)), served_row("n-2", 1, stored(&dk(), "n-2", 1, "A second invented note"))]), 1),        served(),    ]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.parked().len(), 2, "no key yet: both parked");    // The copy refuses one of them as the fold writes it (as a row breaking one of its rules would).    let refuse = |on: bool| {        let copy = bed.replica.lock().expect("the copy");        let sql = if on {            "CREATE TRIGGER invented_refusal BEFORE INSERT ON cotton_garden_note WHEN NEW.id = 'n-2' BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END"        } else {            "DROP TRIGGER invented_refusal"        };        copy.driver.connection().execute_batch(sql).expect("the trigger");    };    refuse(true);    keys.hold(WORKSPACE, &dk());    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    let _ = run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW);    assert_eq!(bed.body_of("n-2"), None, "the refused row did not fold");    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS), "the row the copy took stands");    assert_eq!(bed.parked().iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), vec!["n-2"], "the refused row is still parked, and only it: nothing lost");    // The next pass, the copy taking them again: both open and fold, and only then do their parks go.    refuse(false);    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS));    assert_eq!(bed.body_of("n-2").as_deref(), Some("A second invented note"));    assert!(bed.parked().is_empty(), "{:?}", bed.parked());}/// RULE: no key, no write — the write waits in the outbox, retryable and/// named, nothing is posted, and it goes up sealed once the key is held.#[test]fn a_write_with_no_key_waits_by_name_and_nothing_goes_in_the_clear() {    let bed = bed();    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    bed.write("n-1", SECRET_WORDS);    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| seen.path != routes::ACT), "nothing was posted: {:?}", exchange.seen().iter().map(|seen| seen.path.clone()).collect::<Vec<_>>());    assert_eq!(bed.pending(), 1, "the write waits");    let error = bed        .replica        .lock()        .expect("the copy")        .driver        .get("SELECT last_error FROM _outbox", &[])        .expect("a read")        .and_then(|row| row.text("last_error").map(str::to_string));    assert!(error.as_deref().is_some_and(|text| text.starts_with("seal_key_missing")), "{error:?}");    // A transport with no sealer at all refuses the same way.    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, None);    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| seen.path != routes::ACT));    assert_eq!(bed.pending(), 1);    keys.hold(WORKSPACE, &dk());    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert_no_plaintext(&exchange.nth(0));    assert_eq!(bed.pending(), 0);}/// RULE (sealing plan §1): the sweep seals every open row of a sealed/// table — the Worker's own writes — with `expect_version`, leaves a row/// changed since and one kept open, and resumes where a dropped line left it.#[test]fn the_sweep_seals_open_rows_with_their_version_and_resumes() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let open = |id: &str, version: i64, extra: Value| {        let mut data = json!({"noted_on": "2026-11-09", "body": format!("{SECRET_WORDS} {id}"), "mood": "calm"});        if let (Some(data), Some(extra)) = (data.as_object_mut(), extra.as_object()) {            data.extend(extra.clone());        }        served_row(id, version, data)    };    let exchange = ScriptedExchange::new([page(json!([open("n-1", 5, json!({})), open("n-2", 6, json!({})), open("n-3", 7, json!({}))]), 7), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1").as_deref(), Some(&*format!("{SECRET_WORDS} n-1")), "an open row reads as it stands");    assert_eq!(bed.sealed_state("n-1"), Some(0), "noted for the sweep");    // The next pass pulls first, then sweeps what earlier pulls folded: every open row in ONE round trip (SYNC STUCK,    // 25 Nov 2026). n-1 changed on the object since; n-2 and n-3 are sealed.    let exchange = ScriptedExchange::new([page(json!([]), 7), served(), sealed_answer(&[false, true, true])]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert!(exchange.nth(0).path.starts_with(routes::SYNC), "the pull goes first, never behind the sweep");    let first = exchange.nth(2);    assert_eq!(body(&first)["act"], "seal_many");    let rows = body(&first)["args"]["rows"].as_array().cloned().expect("rows");    assert_eq!(rows.iter().map(|r| r["expect_version"].as_i64().unwrap_or_default()).collect::<Vec<_>>(), vec![5, 6, 7]);    assert_no_plaintext(&first);    assert_eq!(cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-2", rows[1]["data"].as_object().expect("data")).expect("opens")["mood"], "calm");    // What was sealed is kept; what was refused waits for the next pass's batch, never retried one by one.    assert_eq!((bed.sealed_state("n-1"), bed.sealed_state("n-2"), bed.sealed_state("n-3")), (Some(0), Some(1), Some(1)));    // The next pass takes what is left, and nothing twice.    let exchange = ScriptedExchange::new([page(json!([]), 7), sealed_answer(&[true])]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let act = exchange.seen().into_iter().find(|seen| seen.path == routes::ACT).expect("one seal_many");    let sent: Vec<String> = body(&act)["args"]["rows"].as_array().cloned().unwrap_or_default().iter().map(|r| r["id"].as_str().unwrap_or_default().to_string()).collect();    assert_eq!(sent, vec!["n-1"]);    assert_eq!(bed.sealed_state("n-1"), Some(1));    // A row the person keeps open stays open.    let exchange = ScriptedExchange::new([page(json!([open("n-4", 9, json!({"keep_open": true}))]), 9), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let exchange = ScriptedExchange::new([page(json!([]), 9), served()]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| seen.path != routes::ACT), "no seal act for a kept-open row");}/// RULE (§3.2 step 8): the table's `seal_v` comes from the object's/// `seal_key` rows, is kept beside the copy for the next launch, and every/// later write seals under it.#[test]fn the_tables_seal_version_comes_from_the_object_and_survives_a_launch() {    let bed = bed();    let (keys, sealer) = sealer_with(Some(dk()));    let version_row = json!({"table": "seal_key", "id": "v:garden_note", "version": 1, "owner": null, "data": {"v": 3}, "created_at": NOW, "updated_at": NOW});    let arrival_row = json!({"table": "seal_key", "id": "arrival", "version": 1, "owner": null, "data": {"pub": "an-arrival-key-the-object-holds"}, "created_at": NOW, "updated_at": NOW});    let exchange = ScriptedExchange::new([page(json!([version_row, arrival_row]), 1), served()]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    // A fresh launch: a new sealer learns the version from the copy.    let sealer = Sealer::new(WORKSPACE, Arc::clone(&keys) as Arc<dyn crate::seal::DataKeyStore>);    bed.write("n-1", SECRET_WORDS);    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let data = body(&exchange.nth(0))["args"]["data"].clone();    assert_eq!(data["seal_v"], 3);    assert!(cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", data.as_object().expect("data")).is_ok());    // An advance moves it on at once.    let act = sealer.advance(TABLE);    assert_eq!(act, json!({"act": "update", "args": {"table": "seal_key", "id": "v:garden_note", "data": {"v": 4}}}));    assert_eq!(sealer.version(TABLE), 4);}/// GUARD: every act a device posts is checked — a sealed column in the/// clear is refused by name, on a write, a seal and a restore alike.#[test]fn every_act_that_names_a_sealed_column_in_the_clear_is_refused_by_name() {    // Todos are sealed (e2e rulings R3); this case holds them as the open table beside the sealed one.    let map = ObjectTables::personal().with_defined([&definition()]).expect("a map").opening(&["todo"]);    assert_eq!(map.object(TABLE).and_then(|table| table.seal.clone()), Some(spec()), "the map marks the table sealed");    let spec_of = |name: &str| map.object(name).and_then(|table| table.seal.clone());    let clear = json!({"table": TABLE, "id": "n-1", "data": {"noted_on": "2026-11-11", "body": SECRET_WORDS}});    for act in ["create", "update", "seal"] {        let refused = crate::seal::guard_act(spec_of, act, &clear).expect_err("refused");        assert!(refused.starts_with("seal_clear_refused") && refused.contains("body"), "{refused}");    }    let restore = json!({"rows": [{"table": "todo", "id": "t-1", "data": {"title": "open"}}, {"table": TABLE, "id": "n-1", "data": {"mood": "glad"}}]});    assert!(crate::seal::guard_act(spec_of, "restore", &restore).is_err());    let sealed = json!({"table": TABLE, "id": "n-1", "data": stored(&dk(), "n-1", 1, SECRET_WORDS)});    assert!(crate::seal::guard_act(spec_of, "create", &sealed).is_ok());    let kept_open = json!({"table": TABLE, "id": "n-1", "data": {"body": "a procedure", "keep_open": true}});    assert!(crate::seal::guard_act(spec_of, "update", &kept_open).is_ok());    assert!(crate::seal::guard_act(spec_of, "update", &json!({"table": "todo", "id": "t-1", "data": {"title": "open"}})).is_ok(), "an open table is untouched");}/// The object's `seal_key` rows as a whole-table pull answers them.fn keys_page(v: u32) -> Reply {    page(json!([{"table": "seal_key", "id": format!("v:{TABLE}"), "version": 4, "owner": null, "data": {"v": v}, "created_at": NOW, "updated_at": NOW}]), 4)}/// A copy with the sealed table placed and no pull to the object's end yet/// (the object answers version 0): what a brand-new copy is.fn fresh_bed() -> Bed {    let bed = bed();    let exchange = ScriptedExchange::new([page(json!([]), 0), served()]);    let mut object = bed.transport(&exchange, None);    bed.pass(&mut object);    bed}fn open_body(data: &Value, id: &str) -> Value {    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, id, data.as_object().expect("the data")).expect("it opens with the database's key");    opened.get("body").cloned().unwrap_or(Value::Null)}/// RULE (seal-gaps 3): a copy that has not pulled to the object's end/// seals nothing before it has read the object's seal keys: it asks for/// them whole first, keeps them beside the copy, and seals under the/// version they say — never under 1 while the object is past it.#[test]fn a_fresh_copy_reads_the_objects_seal_keys_before_it_seals() {    let bed = fresh_bed();    bed.write("n-1", SECRET_WORDS);    let (_keys, sealer) = sealer_with(Some(dk()));    assert!(!sealer.has_learned());    let exchange = ScriptedExchange::new([keys_page(4), act_taken(), page(json!([]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let asked = exchange.nth(0);    assert_eq!(asked.method, "GET");    assert!(asked.path.contains("since=0") && asked.path.contains("tables=seal_key"), "{}", asked.path);    let act = exchange.nth(1);    assert_no_plaintext(&act);    assert_eq!(body(&act)["args"]["data"]["seal_v"], 4, "sealed under the object's version");    assert_eq!(bed.pending(), 0);    let kept = crate::seal::kept_keys(bed.replica.lock().expect("the copy").driver.connection()).expect("the kept keys");    assert_eq!(kept.len(), 1, "kept beside the copy: {kept:?}");}/// RULE (seal-gaps 3): when the seal keys cannot be read, the write waits,/// retryable, by name, and nothing is posted.#[test]fn a_fresh_copy_whose_seal_keys_cannot_be_read_waits() {    let bed = fresh_bed();    bed.write("n-1", SECRET_WORDS);    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([Reply::json(503, r#"{"code":"busy","message":"try later"}"#), page(json!([]), 0), served()]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| seen.method != "POST"), "nothing posted");    assert_eq!(bed.pending(), 1, "the write waits");}/// RULE (seal-gaps 2): a top-up (and the remake and restore that run it)/// sends a sealed table's row sealed under the object's version with its/// blind tokens, never in the clear; with no key it stops by name before/// anything is sent, and the object still lacks the row, so a remake keeps/// the copy.#[test]fn a_top_up_seals_what_it_sends_and_stops_without_a_key() {    let bed = fresh_bed();    bed.write("n-1", SECRET_WORDS);    let rekey = Rekey::default();    let served_tables = [definition()];    let tables = [TABLE.to_string()];    let into = RestoreInto { layout: &bed.layout, object_id: WORKSPACE, served_tables: &served_tables, tables: &tables, rekey: &rekey, at: NOW };    let held_none = || Reply::ok(r#"{"held": {}}"#);    // No key: stopped by name, nothing sent, still lacking.    let (_keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([held_none(), keys_page(3), held_none()]);    let object = bed.transport(&exchange, Some(sealer));    let stopped = object.top_up(&into, &mut |_, _| true, Written::Nothing).expect_err("no key");    assert_eq!((stopped.status, stopped.code.as_str()), (0, crate::seal::SEAL_KEY_MISSING), "{}", stopped.message);    assert!(exchange.seen().iter().all(|seen| seen.method != "POST"), "nothing posted");    assert_eq!(object.lacking(&into).expect("asked").len(), 1, "the object still lacks it");    // With the key: sealed under the object's version, tokens beside it.    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([held_none(), keys_page(3), Reply::ok(r#"{"version": 9, "restored": [{"table": "garden_note", "id": "n-1", "landed": "made"}]}"#)]);    let object = bed.transport(&exchange, Some(sealer));    let sent = object.top_up(&into, &mut |_, _| true, Written::Nothing).expect("sent");    assert_eq!(sent.sent, 1);    let restore = exchange.nth(2);    let text = String::from_utf8_lossy(&restore.body).to_string();    assert!(!text.contains("Pumpkin"), "a sealed body left in the clear: {text}");    let said = body(&restore);    assert_eq!(said["act"], "restore");    let row = &said["args"]["rows"][0];    assert_eq!(row["data"]["seal_v"], 3);    assert!(row["data"].get("body").is_none() && row["data"].get("mood").is_none(), "{row}");    assert!(row["blind"].as_array().is_some_and(|tokens| !tokens.is_empty()), "{row}");    assert_eq!(open_body(&row["data"], "n-1"), json!(SECRET_WORDS));}/// RULE (seal-gaps 2): an adopt posts a sealed table's write sealed, under/// the object's version, with its blind tokens.#[test]fn an_adopt_seals_what_it_posts() {    let bed = fresh_bed();    bed.write("n-1", SECRET_WORDS);    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([keys_page(2), act_taken()]);    let object = bed.transport(&exchange, Some(sealer));    let rekey = Rekey::default();    let served_tables = [definition()];    let into = AdoptInto { layout: &bed.layout, object_id: WORKSPACE, served_tables: &served_tables, rekey: &rekey, sends: &|table, _| table == "cotton_garden_note", at: NOW };    let adopted = object.adopt_writes(&into, &mut |_, _| true).expect("adopted");    assert_eq!((adopted.delivered, adopted.refused), (1, 0));    let act = exchange.nth(1);    assert_no_plaintext(&act);    let said = body(&act);    assert_eq!(said["act"], "create");    assert_eq!(said["args"]["data"]["seal_v"], 2);    assert!(said["args"]["blind"].as_array().is_some_and(|tokens| !tokens.is_empty()));    assert_eq!(open_body(&said["args"]["data"], "n-1"), json!(SECRET_WORDS));}/// RULE (12 Nov 2026): a kit copy keeps only its/// kit's definitions, yet the passes hold every served table's plural from/// the object's whole answer: the Keys card asking for a table the owner made/// names it ("Garden notes"), not by its id.#[test]fn a_kit_copy_holds_the_plural_of_a_table_outside_its_kit() {    let bed = bed();    let kit = cotton_core::kit::AppKit::named("keys").map(Arc::new);    assert!(kit.as_ref().is_some_and(|kit| !kit.keeps_table(TABLE)), "the Keys kit keeps no garden note");    let exchange = ScriptedExchange::new([page(json!([]), 1), served()]);    let mut object = bed.transport(&exchange, None).keeping_to(kit);    bed.pass(&mut object);    assert_eq!(bed.held.plural(TABLE).as_deref(), Some("Garden notes"));}/// RULE (e2e rulings R1, 15 Nov 2026: walk todos-sealed sent news_settings in the clear at sign-in): a table this build compiles but carries no definition of (an app's build carries its own kit's files) waits for the object's definition before any write of it goes: until then it is neither open nor sealed here, and once the definition is placed it is what that says.#[test]fn a_compiled_table_with_no_carried_definition_waits_for_the_objects() {    let map = ObjectTables::personal();    let waiting = map.object("news_settings").expect("mapped");    if cotton_core::kit::table_file("news_settings").is_some() {        return; // a build that carries it rules it from its own file    }    assert!(waiting.awaits_seal(), "unknown until the object says");    let sealed = json!({"id": "news_settings", "columns": [{"key": "timezone", "type": "text"}], "seal": {"clear": []}});    let placed = map.with_defined([&sealed]).expect("a map");    let table = placed.object("news_settings").expect("mapped");    assert!(table.seal.is_some() && !table.awaits_seal(), "sealed as the object's definition says");    let open = json!({"id": "news_settings", "columns": [{"key": "timezone", "type": "text"}]});    let placed = map.with_defined([&open]).expect("a map");    let table = placed.object("news_settings").expect("mapped");    assert!(table.seal.is_none() && !table.awaits_seal(), "open as the object's definition says");}// ── film-progress-clobber: a write says only what it changed ───────────────fn kit_definition(table: &str) -> Value {    serde_json::from_slice(cotton_core::kit::table_file(table).expect("the kit's table")).expect("the kit's definition reads")}fn served_definition(definition: &Value) -> Reply {    Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition], "flavour": {}, "boards": [], "etag": "e-film"}).to_string())}/// `patch` written on this phone to the row `id` of the copy's `store`, queued for the object.fn edit(bed: &Bed, store: &str, id: &str, patch: Map<String, Value>) {    let copy = bed.replica.lock().expect("the copy");    let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(13)));    cotton_store::mint::mint(        &copy.driver,        &cotton_store::mint::Act {            actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")),            verb: "edit_row".into(),            history: cotton_store::mint::History::None,            changes: vec![cotton_store::mint::Change::update(store, id, patch)],        },        &cotton_store::mint::clock::writer_clock(&copy.driver, 1_762_000_100_000, &mut ids).expect("the copy's clock"),        &mut ids,        cotton_store::mint::Held::Replica,    )    .expect("a queued edit");}/// RULE (film-progress-clobber, 18 Nov 2026): a phone holding a film at version n saves its place after another writer/// laid a new master, tracks and state at n+1. The save names only the place, so what the other writer laid survives.fn a_saved_place_leaves_what_another_writer_laid(table: &str) {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let definition = kit_definition(table);    let spec = crate::seal::spec_of_definition(&definition).expect("a seal block").expect("the table is sealed");    let store = ObjectTables::personal().with_defined([&definition]).expect("a map").object(table).expect("mapped").store.clone();    let id = "11111111-2222-4333-8444-555555555555";    let mut held = Map::new();    held.insert("title".into(), json!("Synthetic Harbour"));    held.insert("file".into(), json!("db/films/f1/master.m3u8"));    held.insert("subtitle_work".into(), json!("generating"));    held.insert("position".into(), json!(10));    let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, table, id, 1, &spec, &held, None).expect("a sealed row");    let row = json!({"table": table, "id": id, "version": 5, "owner": null, "data": sealed, "created_at": NOW, "updated_at": NOW});    let exchange = ScriptedExchange::new([page(json!([row]), 5), served_definition(&definition)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut place = Map::new();    place.insert("position".into(), json!(70));    place.insert("position_at".into(), json!("2026-11-18T15:30:00.000Z"));    edit(&bed, &store, id, place);    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 5)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let sent = body(&exchange.nth(0));    assert_eq!(sent["act"], "update");    let data = sent["args"]["data"].as_object().expect("the data");    let mut named: Vec<&str> = data.keys().map(String::as_str).collect();    named.sort_unstable();    assert_eq!(named, ["position", "position_at"], "the save names the place and nothing else");    // The object merges what it is sent over what it holds at n+1.    let mut object_row = json!({"file": "db/films/f1/master-abc123.m3u8", "subtitle_work": "ready", "subtitle_note": "laid", "position": 10});    for (key, value) in data {        object_row[key] = value.clone();    }    assert_eq!(object_row["file"], "db/films/f1/master-abc123.m3u8");    assert_eq!(object_row["subtitle_work"], "ready");    assert_eq!(object_row["subtitle_note"], "laid");    assert_eq!(object_row["position"], 70);    assert_eq!(bed.pending(), 0);}#[test]fn a_films_saved_place_leaves_what_another_writer_laid() {    a_saved_place_leaves_what_another_writer_laid("film");}#[test]fn a_series_episodes_saved_place_leaves_what_another_writer_laid() {    a_saved_place_leaves_what_another_writer_laid("film_episode");}/// RULE (film-progress-clobber): the sealed half is one blob, so an edit of a sealed column is kept only while the row is/// at the version this copy read. Refused, it waits; the pull brings the other writer's words, and the edit goes again over them.#[test]fn a_sealed_edit_over_a_row_that_moved_goes_again_over_the_newest_words() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let row = |version: i64, mood: &str| {        let mut plain = Map::new();        plain.insert("noted_on".into(), json!("2026-11-10"));        plain.insert("body".into(), json!("The first words"));        plain.insert("mood".into(), json!(mood));        let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, TABLE, "n-1", 1, &spec(), &plain, None).expect("a sealed row");        // Changed on the object before this phone's edit (UNSENT HEAL 5: a change older than the row's is stale).        let mut served = served_row("n-1", version, Value::Object(sealed));        served["updated_at"] = json!(BEFORE_THE_EDIT);        served    };    let exchange = ScriptedExchange::new([page(json!([row(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    // Refused as moved, the row is read again from the object (UNSENT HEAL 4) and the edit goes over it, this pass.    let moved = Reply::json(409, r#"{"code": "version_moved", "message": "garden_note n-1 is at version 6, not 5"}"#);    let rows = Reply::json(200, &json!({ "rows": [row(6, "stormy")] }).to_string());    let exchange = ScriptedExchange::new([moved, rows, act_taken(), page(json!([row(6, "stormy")]), 6), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let first = body(&exchange.nth(0));    assert_eq!((first["act"].as_str(), first["args"]["expect_version"].as_i64()), (Some("seal"), Some(5)));    let again = body(&exchange.nth(2));    assert_eq!((again["act"].as_str(), again["args"]["expect_version"].as_i64()), (Some("seal"), Some(6)));    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", again["args"]["data"].as_object().expect("the data")).expect("it opens");    assert_eq!(opened["body"], "The words I wrote", "the edit is kept");    assert_eq!(opened["mood"], "stormy", "the other writer's words are kept");    assert_eq!(bed.pending(), 0);}/// RULE (undo-after-columns, 18 Nov 2026): the bin's mark on a sealed table is a clear column. Putting a row in the bin and/// taking it out each go up as that column alone, the way out as an explicit null, and the sealed blob is never sent again.fn the_bins_mark_goes_up_alone(table: &str, column: &str, fields: Value) {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let definition = kit_definition(table);    let spec = crate::seal::spec_of_definition(&definition).expect("a seal block").expect("the table is sealed");    let store = ObjectTables::personal().with_defined([&definition]).expect("a map").object(table).expect("mapped").store.clone();    let id = "22222222-3333-4444-8555-666666666666";    let held = fields.as_object().expect("the row's fields").clone();    let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, table, id, 1, &spec, &held, None).expect("a sealed row");    let row = json!({"table": table, "id": id, "version": 5, "owner": null, "data": sealed, "created_at": NOW, "updated_at": NOW});    let exchange = ScriptedExchange::new([page(json!([row]), 5), served_definition(&definition)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let copied: i64 = bed.replica.lock().expect("the copy").driver.connection().query_row(&format!("SELECT COUNT(*) FROM \"{store}\" WHERE id = ?1"), [id], |row| row.get(0)).expect("a count");    assert_eq!(copied, 1, "{table}: the row is in this copy");    for said in [json!("2026-11-18T10:00:00.000Z"), Value::Null] {        let mut mark = Map::new();        mark.insert(column.into(), said.clone());        edit(&bed, &store, id, mark);        let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 5)]);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));        bed.pass(&mut object);        let sent = body(&exchange.nth(0));        assert_eq!(sent["act"], "update", "{table}: a clear column needs no seal");        assert_eq!(sent["args"]["data"], json!({column: said}), "{table}: the mark and nothing else");        assert_eq!(bed.pending(), 0, "{table}: taken");    }}#[test]fn a_sealed_documents_way_in_and_out_of_the_bin_goes_up_alone() {    let paper = json!({"title": "A synthetic paper", "original_name": "synthetic.pdf", "mime": "application/pdf", "byte_size": 12, "sha256": "0".repeat(64), "storage_path": "db/documents/synthetic.pdf", "status": "ready", "doc_type": "other", "source": "app"});    the_bins_mark_goes_up_alone("document", "trashed_at", paper);}#[test]fn a_sealed_notes_way_in_and_out_of_the_bin_goes_up_alone() {    the_bins_mark_goes_up_alone("note", "trashed_at", json!({"title": "A synthetic note", "body": "Synthetic."}));}#[test]fn a_sealed_notes_archive_and_its_return_go_up_alone() {    the_bins_mark_goes_up_alone("note", "archived_at", json!({"title": "A synthetic note", "body": "Synthetic."}));}/// An app's kit holding the invented garden note and nothing else of the personal kit.fn garden_kit() -> Arc<cotton_core::kit::AppKit> {    Arc::new(cotton_core::kit::AppKit {        id: "garden".into(), tools: Vec::new(), tables: vec![TABLE.into()], folds: Vec::new(), aside: Vec::new(),        fan_of: None, acts: Vec::new(), face: None, signals: false, only: Default::default(), window: Default::default(), all_history: Vec::new(), late: Vec::new(),    })}impl Bed {    /// The zone claim as an older build wrote it at launch: the database's    /// `news_settings` row (its zone, the rest defaults), queued for the object.    fn claim_zone(&self) {        let copy = self.replica.lock().expect("the copy");        let mut patch = Map::new();        patch.insert("workspace_id".into(), WORKSPACE.into());        patch.insert("timezone".into(), "Asia/Kolkata".into());        patch.insert("created_at".into(), NOW.into());        patch.insert("updated_at".into(), NOW.into());        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(5)));        cotton_store::mint::mint(            &copy.driver,            &cotton_store::mint::Act {                actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")),                verb: "materialize_todo_recurrences".into(),                history: cotton_store::mint::History::None,                changes: vec![cotton_store::mint::Change::create("cotton_news_settings", WORKSPACE, patch)],            },            &cotton_store::mint::clock::writer_clock(&copy.driver, 1_761_000_000_000, &mut ids).expect("the copy's clock"),            &mut ids,            cotton_store::mint::Held::Replica,        )        .expect("a queued claim");    }    fn queued_tables(&self) -> Vec<String> {        let copy = self.replica.lock().expect("the copy");        // The author's own fact, queued beside its first write, is bookkeeping.        copy.driver.all("SELECT tbl FROM _outbox WHERE tbl <> 'cotton_authors' ORDER BY hlc", &[]).expect("the outbox").iter().filter_map(|row| row.text("tbl").map(str::to_string)).collect()    }}/// RULE (owner, 21 Nov 2026: Books, Music, Cinemas and Story said "Waiting to/// send 1 row" for ever): a queued row of a table the app's kit does not/// carry, which this copy can never seal (no kit app takes that table's/// definition), leaves the queue at the next pass and stays on this phone as/// it is; the rows behind it go in the same pass, and a row of a table the/// kit carries still waits for its key.#[test]fn a_row_of_a_table_the_kit_does_not_carry_leaves_the_queue_and_the_rows_behind_it_go() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(garden_kit()));    bed.pass(&mut object);    bed.claim_zone();    bed.write("n-1", SECRET_WORDS);    assert_eq!(bed.queued_tables(), ["cotton_news_settings", "cotton_garden_note"]);    // With no key, the kit table's row waits by name; the claim leaves. (The pass after the first fill asks the    // tables it left whole, as an object that carries them again answers.)    let (_none, keyless) = sealer_with(None);    let exchange = ScriptedExchange::new([again_page(json!([]), 1, &garden_kit())]);    let mut object = bed.transport(&exchange, Some(keyless)).keeping_to(Some(garden_kit()));    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| seen.path != routes::ACT), "nothing was posted");    assert_eq!(bed.queued_tables(), ["cotton_garden_note"], "the note waits for its key, the claim is gone");    // With the key, the note goes and nothing waits.    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(garden_kit()));    bed.pass(&mut object);    let posted: Vec<Value> = exchange.seen().iter().filter(|seen| seen.path == routes::ACT).map(body).collect();    assert_eq!(posted.len(), 1, "only the note was posted: {posted:?}");    assert_eq!(posted[0]["args"]["table"], json!(TABLE));    assert_no_plaintext(&exchange.nth(0));    assert_eq!(bed.pending(), 0, "nothing waits: {:?}", bed.queued_tables());    let kept = bed.replica.lock().expect("the copy").driver.get("SELECT timezone FROM cotton_news_settings WHERE workspace_id = ?", &[rusqlite::types::Value::Text(WORKSPACE.into())]).expect("a read");    assert_eq!(kept.and_then(|row| row.text("timezone").map(str::to_string)).as_deref(), Some("Asia/Kolkata"), "the row stays on this phone");}/// RULE: Cotton keeps the whole object, so its claim is never let go to the/// kit rule; but `news_settings` is retired (TABLE DROP 1), so the claim is/// parked with its patch, never sent, and the row stays on this phone.#[test]fn the_whole_objects_claim_of_a_retired_table_is_parked_and_kept() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    bed.claim_zone();    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| seen.path != routes::ACT), "nothing was posted");    assert!(bed.queued_tables().is_empty(), "{:?}", bed.queued_tables());    let copy = bed.replica.lock().expect("the copy");    let parked = copy.driver.all("SELECT tbl, reason FROM _parked WHERE direction = 'push'", &[]).expect("the parks");    assert!(parked.iter().any(|row| row.text("tbl") == Some("cotton_news_settings") && row.text("reason").is_some_and(|reason| reason.starts_with("table_gone"))), "{parked:?}");}/// RULE (owner's lost edit, 21 Nov 2026): an edit of a merged column (Words' body) made offline over version 5, refused because the/// assistant's rewrite made it 6, does not go again over the rewrite by its later stamp. The pull keeps the newer body as theirs, the row/// is not sent while its app's merge waits, and the merged body goes at version 6 and becomes the base of what follows.#[test]fn an_edit_refused_as_moved_keeps_the_newer_text_until_it_is_merged() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let row = |version: i64, body: &str| {        let mut plain = Map::new();        plain.insert("noted_on".into(), json!("2026-11-10"));        plain.insert("body".into(), json!(body));        plain.insert("mood".into(), json!("calm"));        let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, TABLE, "n-1", 1, &spec(), &plain, None).expect("a sealed row");        served_row("n-1", version, Value::Object(sealed))    };    let base = "Pack the bag\nBook the train\n";    let theirs = "Pack the bag\nBook the 7:10 train, seat 42\n";    let mine = "Pack the bag and the charger\nBook the train\n";    let exchange = ScriptedExchange::new([page(json!([row(5, base)]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    // Offline: the edit, and the base the app keeps for it.    let mut words = Map::new();    words.insert("body".into(), json!(mine));    edit(&bed, "cotton_garden_note", "n-1", words);    let edit_base = |sql: &str| {        let copy = bed.replica.lock().expect("the copy");        let db = copy.driver.connection();        db.execute_batch(crate::seal::EDIT_BASE_DDL).expect("the table");        db.execute_batch(sql).expect("the base");    };    edit_base(&format!("INSERT INTO _edit_base (tbl, row_id, col, base) VALUES ('{TABLE}', 'n-1', 'body', '{base}')"));    let held = || -> (String, i64, Option<String>) {        let copy = bed.replica.lock().expect("the copy");        copy.driver.connection().query_row("SELECT base, moved, theirs FROM _edit_base WHERE row_id = 'n-1'", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).expect("the base row")    };    // Online: refused as moved; the pull brings the assistant's rewrite.    let moved = Reply::json(409, r#"{"code": "version_moved", "message": "garden_note n-1 is at version 6, not 5"}"#);    let exchange = ScriptedExchange::new([moved, page(json!([row(6, theirs)]), 6), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(held(), (base.to_string(), 1, Some(theirs.to_string())), "the newer text is kept as theirs");    assert_eq!(bed.pending(), 1);    // While the merge waits, the row is not sent over the rewrite.    let exchange = ScriptedExchange::new([page(json!([]), 6)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert!(exchange.seen().iter().all(|seen| !seen.path.contains("/v1/act")), "no post while the merge waits: {:?}", exchange.seen().iter().map(|seen| seen.path.clone()).collect::<Vec<_>>());    assert_eq!(bed.pending(), 1);    // The app merges (Words: `notes::merge_waiting`) and writes the result as its edit.    let merged = cotton_core::cotton_rules::writing::merge::merge(base, mine, theirs).text;    assert_eq!(merged, "Pack the bag and the charger\nBook the 7:10 train, seat 42\n");    let mut words = Map::new();    words.insert("body".into(), json!(merged));    edit(&bed, "cotton_garden_note", "n-1", words);    edit_base(&format!("UPDATE _edit_base SET base = '{theirs}', theirs = NULL, moved = 0"));    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 6)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let again = body(&exchange.nth(0));    assert_eq!((again["act"].as_str(), again["args"]["expect_version"].as_i64()), (Some("seal"), Some(6)));    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", again["args"]["data"].as_object().expect("the data")).expect("it opens");    assert_eq!(opened["body"], merged, "both sides' words go up");    assert_eq!(bed.pending(), 0);    assert_eq!(held(), (merged.clone(), 0, None), "what the object took is the base of what follows");}/// A second invented sealed table, the garden's plots, beside the notes.const PLOT: &str = "garden_plot";fn plot_definition() -> Value {    let mut definition = definition();    definition["id"] = json!(PLOT);    definition["name"] = json!("Garden plot");    definition["plural"] = json!("Garden plots");    definition}/// RULE (seen on an emulator, 22 Nov 2026): a new phone's first pull runs while it waits for the key, so every row it/// brings parks; once the key is held, the rows of tables the kit does not name late open first and fold on their own/// (Comms' chats stood only once its mail had opened with them); the pass rests there so they are drawn, and the late/// tables' rows open on the next pass.#[test]fn rows_parked_before_the_key_open_in_the_kits_order_the_late_tables_after() {    let bed = bed();    let kit = Arc::new(cotton_core::kit::AppKit {        id: "garden".into(), tools: Vec::new(), tables: vec![TABLE.into(), PLOT.into()], folds: Vec::new(), aside: Vec::new(),        fan_of: None, acts: Vec::new(), face: None, signals: false, only: Default::default(), window: Default::default(), all_history: Vec::new(),        late: vec![TABLE.into()],    });    let plot = |id: &str| {        let mut row = Map::new();        row.insert("noted_on".into(), json!("2026-11-10"));        row.insert("body".into(), json!("The bean row"));        row.insert("mood".into(), json!("calm"));        let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, PLOT, id, 1, &spec(), &row, None).expect("a sealed row");        json!({"table": PLOT, "id": id, "version": 1, "owner": null, "data": sealed, "created_at": NOW, "updated_at": NOW})    };    let both = Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition(), plot_definition()], "flavour": {}, "boards": [], "etag": "e1"}).to_string());    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS)), plot("p-1")]), 1), both]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    bed.pass(&mut object);    assert_eq!(bed.parked().len(), 2, "no key yet: both parked");    // The key is held. The pass opens the plot alone and rests there, still behind, before it asks the object for    // anything: a pass tells the screens what it folded as it ends, so the plot is drawn before the note opens, and    // nothing the object holds meanwhile (here a second note) folds with it.    keys.hold(WORKSPACE, &dk());    let exchange = ScriptedExchange::new([page(json!([served_row("n-2", 1, stored(&dk(), "n-2", 1, "A second invented note"))]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    let report = run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW).expect("a pass");    let plot_body = bed.replica.lock().expect("the copy").driver.get("SELECT body FROM cotton_garden_plot WHERE id = 'p-1'", &[]).expect("a read").and_then(|row| row.text("body").map(str::to_string));    assert_eq!(plot_body.as_deref(), Some("The bean row"), "the table that is not late opened first");    assert_eq!(bed.parked().iter().map(|row| row.table.as_str()).collect::<Vec<_>>(), vec![TABLE], "the late table's row waits for the next pass");    assert_eq!(exchange.seen().iter().filter(|seen| seen.path.starts_with(routes::SYNC)).count(), 0, "the pass asked no page: it rested on what opened");    assert_eq!(bed.body_of("n-2"), None, "nothing pulled folded with the plot");    assert!(report.behind, "still behind: the loop comes straight back");    assert!(report.tables.iter().any(|table| table.contains("garden_plot")), "the plot is told to the screens as the pass ends: {:?}", report.tables);    // The next pass opens the late row, then asks the object from where the cursor stood.    let exchange = ScriptedExchange::new([again_page(json!([served_row("n-2", 1, stored(&dk(), "n-2", 1, "A second invented note"))]), 1, &kit)]);    let mut object = bed.transport(&exchange, Some(sealer)).keeping_to(Some(kit));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS));    assert_eq!(bed.body_of("n-2").as_deref(), Some("A second invented note"));    assert!(bed.parked().is_empty());}/// A page from an object that carries tables again whole (`again=`): it says it carried every table `kit` pulls.fn again_page(rows: Value, version: i64, kit: &cotton_core::kit::AppKit) -> Reply {    Reply::ok(&json!({"version": version, "rows": rows, "server_time": NOW, "again": kit.pulled()}).to_string())}/// The tables a sync page asks for (`tables=`).fn tables_asked(path: &str) -> Vec<String> {    path.split("tables=").nth(1).unwrap_or_default().split('&').next().unwrap_or_default().split(',').filter(|table| !table.is_empty()).map(str::to_string).collect()}/// RULE (seen on an emulator, 22 Nov 2026: a new Comms phone's first pull of an account of 110,000 emails brought the/// mail's 90-day window with the chats, 22,000 rows in one pass, and the recovery card, asked once a pass ends, stood at/// 47 s against 10 s without mail; the pass after it pulled the whole kit again from the start, every chat and mail a/// second time): a fresh copy's first fill asks the app's own tables but the kit's late ones, so it ends once the chats/// are in; the pass after asks the tables it left whole (`again=`) and the rest since its cursor, never from the start.#[test]fn a_first_fill_leaves_the_kits_late_tables_and_the_next_pass_asks_them_whole_since_its_cursor() {    let bed = bed();    let kit = Arc::new(cotton_core::kit::AppKit {        id: "garden".into(), tools: Vec::new(), tables: vec![TABLE.into(), PLOT.into()], folds: Vec::new(), aside: Vec::new(),        fan_of: None, acts: Vec::new(), face: None, signals: false, only: Default::default(), window: Default::default(), all_history: Vec::new(),        late: vec![TABLE.into()],    });    let mut plot = Map::new();    plot.insert("noted_on".into(), json!("2026-11-10"));    plot.insert("body".into(), json!("The bean row"));    plot.insert("mood".into(), json!("calm"));    let plot = cotton_core::seal::seal_row(&dk(), WORKSPACE, PLOT, "p-1", 1, &spec(), &plot, None).expect("a sealed row");    let both = Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition(), plot_definition()], "flavour": {}, "boards": [], "etag": "e1"}).to_string());    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([{"table": PLOT, "id": "p-1", "version": 1, "owner": null, "data": plot, "created_at": NOW, "updated_at": NOW}]), 1), both]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    bed.pass(&mut object);    let fill: Vec<String> = exchange.seen().iter().filter(|seen| seen.path.starts_with(routes::SYNC)).map(|seen| seen.path.clone()).collect();    let asked = tables_asked(&fill[0]);    assert!(fill[0].contains("since=0&") && asked.iter().any(|table| table == PLOT), "the fill asks the app's own tables: {}", fill[0]);    assert!(!asked.iter().any(|table| table == TABLE), "but not the kit's late table: {}", fill[0]);    let exchange = ScriptedExchange::new([again_page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS))]), 1, &kit)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    bed.pass(&mut object);    let next: Vec<String> = exchange.seen().iter().filter(|seen| seen.path.starts_with(routes::SYNC)).map(|seen| seen.path.clone()).collect();    assert_eq!(next.len(), 1, "one page: {next:?}");    assert!(next[0].contains("since=1&"), "the pass after the fill asks since its cursor, never from the start: {}", next[0]);    assert!(next[0].contains("&limit=5000&"), "the key held, its pages are whole: {}", next[0]);    let again: Vec<&str> = next[0].split("again=").nth(1).expect("it asks tables again").split('&').next().unwrap_or_default().split(',').collect();    assert!(again.contains(&TABLE), "the late table comes whole: {}", next[0]);    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS), "and its rows land");    // Once they came, nothing is owed: the next pass asks since its cursor alone.    let exchange = ScriptedExchange::new([page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer)).keeping_to(Some(kit));    bed.pass(&mut object);    let after: Vec<String> = exchange.seen().iter().filter(|seen| seen.path.starts_with(routes::SYNC)).map(|seen| seen.path.clone()).collect();    assert!(after.len() == 1 && after[0].contains("since=1&") && !after[0].contains("again="), "nothing more is owed: {after:?}");}/// RULE (seen on an emulator, 22 Nov 2026: Comms' recovery code typed while the mail's window came, the key was held/// 10 s later against 1.3 s with nothing coming, and the chats stood 15.3 s after the key against 9.4 s): a pass that/// carries the kit's late tables while no key is held asks short pages, as its rows only park, so a key opened/// meanwhile waits on one short page.#[test]fn a_pass_of_the_late_tables_before_the_key_asks_short_pages() {    let bed = bed();    let kit = Arc::new(cotton_core::kit::AppKit {        id: "garden".into(), tools: Vec::new(), tables: vec![TABLE.into(), PLOT.into()], folds: Vec::new(), aside: Vec::new(),        fan_of: None, acts: Vec::new(), face: None, signals: false, only: Default::default(), window: Default::default(), all_history: Vec::new(),        late: vec![TABLE.into()],    });    let both = Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition(), plot_definition()], "flavour": {}, "boards": [], "etag": "e1"}).to_string());    let (_keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([page(json!([]), 1), both]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    bed.pass(&mut object);    let fill = exchange.seen().iter().find(|seen| seen.path.starts_with(routes::SYNC)).map(|seen| seen.path.clone()).expect("the fill");    assert!(fill.contains("&limit=5000&"), "the chats' fill is asked whole: {fill}");    let exchange = ScriptedExchange::new([again_page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS))]), 1, &kit)]);    let mut object = bed.transport(&exchange, Some(sealer)).keeping_to(Some(kit));    bed.pass(&mut object);    let late = exchange.seen().iter().find(|seen| seen.path.starts_with(routes::SYNC)).map(|seen| seen.path.clone()).expect("the late tables' pass");    assert!(late.contains("again=") && late.contains("&limit=1000&"), "no key: the late tables come in short pages: {late}");    assert_eq!(bed.parked().len(), 1, "and their rows park");}fn served_open() -> Reply {    let mut open = definition();    open.as_object_mut().expect("a definition").remove("seal");    Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [open], "flavour": {}, "boards": [], "etag": "e-open"}).to_string())}/// RULE (the memory lock, 23 Nov 2026, assets/design/shared/MEMORY-LOCK.md): a/// table the object seals after this copy pulled its rows open (memory, one/// account at a time) comes again whole, once, so each row is noted open with/// the object's version and the sweep seals it; a copy that never kept the set/// of sealed tables it has seen takes today's as seen and pulls nothing again.#[test]fn a_table_sealed_after_its_rows_came_open_comes_again_whole_once_and_is_swept() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let open = |id: &str, version: i64| served_row(id, version, json!({"noted_on": "2026-11-09", "body": format!("{SECRET_WORDS} {id}"), "mood": "calm"}));    // The table is open: its rows fold with no seal note.    let exchange = ScriptedExchange::new([page(json!([open("n-1", 5), open("n-2", 6)]), 6), served_open()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.body_of("n-1").as_deref(), Some(&*format!("{SECRET_WORDS} n-1")));    // A pass with nothing new: the copy keeps the (empty) set of sealed tables it has seen, and asks nothing again.    let exchange = ScriptedExchange::new([page(json!([]), 6), served_open()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert!(!exchange.nth(0).path.contains("again="), "nothing is owed: {}", exchange.nth(0).path);    // The object seals the table: the pass's first page places the sealed definition, and the pass asks for the    // table again whole; every row lands noted open with its version.    // The switch moved the object's version (7): the pass asks for the definitions.    let again = Reply::ok(&json!({"version": 7, "rows": [open("n-1", 5), open("n-2", 6)], "server_time": NOW, "again": [TABLE]}).to_string());    let exchange = ScriptedExchange::new([page(json!([]), 7), served(), again]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let asked = exchange.seen().into_iter().filter(|seen| seen.path.starts_with(routes::SYNC)).last().expect("a page asked");    assert!(asked.path.contains(&format!("again={TABLE}")), "the sealed table is asked again whole: {}", asked.path);    assert_eq!((bed.sealed_state("n-1"), bed.sealed_state("n-2")), (Some(0), Some(0)), "noted for the sweep");    // The sweep seals each at the version the object holds, and the table is never asked whole again.    let exchange = ScriptedExchange::new([page(json!([]), 7), served(), sealed_answer(&[true, true])]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let seals: Vec<(String, i64)> = exchange.seen().iter().filter(|seen| seen.path == routes::ACT).flat_map(|seen| body(seen)["args"]["rows"].as_array().cloned().unwrap_or_default()).map(|r| (r["id"].as_str().unwrap_or_default().to_string(), r["expect_version"].as_i64().unwrap_or(-1))).collect();    assert_eq!(seals, vec![("n-1".to_string(), 5), ("n-2".to_string(), 6)]);    for seen in exchange.seen().iter().filter(|seen| seen.path == routes::ACT) {        assert_no_plaintext(seen);    }    assert!(exchange.seen().iter().filter(|seen| seen.path.starts_with(routes::SYNC)).all(|seen| !seen.path.contains("again=")), "asked whole once");    assert_eq!((bed.sealed_state("n-1"), bed.sealed_state("n-2")), (Some(1), Some(1)));}/// A copy updated to this build, its sealed tables pulled sealed already (every row noted): it takes them as seen and asks nothing again.#[test]fn a_copy_whose_sealed_rows_are_all_noted_asks_nothing_again() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([served_row("n-1", 5, stored(&dk(), "n-1", 1, "a sealed line"))]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    for _ in 0..2 {        let exchange = ScriptedExchange::new([page(json!([]), 5), served()]);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));        bed.pass(&mut object);        assert!(exchange.seen().iter().filter(|seen| seen.path.starts_with(routes::SYNC)).all(|seen| !seen.path.contains("again=")), "nothing asked again");    }}/// RULE (coordinator, 24 Nov 2026: the owner's lock stood at 320 sealed, 21 open, every open one archived and/// written by an assistant): memory as the object serves it under the lock, an active entry and an archived/// assistant's entry, both land, are noted open and are sealed by the next sweep.#[test]fn memory_under_the_lock_an_archived_assistants_entry_is_swept_like_any_other() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let mut memory: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/memory.json")).expect("the kit's memory");    memory["seal"] = json!({"clear": ["status", "visibility", "origin_kind", "machine", "reviewed_at", "archived_at", "created_at", "superseded_by"], "blind": ["title"], "blind_exact": ["slug"]});    let served_memory = Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [memory], "flavour": {}, "boards": [], "etag": "e-memory"}).to_string());    let entry = |id: &str, version: i64, data: Value| json!({"table": "memory", "id": id, "version": version, "owner": null, "data": data, "created_at": NOW, "updated_at": NOW});    let rows = json!([        entry("00000000-0000-4000-8000-000000000001", 5, json!({"slug": "invented-kept", "title": "Invented kept entry", "status": "active", "visibility": "private", "origin_kind": "user", "created_at": NOW})),        entry("00000000-0000-4000-8000-000000000002", 6, json!({"slug": "invented-archived", "title": "Invented archived entry", "status": "archived", "archived_at": NOW, "visibility": "private", "origin_kind": "agent", "origin_label": "Invented Claude", "source": "invented session", "created_at": NOW})),    ]);    let exchange = ScriptedExchange::new([page(rows, 6), served_memory.clone()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let state = |id: &str| {        let copy = bed.replica.lock().expect("the copy");        let noted = copy.driver.get("SELECT sealed FROM _seal WHERE tbl = 'memory' AND row_id = ?", &[rusqlite::types::Value::Text(id.into())]).expect("a read").and_then(|row| row.int("sealed"));        let held = copy.driver.get("SELECT status FROM cotton_memories WHERE id = ?", &[rusqlite::types::Value::Text(id.into())]).expect("a read").and_then(|row| row.text("status").map(str::to_string));        (noted, held)    };    eprintln!("after the pull: kept {:?}, archived {:?}", state("00000000-0000-4000-8000-000000000001"), state("00000000-0000-4000-8000-000000000002"));    let exchange = ScriptedExchange::new([sealed_answer(&[true, true]), page(json!([]), 6), served_memory]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let seals: Vec<String> = exchange.seen().iter().filter(|seen| seen.path == routes::ACT).flat_map(|seen| body(seen)["args"]["rows"].as_array().cloned().unwrap_or_default()).map(|r| r["id"].as_str().unwrap_or_default().to_string()).collect();    eprintln!("sealed: {seals:?}; after: kept {:?}, archived {:?}", state("00000000-0000-4000-8000-000000000001"), state("00000000-0000-4000-8000-000000000002"));    assert_eq!(seals.len(), 2, "both entries are sealed: {seals:?}");}/// The owner's path (24 Nov 2026): memory pulled open first, then sealed by the lock, taken again whole and swept;/// an archived assistant's entry with it.#[test]fn memory_turned_sealed_takes_an_archived_assistants_entry_again_and_sweeps_it() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let kit: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/memory.json")).expect("the kit's memory");    let mut sealed = kit.clone();    sealed["seal"] = json!({"clear": ["status", "visibility", "origin_kind", "machine", "reviewed_at", "archived_at", "created_at", "superseded_by"], "blind": ["title"], "blind_exact": ["slug"]});    let defs = |table: &Value, etag: &str| Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [table], "flavour": {}, "boards": [], "etag": etag}).to_string());    let kept = "00000000-0000-4000-8000-000000000001";    let archived = "00000000-0000-4000-8000-000000000002";    let entry = |id: &str, version: i64, data: Value| json!({"table": "memory", "id": id, "version": version, "owner": null, "data": data, "created_at": NOW, "updated_at": NOW});    let rows = || {        json!([            entry(kept, 5, json!({"slug": "invented-kept", "title": "Invented kept entry", "body": "", "status": "active", "visibility": "private", "origin_kind": "user", "created_at": NOW})),            entry(archived, 6, json!({"slug": "invented-assistant-note", "title": "Invented assistant note about herons", "body": "", "status": "archived", "archived_at": NOW, "machine": null, "visibility": "private", "origin_kind": "agent", "origin_label": "invented-mac hook", "source": null, "source_external_id": null, "superseded_by": null})),        ])    };    // Open: both land with no seal note.    let exchange = ScriptedExchange::new([page(rows(), 6), defs(&kit, "e-open")]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let exchange = ScriptedExchange::new([page(json!([]), 6), defs(&kit, "e-open")]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    // The lock: sealed definitions, the table asked again whole.    let again = Reply::ok(&json!({"version": 7, "rows": rows(), "server_time": NOW, "again": ["memory"]}).to_string());    let exchange = ScriptedExchange::new([page(json!([]), 7), defs(&sealed, "e-sealed"), again]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let asked: Vec<String> = exchange.seen().iter().map(|seen| seen.path.clone()).collect();    let state = |id: &str| {        let copy = bed.replica.lock().expect("the copy");        copy.driver.get("SELECT sealed FROM _seal WHERE tbl = 'memory' AND row_id = ?", &[rusqlite::types::Value::Text(id.into())]).expect("a read").and_then(|row| row.int("sealed"))    };    eprintln!("asked: {asked:?}\nnoted: kept {:?}, archived {:?}", state(kept), state(archived));    let exchange = ScriptedExchange::new([sealed_answer(&[true, true]), page(json!([]), 7), defs(&sealed, "e-sealed")]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let seals: Vec<String> = exchange.seen().iter().filter(|seen| seen.path == routes::ACT).flat_map(|seen| body(seen)["args"]["rows"].as_array().cloned().unwrap_or_default()).map(|r| r["id"].as_str().unwrap_or_default().to_string()).collect();    assert_eq!(seals, vec![kept.to_string(), archived.to_string()], "both swept");}/// An object from before `seal_many` (SYNC STUCK, 25 Nov 2026) answers `unknown_act`: the sweep seals one row a round/// trip for the rest of the pass, as it always did.#[test]fn the_sweep_falls_back_to_one_row_a_trip_on_an_object_without_seal_many() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let open = |id: &str, version: i64| served_row(id, version, json!({"noted_on": "2026-11-09", "body": format!("{SECRET_WORDS} {id}"), "mood": "calm"}));    let exchange = ScriptedExchange::new([page(json!([open("n-1", 5), open("n-2", 6)]), 6), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let exchange = ScriptedExchange::new([page(json!([]), 6), served(), Reply::json(400, r#"{"code": "unknown_act", "message": "no act seal_many"}"#), act_taken(), act_taken()]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let acts: Vec<String> = exchange.seen().iter().filter(|seen| seen.path == routes::ACT).map(|seen| body(seen)["act"].as_str().unwrap_or_default().to_string()).collect();    assert_eq!(acts, vec!["seal_many", "seal", "seal"]);    assert_eq!((bed.sealed_state("n-1"), bed.sealed_state("n-2")), (Some(1), Some(1)));}/// SYNC STUCK (25 Nov 2026): one pass's sweep seals no more than its budget, rows or time, and says more is left; the/// rest go on later passes, so a phone holding thousands of open rows still finishes every pass.#[test]fn a_sweep_seals_no_more_than_its_budget_and_says_the_rest_wait() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let rows: Vec<Value> = (1..=5).map(|i| served_row(&format!("n-{i}"), i, json!({"noted_on": "2026-11-09", "body": format!("{SECRET_WORDS} {i}"), "mood": "calm"}))).collect();    let exchange = ScriptedExchange::new([page(json!(rows), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let map = object.map();    let path = bed.replica.lock().expect("the copy").path.clone();    let file = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).expect("the copy, read only");    let open = crate::seal::sweep::open_rows(&file, &map).expect("open rows");    assert_eq!(open.len(), 5);    let row_of = |table: &str, id: &str| match map.object(table) {        Some(stored) if !file_columns(&file, &stored.store)?.is_empty() => row_now(&file, stored, id),        _ => Ok(None),    };    let mut posted = Vec::new();    let mut kept = 0;    let swept = crate::seal::sweep::sweep(        &sealer,        &map,        &open,        crate::seal::sweep::Budget { rows: 2, until: None },        row_of,        |rows| {            posted.push(rows.len());            Ok(rows.iter().map(|_| Ok(())).collect())        },        |notes| {            kept += notes.len();            Ok(())        },    )    .expect("a sweep");    assert_eq!((posted, kept, swept.more), (vec![2], 2, true), "two rows in one trip, kept, the rest said to wait");    // Out of time: nothing more is sealed this pass.    let row_of = |table: &str, id: &str| match map.object(table) {        Some(stored) if !file_columns(&file, &stored.store)?.is_empty() => row_now(&file, stored, id),        _ => Ok(None),    };    let late = crate::seal::sweep::sweep(&sealer, &map, &open, crate::seal::sweep::Budget { rows: usize::MAX, until: Some(std::time::Instant::now()) }, row_of, |_| panic!("nothing is posted out of time"), |_| Ok(())).expect("a sweep");    assert!(late.more);}/// Park `ids` before the key: a first pull of them with no key held.fn parked_before_the_key(bed: &Bed, rows: Vec<Value>) -> (Arc<HeldDataKeys>, Arc<Sealer>) {    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([page(Value::Array(rows), 1), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    (keys, sealer)}/// RULE (FIRST SYNC, dev, 26 Nov 2026: a new phone's first pull parked 70,000 invented mails before the key, and/// opened all in one page they never folded inside a pass, so none ever opened): a page opens at most/// REOPEN_AT_ONCE parked rows; the pass rests on them and the next pass opens the rest.#[test]fn rows_parked_before_the_key_open_a_batch_a_pass() {    let bed = bed();    let n = super::REOPEN_AT_ONCE + 3;    let rows = (0..n).map(|i| served_row(&format!("n-{i:05}"), 1, stored(&dk(), &format!("n-{i:05}"), 1, "An invented note"))).collect();    let (keys, sealer) = parked_before_the_key(&bed, rows);    assert_eq!(bed.parked().len(), n);    keys.hold(WORKSPACE, &dk());    let exchange = ScriptedExchange::new([page(json!([]), 1), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.parked().len(), 3, "one batch a pass");    assert_eq!(bed.body_of("n-00000").as_deref(), Some("An invented note"));    let exchange = ScriptedExchange::new([page(json!([]), 1), served()]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert!(bed.parked().is_empty(), "the rest on the next pass");    assert_eq!(bed.body_of(&format!("n-{:05}", n - 1)).as_deref(), Some("An invented note"));}/// RULE: rows that still do not open once the key is held (another key's) go to the back of the queue, so a full/// batch of them never holds back a row that opens, and never asks the pass back for more.#[test]fn rows_that_never_open_never_hold_the_queue() {    let bed = bed();    let alien = DataKey::from_bytes([9; 32]);    let mut rows: Vec<Value> = (0..super::REOPEN_AT_ONCE).map(|i| served_row(&format!("a-{i:05}"), 1, stored(&alien, &format!("a-{i:05}"), 1, "Elsewhere"))).collect();    rows.push(served_row("z-1", 1, stored(&dk(), "z-1", 1, SECRET_WORDS)));    let (keys, sealer) = parked_before_the_key(&bed, rows);    keys.hold(WORKSPACE, &dk());    for _ in 0..2 {        let exchange = ScriptedExchange::new([page(json!([]), 1), served()]);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));        bed.pass(&mut object);    }    assert_eq!(bed.body_of("z-1").as_deref(), Some(SECRET_WORDS), "opened past a batch that never opens");    assert_eq!(bed.parked().len(), super::REOPEN_AT_ONCE, "the others stay parked by name");    assert!(bed.parked().iter().all(|row| row.code == "seal_does_not_open"));}/// One pass with a batch of `n` on this thread: whether it ended behind (the loop then comes straight back), or why/// it failed.fn pass_batched(bed: &Bed, sealer: &Arc<Sealer>, rows: Value, n: usize) -> Result<bool, String> {    super::REOPEN_TEST.with(|cell| cell.set(Some(n)));    let exchange = ScriptedExchange::new([page(rows, 1), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(sealer)));    let report = run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW);    super::REOPEN_TEST.with(|cell| cell.set(None));    report.map(|report| report.behind).map_err(|failure| format!("{failure:?}"))}fn notes(n: usize) -> Vec<Value> {    (0..n).map(|i| served_row(&format!("n-{i:02}"), 1, stored(&dk(), &format!("n-{i:02}"), 1, "An invented note"))).collect()}fn refuse_note(bed: &Bed, id: Option<&str>) {    let copy = bed.replica.lock().expect("the copy");    let sql = match id {        Some(id) => format!("CREATE TRIGGER invented_refusal BEFORE INSERT ON cotton_garden_note WHEN NEW.id = '{id}' BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END"),        None => "DROP TRIGGER invented_refusal".to_string(),    };    copy.driver.connection().execute_batch(&sql).expect("the trigger");}/// RULE (FIRST SYNC 2 REVIEW): many batches, one a pass: each pass but the last ends behind (the loop comes straight/// back), and the last does not; a row the object takes between batches folds once a page is asked.#[test]fn parked_rows_open_over_many_batches_each_pass_behind_but_the_last() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, notes(10));    keys.hold(WORKSPACE, &dk());    let mut left = Vec::new();    let mut behind = Vec::new();    for pass in 0..4 {        // A new note reaches the object after the first batch: served by any page asked from then (a pass that        // rests on its batch asks none).        let rows = if pass >= 1 { json!([served_row("new-1", 1, stored(&dk(), "new-1", 1, "Arrived between batches"))]) } else { json!([]) };        behind.push(pass_batched(&bed, &sealer, rows, 3).expect("a pass"));        left.push(bed.parked().len());    }    assert_eq!(left, vec![7, 4, 1, 0]);    assert_eq!(behind, vec![true, true, true, false], "behind while a full batch opened; not on the last");    assert_eq!(bed.body_of("new-1").as_deref(), Some("Arrived between batches"));    assert_eq!(bed.body_of("n-09").as_deref(), Some("An invented note"));}/// RULE (FIRST SYNC 2 REVIEW): a batch whose fold fails whole (the app killed mid-batch, as far as the copy knows)/// loses nothing: every park stands, and the next pass opens them.#[test]fn a_batch_whose_fold_fails_whole_loses_nothing() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, notes(5));    keys.hold(WORKSPACE, &dk());    {        let copy = bed.replica.lock().expect("the copy");        copy.driver.connection().execute_batch("CREATE TRIGGER invented_refusal BEFORE INSERT ON cotton_garden_note BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END").expect("the trigger");    }    let _ = pass_batched(&bed, &sealer, json!([]), 3);    assert_eq!(bed.parked().len(), 5, "every park stands");    refuse_note(&bed, None);    for _ in 0..3 {        let _ = pass_batched(&bed, &sealer, json!([]), 3);    }    assert!(bed.parked().is_empty(), "{:?}", bed.parked().iter().map(|r| r.id.clone()).collect::<Vec<_>>());    assert_eq!(bed.body_of("n-04").as_deref(), Some("An invented note"));}/// RULE (FIRST SYNC 2 REVIEW: one row that opens but whose fold is refused kept its place at the front, so every/// batch was full and asked for more, a second apart, for as long as the app ran): a tried row goes behind, the rest/// open, and once only tried rows are left no pass ends behind.#[test]fn a_row_that_opens_but_never_stands_goes_behind_and_asks_no_more() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, notes(7));    keys.hold(WORKSPACE, &dk());    // A whole batch of rows the copy refuses, at the front: on the old order they filled every batch for good.    bed.replica.lock().expect("the copy").driver.connection().execute_batch("CREATE TRIGGER invented_refusal BEFORE INSERT ON cotton_garden_note WHEN NEW.id IN ('n-00', 'n-01', 'n-02') BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END").expect("the trigger");    let mut behind = Vec::new();    for _ in 0..6 {        behind.push(pass_batched(&bed, &sealer, json!([]), 3).unwrap_or(true));    }    assert_eq!(bed.parked().iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), vec!["n-00", "n-01", "n-02"], "every other row opened");    assert!(bed.parked().iter().all(|r| r.tried() && r.code == crate::seal::FOLD_REFUSED), "named refused, behind the rest");    assert_eq!(behind.last(), Some(&false), "no pass back for them: {behind:?}");    assert_eq!(behind.iter().skip_while(|b| **b).filter(|b| **b).count(), 0, "once settled, never behind again: {behind:?}");    // The copy takes them again: a later pass opens them.    refuse_note(&bed, None);    let _ = pass_batched(&bed, &sealer, json!([]), 3);    assert!(bed.parked().is_empty());}/// RULE (FIRST SYNC 2 REVIEW): a tried row is behind every row not yet tried, whatever the clock said when they were/// parked: a park from a page with no time ("") or a slow phone clock never stays at the front.#[test]fn a_tried_row_sorts_behind_every_untried_one() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, notes(4));    keys.hold(WORKSPACE, &dk());    {        let copy = bed.replica.lock().expect("the copy");        copy.driver.connection().execute_batch("UPDATE _seal_parked SET at = '' WHERE row_id = 'n-00'; UPDATE _seal_parked SET at = '1999-01-01T00:00:00Z' WHERE row_id = 'n-01'").expect("the clocks");    }    refuse_note(&bed, Some("n-00"));    let _ = pass_batched(&bed, &sealer, json!([]), 1);    let file = bed.replica.lock().expect("the copy");    let next: Vec<String> = crate::seal::parked_next(file.driver.connection(), &[], 10).expect("the queue").into_iter().map(|r| r.id).collect();    assert_eq!(next.last().map(String::as_str), Some("n-00"), "tried, behind the rest: {next:?}");}/// RULE (FIRST SYNC 2 REVIEW): last write wins inside one fold. A row parked at version 1 opens beside the same row/// the page brings at version 2: version 2 stands, whatever order they fold in.#[test]fn a_parked_row_and_its_newer_version_in_one_fold_leave_the_newer() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, vec![served_row("n-1", 1, stored(&dk(), "n-1", 1, "The first words"))]);    keys.hold(WORKSPACE, &dk());    let newer = json!([{"table": TABLE, "id": "n-1", "version": 2, "owner": null, "data": stored(&dk(), "n-1", 1, "The newer words"), "created_at": NOW, "updated_at": "2026-11-21T12:00:00Z"}]);    pass_batched(&bed, &sealer, newer, 5).expect("a pass");    assert_eq!(bed.body_of("n-1").as_deref(), Some("The newer words"));    assert!(bed.parked().is_empty());}/// RULE (FIRST SYNC 2 REVIEW): a row of a table that is not late, which opens but whose fold is refused, never holds/// the late tables (mail) back: they open on the pass after it was tried, and no pass ends behind for it after that.#[test]fn a_refused_row_ahead_of_the_late_tables_never_holds_them() {    let bed = bed();    let kit = Arc::new(cotton_core::kit::AppKit {        id: "garden".into(), tools: Vec::new(), tables: vec![TABLE.into(), PLOT.into()], folds: Vec::new(), aside: Vec::new(),        fan_of: None, acts: Vec::new(), face: None, signals: false, only: Default::default(), window: Default::default(), all_history: Vec::new(),        late: vec![TABLE.into()],    });    let mut row = Map::new();    row.insert("noted_on".into(), json!("2026-11-10"));    row.insert("body".into(), json!("The bean row"));    row.insert("mood".into(), json!("calm"));    let plot = json!({"table": PLOT, "id": "p-1", "version": 1, "owner": null, "data": cotton_core::seal::seal_row(&dk(), WORKSPACE, PLOT, "p-1", 1, &spec(), &row, None).expect("a sealed row"), "created_at": NOW, "updated_at": NOW});    let both = || Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition(), plot_definition()], "flavour": {}, "boards": [], "etag": "e1"}).to_string());    let (keys, sealer) = sealer_with(None);    let exchange = ScriptedExchange::new([page(json!([served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS)), plot]), 1), both()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    bed.pass(&mut object);    assert_eq!(bed.parked().len(), 2);    bed.replica.lock().expect("the copy").driver.connection().execute_batch("CREATE TRIGGER invented_refusal BEFORE INSERT ON cotton_garden_plot BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END").expect("the trigger");    keys.hold(WORKSPACE, &dk());    let mut behind = Vec::new();    for _ in 0..4 {        let exchange = ScriptedExchange::new([again_page(json!([]), 1, &kit), both()]);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));        behind.push(run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW).map(|report| report.behind).unwrap_or(true));    }    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS), "the late row opened: {behind:?}");    assert_eq!(bed.parked().iter().map(|r| r.table.as_str()).collect::<Vec<_>>(), vec![PLOT], "the refused row keeps its park");    assert_eq!(behind.last(), Some(&false), "{behind:?}");}/// RULE (FIRST SYNC 3 REVIEW): a batch-full of stuck rows of a table that is not late never holds the late tables/// (mail) out: once tried they sort behind every untried row, the mail's included.#[test]fn a_batch_of_stuck_rows_ahead_of_the_mail_never_holds_it_out() {    let bed = bed();    let kit = Arc::new(cotton_core::kit::AppKit {        id: "garden".into(), tools: Vec::new(), tables: vec![TABLE.into(), PLOT.into()], folds: Vec::new(), aside: Vec::new(),        fan_of: None, acts: Vec::new(), face: None, signals: false, only: Default::default(), window: Default::default(), all_history: Vec::new(),        late: vec![TABLE.into()],    });    let plot = |id: &str| {        let mut row = Map::new();        row.insert("noted_on".into(), json!("2026-11-10"));        row.insert("body".into(), json!("The bean row"));        row.insert("mood".into(), json!("calm"));        json!({"table": PLOT, "id": id, "version": 1, "owner": null, "data": cotton_core::seal::seal_row(&dk(), WORKSPACE, PLOT, id, 1, &spec(), &row, None).expect("a sealed row"), "created_at": NOW, "updated_at": NOW})    };    let both = || Reply::ok(&json!({"business": {"kind": "personal"}, "tools": [], "tables": [definition(), plot_definition()], "flavour": {}, "boards": [], "etag": "e1"}).to_string());    let (keys, sealer) = sealer_with(None);    let rows = json!([plot("p-1"), plot("p-2"), plot("p-3"), served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS)), served_row("n-2", 1, stored(&dk(), "n-2", 1, "A second invented note"))]);    let exchange = ScriptedExchange::new([page(rows, 1), both()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));    bed.pass(&mut object);    assert_eq!(bed.parked().len(), 5);    bed.replica.lock().expect("the copy").driver.connection().execute_batch("CREATE TRIGGER invented_refusal BEFORE INSERT ON cotton_garden_plot BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END").expect("the trigger");    keys.hold(WORKSPACE, &dk());    super::REOPEN_TEST.with(|cell| cell.set(Some(3)));    let mut behind = Vec::new();    for _ in 0..4 {        let exchange = ScriptedExchange::new([again_page(json!([]), 1, &kit), both()]);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).keeping_to(Some(Arc::clone(&kit)));        behind.push(run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW).map(|report| report.behind).unwrap_or(true));    }    super::REOPEN_TEST.with(|cell| cell.set(None));    assert_eq!(bed.body_of("n-1").as_deref(), Some(SECRET_WORDS), "the mail got in past a batch of stuck rows: {behind:?}");    assert_eq!(bed.body_of("n-2").as_deref(), Some("A second invented note"));    assert_eq!(bed.parked().iter().filter(|r| r.table == PLOT).count(), 3, "the stuck rows keep their parks");    assert_eq!(behind.last(), Some(&false), "{behind:?}");}/// RULE (FIRST SYNC 3 REVIEW): rows tried before that open now (their key came) are progress: a full batch of them/// brings the pass straight back, so the rest follow at once.#[test]fn tried_rows_that_open_now_bring_the_pass_back() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, notes(4));    bed.replica.lock().expect("the copy").driver.connection().execute_batch("UPDATE _seal_parked SET at = '~00000000000000000001'").expect("tried before");    keys.hold(WORKSPACE, &dk());    assert_eq!(pass_batched(&bed, &sealer, json!([]), 3), Ok(true), "a full batch of tried rows that opened: back at once");    assert_eq!(bed.parked().len(), 1);    assert_eq!(pass_batched(&bed, &sealer, json!([]), 3), Ok(false));    assert!(bed.parked().is_empty());}/// A kept wrap made unopenable: `id`'s wrap replaced by one another database's key made (a copy made again).fn keep_a_former_wrap(bed: &Bed, id: &str) {    let former = stored(&DataKey::from_bytes([9; 32]), id, 1, "a former database's words");    let copy = bed.replica.lock().expect("the copy");    copy.driver        .run("UPDATE _seal SET dek_enc = ? WHERE tbl = ? AND row_id = ?", &[rusqlite::types::Value::Text(former["dek_enc"].as_str().expect("a wrap").into()), rusqlite::types::Value::Text(TABLE.into()), rusqlite::types::Value::Text(id.into())])        .expect("the former wrap kept");}fn last_error(bed: &Bed) -> Option<String> {    bed.replica.lock().expect("the copy").driver.get("SELECT last_error FROM _outbox LIMIT 1", &[]).expect("a read").and_then(|row| row.text("last_error").map(str::to_string))}/// Two notes sent, then `n-1`'s kept wrap made a former database's and an edit of it passed: with the row's version/// read from a pull first (`with_version`), or never read.fn former_wrap_bed(with_version: bool) -> (Bed, Arc<ScriptedExchange>) {    let (bed, sealer) = two_notes_sent(with_version);    keep_a_former_wrap(&bed, "n-1");    let mut patch = Map::new();    patch.insert("body".into(), "An edit after the copy was made again".into());    edit(&bed, "cotton_garden_note", "n-1", patch);    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 2)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    (bed, exchange)}/// Two notes sealed and sent, so this device's key is proven by their wraps; `with_version`: `n-1` then read back/// from a pull at version 2.fn two_notes_sent(with_version: bool) -> (Bed, Arc<Sealer>) {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), act_taken(), act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    bed.write("n-1", SECRET_WORDS);    {        let copy = bed.replica.lock().expect("the copy");        let mut patch = Map::new();        for (column, value) in [("workspace_id", WORKSPACE), ("noted_on", "2026-11-11"), ("body", "the other note"), ("mood", "calm"), ("created_at", NOW), ("updated_at", NOW)] {            patch.insert(column.into(), value.into());        }        let mut ids = crate::seams::op_ids(Arc::new(crate::seams::SeededRandom::new(21)));        cotton_store::mint::mint(            &copy.driver,            &cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")), verb: "add_note".into(), history: cotton_store::mint::History::None, changes: vec![cotton_store::mint::Change::create("cotton_garden_note", "n-2", patch)] },            &cotton_store::mint::clock::writer_clock(&copy.driver, 1_762_000_050_000, &mut ids).expect("the copy's clock"),            &mut ids,            cotton_store::mint::Held::Replica,        )        .expect("a second note");    }    bed.pass(&mut object);    assert_eq!(bed.pending(), 0);    if with_version {        // The object's row comes back at version 2: this phone now holds the version it read.        let created = body(&exchange.nth(2))["args"]["data"].clone();        let exchange = ScriptedExchange::new([page(json!([served_row("n-1", 2, created)]), 2), served()]);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));        bed.pass(&mut object);    }    (bed, sealer)}fn posted_over_a_row(exchange: &ScriptedExchange) -> bool {    exchange.seen().iter().filter_map(|seen| serde_json::from_slice::<Value>(&seen.body).ok()).any(|sent| ["create", "update", "seal"].contains(&sent["act"].as_str().unwrap_or_default()))}/// RULE (UNSENT HEAL 2 review, follow-up 1): a create (an op handed over again, or an undo of a delete, which goes as/// a create and becomes an update on `duplicate_id`) is never held to a version: a kept wrap that no longer opens is/// refused `seal_does_not_open`, though the key is proven, and nothing is posted over the row.#[test]fn a_create_never_reseals_a_wrap_that_does_not_open() {    let (bed, sealer) = two_notes_sent(false);    bed.write("n-3", "a third invented note");    {        // The row's wrap is kept already, as for a row handed over again: a former database's.        let former = stored(&DataKey::from_bytes([9; 32]), "n-3", 1, "a former database's words");        let copy = bed.replica.lock().expect("the copy");        copy.driver            .run("INSERT OR REPLACE INTO _seal (tbl, row_id, sealed, dek_enc, seal_v, version) VALUES (?, 'n-3', 1, ?, 1, 0)", &[rusqlite::types::Value::Text(TABLE.into()), rusqlite::types::Value::Text(former["dek_enc"].as_str().expect("a wrap").into())])            .expect("the former wrap kept");    }    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 2)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.pending(), 1);    assert!(last_error(&bed).is_some_and(|error| error.starts_with("seal_does_not_open")), "{:?}", last_error(&bed));    assert!(!posted_over_a_row(&exchange), "nothing posted over the row");}/// RULE (UNSENT HEAL 2 review, follow-up 1): the row a refused write links to, sent first as it stands here/// (`send_row`, a create that becomes an update), is never held to a version: its kept wrap that no longer opens is/// refused, though the key is proven, and nothing is posted.#[test]fn a_linked_row_sent_first_never_reseals_a_wrap_that_does_not_open() {    let (bed, sealer) = two_notes_sent(true);    // A pass with nothing queued: this transport's map takes the notes table from the definitions.    let exchange = ScriptedExchange::new([page(json!([]), 2), served(), act_taken(), act_taken()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let before = exchange.calls();    keep_a_former_wrap(&bed, "n-1");    let copy = bed.replica.lock().expect("the copy");    let map = object.map();    assert!(map.ours("cotton_garden_note").is_some(), "the table is mapped");    let refused = object.send_row(copy.driver.connection(), &map, "cotton_garden_note", "n-1").expect("the copy answers").expect_err("refused");    assert_eq!(exchange.calls(), before, "nothing posted");    assert_eq!(refused.code, "seal_does_not_open");    assert!(!posted_over_a_row(&exchange), "nothing posted over the row");}/// RULE (UNSENT HEAL, 26 Nov 2026; UNSENT HEAL 2, review item 1): a row whose kept wrap no longer opens (a former/// database's) was refused `seal_does_not_open` on every pass for good. Once another kept wrap opens with this/// device's key, and the post is held to the version this phone read, the edit goes sealed whole under a fresh DEK.#[test]fn an_edit_whose_kept_wrap_no_longer_opens_goes_under_a_fresh_key_once_the_key_is_proven() {    let (bed, exchange) = former_wrap_bed(true);    assert_eq!(bed.pending(), 0, "the edit went: {:?}", last_error(&bed));    let sent = body(&exchange.nth(0));    assert_eq!((sent["act"].as_str(), sent["args"]["expect_version"].as_i64()), (Some("seal"), Some(2)), "held to the version read");    let data = sent["args"]["data"].as_object().expect("the edit's data");    assert_eq!(cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", data).expect("opens with this database's key")["body"], "An edit after the copy was made again");}/// RULE (UNSENT HEAL 2, review item 1): where the post is not held to a version this phone read, an old wrap says/// this copy may be out of date; the whole sealed copy would replace a newer row, so it is never healed there: it/// waits by name and is shown.#[test]fn an_unguarded_post_never_heals_a_wrap_that_does_not_open() {    let (bed, exchange) = former_wrap_bed(false);    assert_eq!(bed.pending(), 1);    assert!(last_error(&bed).is_some_and(|error| error.starts_with("seal_does_not_open")), "{:?}", last_error(&bed));    let posted = exchange.seen().iter().filter_map(|seen| serde_json::from_slice::<Value>(&seen.body).ok()).any(|sent| sent["act"] == "update" || sent["act"] == "seal");    assert!(!posted, "nothing posted over the row");}/// RULE (UNSENT HEAL): with no other wrap that opens, the key is not proven, so nothing is sealed under it. The edit/// waits by name (`seal_does_not_open`), and the person is told (`unsent_heal`).#[test]fn an_unproven_key_never_seals_over_a_wrap_that_does_not_open() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    bed.write("n-1", SECRET_WORDS);    bed.pass(&mut object);    keep_a_former_wrap(&bed, "n-1");    let mut patch = Map::new();    patch.insert("body".into(), "An edit that must wait".into());    edit(&bed, "cotton_garden_note", "n-1", patch);    let exchange = ScriptedExchange::new([page(json!([]), 2)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert_eq!(bed.pending(), 1);    assert!(last_error(&bed).is_some_and(|error| error.starts_with("seal_does_not_open")), "{:?}", last_error(&bed));}/// RULE (FIRST SYNC 4 REVIEW): parks of a table this copy no longer maps (an app update that dropped it) open/// nothing and are no progress: a full batch of them never brings the pass back.#[test]fn parks_of_a_table_no_longer_mapped_never_bring_the_pass_back() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, notes(4));    bed.replica        .lock()        .expect("the copy")        .driver        .connection()        .execute_batch("UPDATE _seal_parked SET tbl = 'cotton_garden_vanished', at = '~00000000000000000001'")        .expect("a table the copy no longer maps");    keys.hold(WORKSPACE, &dk());    assert_eq!(pass_batched(&bed, &sealer, json!([]), 3), Ok(false), "no pass back for rows that open nothing");    assert_eq!(pass_batched(&bed, &sealer, json!([]), 3), Ok(false));    assert_eq!(bed.parked().len(), 4, "kept by name, never dropped");}/// RULE (FIRST SYNC 4 REVIEW): among rows already tried, the longest ago comes first whatever its table: tried mail/// is never kept out by stuck rows of another table tried after it.#[test]fn tried_rows_come_longest_ago_first_whatever_their_table() {    let bed = bed();    let _ = parked_before_the_key(&bed, notes(4));    let copy = bed.replica.lock().expect("the copy");    let db = copy.driver.connection();    db.execute_batch(        "UPDATE _seal_parked SET tbl = 'cotton_garden_plot', at = '~00000000000000000002' WHERE row_id IN ('n-00', 'n-01', 'n-02');         UPDATE _seal_parked SET at = '~00000000000000000001' WHERE row_id = 'n-03';",    )    .expect("tried rows");    let next: Vec<String> = crate::seal::parked_next(db, &[TABLE.to_string()], 3).expect("the queue").into_iter().map(|r| r.id).collect();    assert_eq!(next.first().map(String::as_str), Some("n-03"), "the late table's row tried longest ago first: {next:?}");}/// RULE (FIRST SYNC 5, dev 26 Nov 2026: 8,190 of 10,301 mails opened before their conversations, were refused by the/// fold for a thread not yet there, and opened again later): among untried rows, a kit's tables come in its own order,/// a parent before what names it, whatever the order they were parked in.#[test]fn untried_rows_come_in_the_kits_order_parents_first() {    let bed = bed();    let _ = parked_before_the_key(&bed, notes(4));    let copy = bed.replica.lock().expect("the copy");    let db = copy.driver.connection();    // The parent's rows parked after the children's (a later page).    db.execute_batch(&format!(        "UPDATE _seal_parked SET tbl = '{PLOT}', at = '2026-11-21T12:00:00Z' WHERE row_id IN ('n-02', 'n-03');         UPDATE _seal_parked SET at = '2026-11-21T10:00:00Z' WHERE row_id IN ('n-00', 'n-01');"    ))    .expect("parks");    let order = [PLOT.to_string(), TABLE.to_string()];    let next: Vec<String> = crate::seal::parked_next_in(db, &[], &order, 4).expect("the queue").into_iter().map(|r| r.id).collect();    assert_eq!(next, ["n-02", "n-03", "n-00", "n-01"], "the parent table first, though parked later");    // Tried rows keep longest ago first whatever their table.    db.execute_batch(&format!("UPDATE _seal_parked SET at = '~00000000000000000002' WHERE tbl = '{PLOT}'; UPDATE _seal_parked SET at = '~00000000000000000001' WHERE tbl <> '{PLOT}'")).expect("tried");    let next: Vec<String> = crate::seal::parked_next_in(db, &[], &order, 4).expect("the queue").into_iter().map(|r| r.id).collect();    assert_eq!(next, ["n-00", "n-01", "n-02", "n-03"]);}/// RULE (HIDDEN 6, review 5 and M2; two devices): a change of a table held to its version (a list, whose sealed/// `hidden` another phone set) on a copy that holds no version for the row (no `_seal` row at all: pulled before the/// table was sealed) is never posted as an unheld whole-row reseal, and never waits for good: the transport reads that/// one row from the object, lays its own change over what the object holds, and sends it as `seal` held to that version.#[test]fn a_change_held_to_its_version_reads_the_row_and_never_seals_over_another_devices_row() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let row = |version: i64, mood: &str| {        let mut plain = Map::new();        plain.insert("noted_on".into(), json!("2026-11-10"));        plain.insert("body".into(), json!("Weekend films"));        plain.insert("mood".into(), json!(mood));        let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, TABLE, "n-1", 1, &spec(), &plain, None).expect("a sealed row");        served_row("n-1", version, Value::Object(sealed))    };    let exchange = ScriptedExchange::new([page(json!([row(3, "open")]), 3), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).holding_to_version(TABLE);    bed.pass(&mut object);    // This copy holds the row but no seal state for it at all.    bed.replica.lock().expect("the copy").driver.run("DELETE FROM _seal WHERE row_id = 'n-1'", &[]).expect("no version held");    let mut words = Map::new();    words.insert("body".into(), json!("Late films"));    edit(&bed, "cotton_garden_note", "n-1", words);    // Meanwhile the other device changed a sealed column there: version 5.    let held = Reply::ok(&json!({"table": TABLE, "rows": [row(5, "hidden by the other phone")]}).to_string());    let exchange = ScriptedExchange::new([held, act_taken(), page(json!([]), 5)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).holding_to_version(TABLE);    bed.pass(&mut object);    let asked = exchange.nth(0);    assert!(asked.path.starts_with("/v1/rows?table=garden_note&ids=n-1"), "{}", asked.path);    let sent = body(&exchange.nth(1));    assert_eq!((sent["act"].as_str(), sent["args"]["expect_version"].as_i64()), (Some("seal"), Some(5)), "held to the version read from the object");    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", sent["args"]["data"].as_object().expect("data")).expect("opens");    assert_eq!((opened["body"].as_str(), opened["mood"].as_str()), (Some("Late films"), Some("hidden by the other phone")), "its edit, over the other device's sealed column");    assert_eq!(bed.pending(), 0, "it went through");    assert_eq!(crate::seal::held_version(bed.replica.lock().expect("the copy").driver.connection(), TABLE, "n-1").expect("read").filter(|v| *v > 0), None, "the read's version is never kept: this copy does not hold the other device's column (UNSENT HEAL 5); the pull brings the row with its version");}/// RULE (HIDDEN 6, review 5): every list a pull brings keeps the version it came at (above 0), so an edit of it goes/// held to that version at once and never waits on `held_to_version`.#[test]fn a_pulled_list_holds_its_version_and_its_edit_goes_held_to_it() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let definition: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/record_group.json")).expect("the lists' definition");    let spec = crate::seal::spec_of_definition(&definition).expect("a seal block").expect("lists are sealed");    let store = ObjectTables::personal().with_defined([&definition]).expect("a map").object("record_group").expect("mapped").store.clone();    let id = "33333333-4444-4555-8666-777777777777";    let held = json!({"table_id": "film", "name": "Invented Late Films", "hidden": true, "position": 1.0});    let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, "record_group", id, 1, &spec, held.as_object().expect("fields"), None).expect("a sealed row");    assert_eq!(sealed.get("hidden"), Some(&json!(true)), "a category's hidden flag is clear on the row");    let row = json!({"table": "record_group", "id": id, "version": 7, "owner": null, "data": sealed, "created_at": NOW, "updated_at": NOW});    let exchange = ScriptedExchange::new([page(json!([row]), 7), served_definition(&definition)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let version = crate::seal::held_version(bed.replica.lock().expect("the copy").driver.connection(), "record_group", id).expect("read");    assert_eq!(version, Some(7), "the list keeps the version it came at");    let mut name = Map::new();    name.insert("name".into(), json!("Invented Later Films"));    edit(&bed, &store, id, name);    let exchange = ScriptedExchange::new([act_taken(), page(json!([]), 7)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    let sent = body(&exchange.nth(0));    assert_eq!((sent["act"].as_str(), sent["args"]["expect_version"].as_i64()), (Some("seal"), Some(7)));    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, "record_group", id, sent["args"]["data"].as_object().expect("data")).expect("opens");    assert_eq!(opened["name"].as_str(), Some("Invented Later Films"));    // The flag is clear (HIDE FROM SCREEN: synced, never sealed): the rename keeps it, on what it sends when it sends    // it, and on this phone's copy.    if let Some(flag) = opened.get("hidden").or_else(|| sent["args"]["data"].get("hidden")) {        assert!(flag == &json!(true) || flag == &json!(1), "the rename sends the flag as it was: {sent}");    }    let kept: i64 = bed.replica.lock().expect("the copy").driver.connection().query_row("SELECT hidden FROM cotton_groups WHERE id = ?1", [id], |row| row.get(0)).expect("the list on this copy");    assert_eq!(kept, 1, "the rename keeps the flag on this copy");    assert_eq!(bed.pending(), 0);}/// FIRST SYNC FAST's measure (ignored; run by hand with COTTON_SYNC_TIMES=1): a page of 5,000 really sealed rows of/// about 3 KB, the key held, folded through the transport: the unseal, the ops and the fold, per row, on this machine.#[test]#[ignore]fn timed_a_page_of_sealed_rows_with_the_key() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let words = "Invented words for a timing, nothing more. ".repeat(70);    let rows: Vec<Value> = (0..5_000).map(|n| served_row(&format!("n-{n}"), 2 + n, stored(&dk(), &format!("n-{n}"), 1, &words))).collect();    let bytes = serde_json::to_vec(&rows).unwrap().len();    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), page(Value::Array(rows), 5_002), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    if let Ok(pages) = std::env::var("COTTON_TIMED_CHECKPOINT") {        bed.replica.lock().expect("the copy").driver.exec(&format!("PRAGMA wal_autocheckpoint = {pages}")).expect("the pragma");    }    let _ = cotton_store::spans::take();    let began = std::time::Instant::now();    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let took = began.elapsed();    for (name, took, count) in cotton_store::spans::take() {        println!("SPAN {name}: {} ms over {count}", took.as_millis());    }    let held = bed.replica.lock().expect("the copy").driver.get("SELECT COUNT(*) AS n FROM cotton_garden_note", &[]).expect("a count").and_then(|row| row.int("n"));    println!("TIMED 5,000 sealed rows ({bytes} bytes): {:.2}s, {:.0} rows/s, {held:?} held, {} parked", took.as_secs_f64(), 5_000.0 / took.as_secs_f64(), bed.parked().len());}/// RULE (FIRST SYNC FAST, 26 Nov 2026: on the box, SQLite's checkpoint on each page's commit was most of a keyed/// page's time): while a pull has pages to come its commits take no checkpoint, and the pull's last page gives the/// copy its checkpoint back.#[test]fn a_long_pull_holds_the_checkpoint_until_its_last_page() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let autocheckpoint = |bed: &Bed| bed.replica.lock().expect("the copy").driver.get("PRAGMA wal_autocheckpoint", &[]).expect("a read").and_then(|row| row.columns().first().and_then(|(_, value)| match value {        rusqlite::types::Value::Integer(pages) => Some(*pages),        _ => None,    }));    let mut first = json!({"version": 1, "rows": [served_row("n-1", 1, stored(&dk(), "n-1", 1, SECRET_WORDS))], "server_time": NOW});    first["next"] = json!("two");    let failed = Reply::json(500, r#"{"code": "internal", "message": "the object failed"}"#);    let exchange = ScriptedExchange::new([Reply::ok(&first.to_string()), served(), failed]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    let _ = run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW);    assert_eq!(autocheckpoint(&bed), Some(0), "pages to come: no checkpoint on each commit");    let exchange = ScriptedExchange::new([page(json!([served_row("n-2", 2, stored(&dk(), "n-2", 1, SECRET_WORDS))]), 2), served()]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    assert_eq!(autocheckpoint(&bed), Some(1000), "the last page gives the checkpoint back");    assert_eq!(bed.body_of("n-2").as_deref(), Some(SECRET_WORDS));}// ── FIRST SYNC 6: a mail whose conversation is not here yet ─────────────────fn mail_spec(table: &str) -> SealSpec {    ObjectTables::personal().object(table).and_then(|table| table.seal.clone()).expect("the kit seals it")}fn sealed_mail(table: &str, id: &str, fields: Value) -> Value {    let row = fields.as_object().cloned().expect("fields");    let data = cotton_core::seal::seal_row(&dk(), WORKSPACE, table, id, 1, &mail_spec(table), &row, None).expect("a sealed row");    json!({"table": table, "id": id, "version": 1, "owner": null, "data": Value::Object(data), "created_at": NOW, "updated_at": NOW})}fn invented_mail(id: &str, thread: &str) -> Value {    sealed_mail("email", id, json!({"thread_id": thread, "external_id": format!("<{id}@invented.example>"), "subject": "The lake", "from_email": "ada@invented.example", "sent_at": NOW, "body": "An invented mail."}))}fn invented_thread(id: &str) -> Value {    sealed_mail("email_thread", id, json!({"external_key": format!("invented:{id}"), "subject": "The lake", "email_count": 2, "first_at": NOW, "last_at": NOW}))}/// A page with more to come (`next`), so the pull has not reached the object's end.fn page_more(rows: Value, version: i64) -> Reply {    Reply::ok(&json!({"version": version, "rows": rows, "server_time": NOW, "next": format!("c-{version}")}).to_string())}fn mail_pass(bed: &Bed, sealer: &Arc<Sealer>, reply: Reply) {    let exchange = ScriptedExchange::new([reply, served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(sealer)));    run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW).expect("a pass");}/// A pass whose pull stops short of the object's end: one page with more to come folds, and the next is refused (a/// pass cut off half way, as a phone's often is), so the pull never reaches the end.fn mail_pass_short(bed: &Bed, sealer: &Arc<Sealer>, rows: Value, version: i64) {    // The definitions are asked once, on the first pass that pages after the park; the copy holds them after.    let first = !bed.held_definitions_asked.swap(true, std::sync::atomic::Ordering::SeqCst);    let outage = || Reply::new(503, br#"{"code":"invented_outage"}"#.to_vec());    let exchange = if first { ScriptedExchange::new([page_more(rows, version), served(), outage()]) } else { ScriptedExchange::new([page_more(rows, version), outage()]) };    let mut object = bed.transport(&exchange, Some(Arc::clone(sealer)));    let _ = run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW);}fn parks_of(bed: &Bed, table: &str) -> Vec<(String, String, String)> {    let copy = bed.replica.lock().expect("the copy");    let parks: Vec<(String, String, String)> = copy.driver        .connection()        .prepare("SELECT row_id, code, at FROM _seal_parked WHERE tbl = ?1 ORDER BY row_id")        .expect("parks")        .query_map([table], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))        .expect("parks")        .collect::<Result<_, _>>()        .expect("parks");    parks}fn mails_standing(bed: &Bed) -> i64 {    let copy = bed.replica.lock().expect("the copy");    copy.driver.connection().query_row("SELECT count(*) FROM cotton_emails", [], |row| row.get(0)).expect("a count")}/// RULE (FIRST SYNC 6, the coordinator 26 Nov 2026): a parked mail whose conversation is not in the copy folds/// dormant: its park stays, named `waiting_parent` (never `fold_refused`), and it is not opened again on each pass./// When its conversation folds in a later page the mail stands, and its park goes on the next batch. Counted apart/// from refusals.#[test]fn a_mail_whose_conversation_comes_in_a_later_page_waits_then_stands() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, vec![invented_mail("e-1", "th-1"), invented_mail("e-2", "th-1")]);    assert_eq!(parks_of(&bed, "email").len(), 2);    keys.hold(WORKSPACE, &dk());    // The key held: the batch opens both; their conversation is not here, so they fold dormant and wait.    mail_pass_short(&bed, &sealer, json!([]), 2);    let waiting = parks_of(&bed, "email");    assert_eq!(waiting.len(), 2, "the parks stay until the rows stand: {waiting:?}");    assert!(waiting.iter().all(|(_, code, at)| code == crate::seal::WAITING_PARENT && at.starts_with(crate::seal::WAITING)), "{waiting:?}");    assert_eq!(mails_standing(&bed), 0, "dormant: no table row yet");    {        let copy = bed.replica.lock().expect("the copy");        let counts = crate::seal::parked_by_code(copy.driver.connection()).expect("counts");        assert_eq!(counts, Some(vec![(crate::seal::WAITING_PARENT.to_string(), 2)]), "counted apart, never as refused");    }    // A page with no row of their conversation: they are not opened again (their mark is untouched).    mail_pass_short(&bed, &sealer, json!([]), 3);    assert_eq!(parks_of(&bed, "email"), waiting, "not opened again while nothing of their parent came");    // The conversation comes in a later page: the store makes the mails from their kept receipts, and the waiting    // rows go back to the batches.    mail_pass_short(&bed, &sealer, json!([invented_thread("th-1")]), 4);    assert_eq!(mails_standing(&bed), 2, "the conversation's arrival made both mails");    assert!(parks_of(&bed, "email").iter().all(|(_, _, at)| at == "~"), "woken, first among the tried: {:?}", parks_of(&bed, "email"));    // The next batch finds them standing and lets the parks go.    mail_pass(&bed, &sealer, page(json!([]), 5));    assert!(parks_of(&bed, "email").is_empty(), "{:?}", parks_of(&bed, "email"));    assert_eq!(mails_standing(&bed), 2);}/// RULE (FIRST SYNC 6 REVIEW (2)): a pull that reaches the object's end tries the waiting rows once more at most/// once a day, BEHIND every tried row; a row whose conversation is still missing waits again, its park kept.#[test]fn a_caught_up_pull_tries_the_waiting_rows_once_a_day_behind_the_tried() {    let bed = bed();    let alien = DataKey::from_bytes([9; 32]);    let (keys, sealer) = parked_before_the_key(&bed, vec![invented_mail("e-9", "th-none"), served_row("a-1", 1, stored(&alien, "a-1", 1, "Elsewhere"))]);    keys.hold(WORKSPACE, &dk());    mail_pass_short(&bed, &sealer, json!([]), 2);    assert!(parks_of(&bed, "email")[0].2.starts_with(crate::seal::WAITING));    let tried = parks_of(&bed, TABLE)[0].2.clone();    assert!(tried.starts_with('~'), "the row of another key was tried: {tried}");    // Caught up: woken after the fold, behind the tried row.    mail_pass(&bed, &sealer, page(json!([]), 3));    let woken = parks_of(&bed, "email")[0].2.clone();    assert!(woken.starts_with('~') && woken > tried, "behind every tried row: {woken} after {tried}");    // Tried again on the next pass, still dormant: waits again, park kept.    mail_pass_short(&bed, &sealer, json!([]), 4);    let parks = parks_of(&bed, "email");    assert_eq!((parks.len(), parks[0].1.as_str()), (1, crate::seal::WAITING_PARENT));    assert!(parks[0].2.starts_with(crate::seal::WAITING), "{parks:?}");    // Another pull to the end the same day: not woken again.    mail_pass(&bed, &sealer, page(json!([]), 5));    assert!(parks_of(&bed, "email")[0].2.starts_with(crate::seal::WAITING), "once a day: {:?}", parks_of(&bed, "email"));    // A day on (the last wake kept a day back): woken again.    bed.replica.lock().expect("the copy").driver.connection().execute("UPDATE _seal_waiting SET mark = mark - ?1 WHERE tbl = '*'", [crate::seal::WAKE_AT_END_EVERY_MS]).expect("a day back");    mail_pass(&bed, &sealer, page(json!([]), 6));    assert!(!parks_of(&bed, "email")[0].2.starts_with(crate::seal::WAITING), "a day on: woken");}/// RULE (FIRST SYNC 6 REVIEW): a conversation that arrives through the reopen fold (itself parked before the key)/// makes its waiting mails, which go on the next batch.#[test]fn a_conversation_that_comes_through_the_reopen_fold_frees_its_mails() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, vec![invented_mail("e-1", "th-1")]);    keys.hold(WORKSPACE, &dk());    mail_pass_short(&bed, &sealer, json!([]), 2);    assert_eq!(parks_of(&bed, "email")[0].1, crate::seal::WAITING_PARENT);    // The conversation comes while no key is held (a key forgotten, say): parked, untried.    keys.forget(WORKSPACE);    mail_pass_short(&bed, &sealer, json!([invented_thread("th-1")]), 3);    assert_eq!(parks_of(&bed, "email_thread").len(), 1, "the conversation parked");    // The key again: the batch opens the conversation; its fold makes the mail.    keys.hold(WORKSPACE, &dk());    mail_pass_short(&bed, &sealer, json!([]), 4);    assert!(parks_of(&bed, "email_thread").is_empty());    assert_eq!(mails_standing(&bed), 1, "the mail made from its kept receipt");    mail_pass_short(&bed, &sealer, json!([]), 5);    assert!(parks_of(&bed, "email").is_empty(), "{:?}", parks_of(&bed, "email"));}/// RULE (FIRST SYNC 6 REVIEW): a copy that labelled a dormant mail fold_refused (FIRST SYNC 4 and 5) relabels it/// waiting_parent the next time it is tried.#[test]fn a_mail_labelled_fold_refused_by_an_older_build_waits_once_tried() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, vec![invented_mail("e-1", "th-1")]);    bed.replica.lock().expect("the copy").driver.connection().execute_batch(        "UPDATE _seal_parked SET code = 'fold_refused', reason = 'it opened, and this copy refused it as it folded; tried again on a later pass', at = '~00000000000000000003'",    ).expect("as an older build left it");    keys.hold(WORKSPACE, &dk());    mail_pass_short(&bed, &sealer, json!([]), 2);    let parks = parks_of(&bed, "email");    assert_eq!(parks[0].1, crate::seal::WAITING_PARENT, "{parks:?}");}/// RULE (FIRST SYNC 6 REVIEW): a pass whose only parks are waiting for a parent never comes straight back, nor/// does one that tries a full batch of woken rows that still wait.#[test]fn a_pass_with_only_waiting_rows_does_not_come_straight_back() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, vec![invented_mail("e-1", "th-1"), invented_mail("e-2", "th-2")]);    keys.hold(WORKSPACE, &dk());    assert!(pass_batched(&bed, &sealer, json!([]), 2).expect("a pass") == false || parks_of(&bed, "email").iter().all(|p| p.1 == crate::seal::WAITING_PARENT));    assert!(parks_of(&bed, "email").iter().all(|p| p.1 == crate::seal::WAITING_PARENT));    assert_eq!(pass_batched(&bed, &sealer, json!([]), 2), Ok(false), "only waiting rows: no straight-back pass");    bed.replica.lock().expect("the copy").driver.connection().execute_batch("UPDATE _seal_parked SET at = '~'").expect("woken");    assert_eq!(pass_batched(&bed, &sealer, json!([]), 2), Ok(false), "a full batch of woken rows that still wait: no straight-back pass");}/// RULE (FIRST SYNC 6 REVIEW (3)): a mail whose conversation IS here and whose fold is refused is refused, not/// waiting.#[test]fn a_refused_mail_whose_conversation_is_here_is_refused_not_waiting() {    let bed = bed();    let (keys, sealer) = parked_before_the_key(&bed, vec![invented_thread("th-1"), invented_mail("e-1", "th-1")]);    // A copy whose rules refuse the mail itself: its conversation folds first (parents first), and the mail's fold is    // still refused.    bed.replica.lock().expect("the copy").driver.connection().execute_batch(        "CREATE TRIGGER invented_mail_refusal BEFORE INSERT ON cotton_emails BEGIN SELECT RAISE(ABORT, 'an invented refusal'); END;",    ).expect("the trigger");    keys.hold(WORKSPACE, &dk());    mail_pass_short(&bed, &sealer, json!([]), 2);    assert!(parks_of(&bed, "email_thread").is_empty(), "the conversation stands");    let parks = parks_of(&bed, "email");    assert_eq!(parks.first().map(|p| p.1.as_str()), Some(crate::seal::FOLD_REFUSED), "{parks:?}");}/// RULE (HIDDEN 7, review 6): a change of a table held to its version, with no version held, whose row the object/// will not hand back (not live there, or it does not open), goes without a version only when this phone made the/// row; a row this phone pulled waits, held in the outbox by name (no passing code: said to the person after a day).#[test]fn a_held_change_the_object_will_not_hand_back_waits_unless_this_phone_made_the_row() {    let row = |version: i64| {        let mut plain = Map::new();        plain.insert("noted_on".into(), json!("2026-11-10"));        plain.insert("body".into(), json!("Weekend films"));        plain.insert("mood".into(), json!("open"));        served_row("n-1", version, Value::Object(cotton_core::seal::seal_row(&dk(), WORKSPACE, TABLE, "n-1", 1, &spec(), &plain, None).expect("a sealed row")))    };    let none = || Reply::ok(&json!({"table": TABLE, "rows": []}).to_string());    // Pulled from the object: it waits.    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([row(3)]), 3), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).holding_to_version(TABLE);    bed.pass(&mut object);    bed.replica.lock().expect("the copy").driver.run("DELETE FROM _seal WHERE row_id = 'n-1'", &[]).expect("no version held");    let mut words = Map::new();    words.insert("body".into(), json!("Late films"));    edit(&bed, "cotton_garden_note", "n-1", words.clone());    let exchange = ScriptedExchange::new([none(), page(json!([]), 3)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).holding_to_version(TABLE);    bed.pass(&mut object);    let acts: Vec<Value> = exchange.seen().iter().filter(|seen| seen.path.contains("/v1/act")).map(body).collect();    assert!(acts.is_empty(), "nothing went unheld: {acts:?}");    // Not live on the object, and not made here: gone, shown at once, never read again every pass (UNSENT HEAL 7,    // review 1).    assert_eq!(bed.pending(), 0, "not queued to be read for ever");    let parked = cotton_store::rejected::list_parked(&bed.replica.lock().expect("the copy").driver, 50).expect("the parks");    assert!(parked.iter().any(|park| park.reason.starts_with("row_gone")), "{parked:?}");    assert_eq!(crate::unsent_heal::stuck(&bed.replica.lock().expect("the copy").driver, i64::MAX).expect("stuck").len(), 1, "shown");    // Made on this phone, never pulled back: it goes, as its create would.    let bed = bed_made_here();    let exchange = ScriptedExchange::new([none(), act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).holding_to_version(TABLE);    edit(&bed, "cotton_garden_note", "n-1", words);    bed.pass(&mut object);    let acts: Vec<Value> = exchange.seen().iter().filter(|seen| seen.path.contains("/v1/act")).map(body).collect();    assert_eq!(acts.len(), 1, "{acts:?}");    assert_eq!(bed.pending(), 0, "taken");}/// A copy holding `n-1`, made on this phone and taken by the object, with no version read for it.fn bed_made_here() -> Bed {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([]), 1), served(), act_taken(), page(json!([]), 1)]);    let mut object = bed.transport(&exchange, Some(sealer));    bed.pass(&mut object);    bed.write("n-1", "Weekend films");    bed.pass(&mut object);    bed.replica.lock().expect("the copy").driver.run("UPDATE _seal SET version = 0 WHERE row_id = 'n-1'", &[]).expect("no version held");    bed}/// RULE (HIDDEN 8, review 7): a list this phone made, which another device has since resealed under a key this phone/// does not hold, never goes up unversioned: the object holds the row and it does not open here, so the change waits.#[test]fn a_row_made_here_that_another_device_resealed_waits() {    let bed = bed_made_here();    let (_keys, sealer) = sealer_with(Some(dk()));    let other = DataKey::from_bytes([9; 32]);    let mut plain = Map::new();    plain.insert("noted_on".into(), json!("2026-11-10"));    plain.insert("body".into(), json!("Weekend films"));    plain.insert("mood".into(), json!("resealed elsewhere"));    let resealed = served_row("n-1", 6, Value::Object(cotton_core::seal::seal_row(&other, WORKSPACE, TABLE, "n-1", 1, &spec(), &plain, None).expect("a sealed row")));    let mut words = Map::new();    words.insert("body".into(), json!("Late films"));    edit(&bed, "cotton_garden_note", "n-1", words);    let exchange = ScriptedExchange::new([Reply::ok(&json!({"table": TABLE, "rows": [resealed]}).to_string()), page(json!([]), 6)]);    let mut object = bed.transport(&exchange, Some(sealer)).holding_to_version(TABLE);    bed.pass(&mut object);    let acts: Vec<Value> = exchange.seen().iter().filter(|seen| seen.path.contains("/v1/act")).map(body).collect();    assert!(acts.is_empty(), "nothing went unheld over the other device's row: {acts:?}");    assert_eq!(bed.pending(), 1, "it waits");}/// Before the edits `edit` makes (its clock: 1_762_000_100_000 ms), and after them.const BEFORE_THE_EDIT: &str = "2025-10-31T00:00:00.000Z";const AFTER_THE_EDIT: &str = "2026-11-12T10:00:00.000Z";/// A sealed note `n-1` at `version`, as the object serves it, with `mood`, last changed before this phone's edit.fn served_note(version: i64, mood: &str) -> Value {    served_note_at(version, mood, BEFORE_THE_EDIT)}fn served_note_at(version: i64, mood: &str, changed: &str) -> Value {    let mut plain = Map::new();    plain.insert("noted_on".into(), json!("2026-11-10"));    plain.insert("body".into(), json!("The first words"));    plain.insert("mood".into(), json!(mood));    let sealed = cotton_core::seal::seal_row(&dk(), WORKSPACE, TABLE, "n-1", 1, &spec(), &plain, None).expect("a sealed row");    let mut served = served_row("n-1", version, Value::Object(sealed));    served["updated_at"] = json!(changed);    served}fn moved_answer() -> Reply {    Reply::json(409, r#"{"code": "version_moved", "message": "garden_note n-1 is at version 6, not 5"}"#)}/// RULE (UNSENT HEAL 4, the owner's Comms build 40, 26 Nov 2026: 10 mail edits refused `version_moved` on every pass,/// for a day, in passes that answered ok): a row this phone edited that moved on the object, whose newer version the/// pull never brings (a mail outside the phone's window, archived from Post), was posted again at the same old version/// for ever. Refused as moved, the phone reads that one row from the object, lays its own change over what the object/// holds, and posts it held to that version, in the same pass.#[test]fn an_edit_refused_as_moved_is_laid_over_the_row_the_object_holds_when_the_pull_never_brings_it() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    // Refused as moved; the object hands the row back at 6 (another writer's mood); the edit goes held to 6; the pull    // brings nothing of it.    let rows = Reply::json(200, &json!({ "rows": [served_note(6, "stormy")] }).to_string());    let exchange = ScriptedExchange::new([moved_answer(), rows, act_taken(), page(json!([]), 9)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.pending(), 0, "the edit went in the pass it was refused: {:?}", last_error(&bed));    let first = body(&exchange.nth(0));    assert_eq!((first["act"].as_str(), first["args"]["expect_version"].as_i64()), (Some("seal"), Some(5)));    assert!(exchange.nth(1).path.starts_with("/v1/rows?table=garden_note&ids=n-1"), "{}", exchange.nth(1).path);    let again = body(&exchange.nth(2));    assert_eq!((again["act"].as_str(), again["args"]["expect_version"].as_i64()), (Some("seal"), Some(6)), "held to the version the object holds");    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", again["args"]["data"].as_object().expect("the data")).expect("it opens");    assert_eq!(opened["body"], "The words I wrote", "the edit is kept");    assert_eq!(opened["mood"], "stormy", "the other writer's words are kept");}/// RULE (UNSENT HEAL 4): refused as moved, a row the object holds no more (deleted elsewhere: Post/// deleted the mail) has nowhere to go: refused for good (`row_gone`), parked, and shown to the person, never posted/// again at an old version for ever, nor dropped unsaid.#[test]fn an_edit_refused_as_moved_of_a_row_the_object_holds_no_more_is_refused_for_good_and_shown() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    let gone = Reply::json(200, &json!({ "rows": [] }).to_string());    let exchange = ScriptedExchange::new([moved_answer(), gone, page(json!([]), 9)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.pending(), 0, "not queued to be refused again");    let parked = cotton_store::rejected::list_parked(&bed.replica.lock().expect("the copy").driver, 50).expect("the parks");    assert!(parked.iter().any(|park| park.reason.starts_with("row_gone")), "{parked:?}");    let said = crate::unsent_heal::stuck(&bed.replica.lock().expect("the copy").driver, i64::MAX).expect("stuck");    assert_eq!(said.len(), 1, "shown to the person");}fn rows_answer(rows: Value) -> Reply {    Reply::json(200, &json!({ "rows": rows }).to_string())}fn seal_version_held(bed: &Bed) -> Option<i64> {    bed.replica.lock().expect("the copy").driver.get("SELECT version FROM _seal WHERE tbl = ? AND row_id = 'n-1'", &[rusqlite::types::Value::Text(TABLE.into())]).expect("a read").and_then(|row| row.int("version"))}/// RULE (UNSENT HEAL 5, review HIGH): the version a read hands back is used for the one post made from that read and/// never kept on its own. The read's post failing (a 503), the copy keeps its own older version, so the next pass is/// refused as moved, reads again, and the other device's column survives: never this copy's stale row posted at the/// object's version.#[test]fn a_read_whose_post_fails_keeps_no_version_and_the_other_devices_column_survives() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    let unavailable = Reply::json(503, r#"{"code": "unavailable", "message": "try again"}"#);    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([served_note(6, "stormy")])), unavailable, page(json!([]), 9)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    let _ = run_cycle_paged(&bed.replica, &mut object, WORKSPACE, NOW);    assert_eq!(bed.pending(), 1, "the edit waits");    assert_eq!(seal_version_held(&bed), Some(5), "the read's version is not kept over this copy's older row");    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([served_note(6, "stormy")])), act_taken(), page(json!([]), 9)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(bed.pending(), 0, "{:?}", last_error(&bed));    assert_eq!(body(&exchange.nth(0))["args"]["expect_version"].as_i64(), Some(5), "posted at the version the copy's data is");    let sent = body(&exchange.nth(2));    assert_eq!(sent["args"]["expect_version"].as_i64(), Some(6));    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", sent["args"]["data"].as_object().expect("the data")).expect("it opens");    assert_eq!((opened["body"].as_str(), opened["mood"].as_str()), (Some("The words I wrote"), Some("stormy")), "the other device's column survives");}/// RULE (UNSENT HEAL 6, the coordinator's review of HEAL 5): the person's edit is their act and always goes. The/// object's row changed after the edit (any column, any writer, his own first post): the edit is laid over the row the/// object holds and posted held to its version, never dropped for its time.#[test]fn an_edit_older_than_the_rows_last_change_elsewhere_is_laid_over_and_sent() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([served_note_at(6, "stormy", AFTER_THE_EDIT)])), act_taken(), page(json!([]), 9), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).discarding_to(bed.layout.clone(), WORKSPACE.into());    bed.pass(&mut object);    assert_eq!(bed.pending(), 0, "{:?}", last_error(&bed));    let sent = body(&exchange.nth(2));    assert_eq!((sent["act"].as_str(), sent["args"]["expect_version"].as_i64()), (Some("seal"), Some(6)));    let opened = cotton_core::seal::open_row(&dk(), WORKSPACE, TABLE, "n-1", sent["args"]["data"].as_object().expect("the data")).expect("it opens");    assert_eq!((opened["body"].as_str(), opened["mood"].as_str()), (Some("The words I wrote"), Some("stormy")), "his edit over the newer row");    assert!(crate::unsent::discarded(&bed.layout, WORKSPACE).is_empty(), "nothing dropped");}/// RULE (UNSENT HEAL 5, review M3; HEAL 6): a row the object will not hand back readable is asked again only after a/// wait that doubles, never on every pass. Every pass builds its own transport, so the wait is kept in the copy. And/// it never holds the head of the queue: the next change goes in the same pass.#[test]fn a_row_the_object_will_not_hand_back_readable_is_not_asked_again_every_pass() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let other_note = served_row("n-2", 3, stored(&dk(), "n-2", 1, "Other words"));    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm"), other_note]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    let mut words = Map::new();    words.insert("body".into(), json!("Later words"));    edit(&bed, "cotton_garden_note", "n-2", words);    // Sealed with another database's key: it does not open here.    let unopened = served_row("n-1", 6, Value::Object(stored(&DataKey::from_bytes([9; 32]), "n-1", 1, "another key's words").as_object().cloned().expect("a row")));    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([unopened])), act_taken(), page(json!([]), 9), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert!(last_error(&bed).is_some_and(|error| error.starts_with("held_row_unread")), "{:?}", last_error(&bed));    assert_eq!(bed.pending(), 1, "only the unreadable row's change waits");    let posted: Vec<String> = exchange.seen().iter().filter(|seen| seen.path.starts_with("/v1/act")).map(|seen| body(seen)["args"]["id"].as_str().unwrap_or_default().to_string()).collect();    assert_eq!(posted, ["n-1", "n-2"], "the next change went in the same pass");    // The next pass, a new transport as in the app: refused as moved again, and the read waits.    let exchange = ScriptedExchange::new([moved_answer(), page(json!([]), 9), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(exchange.seen().iter().filter(|seen| seen.path.starts_with("/v1/rows")).count(), 0, "the second pass waits out the read");    assert_eq!(bed.pending(), 1);}/// RULE (UNSENT HEAL 5, review M1): a per-key column is laid key by key: the keys this copy wrote over the object's,/// every other key the object holds kept.#[test]fn a_per_key_column_is_laid_key_by_key() {    let keys: std::collections::BTreeSet<String> = ["mine".to_string(), "gone".to_string()].into_iter().collect();    let theirs = json!({"mine": "old", "gone": "was here", "other": "another device's"});    let ours = json!({"mine": "new", "other": "this copy's stale"});    assert_eq!(super::lay_keys(Some(&theirs), &ours, &keys), json!({"mine": "new", "other": "another device's"}));    let as_text = Value::String(theirs.to_string());    let laid = super::lay_keys(Some(&as_text), &ours, &keys);    assert_eq!(serde_json::from_str::<Value>(laid.as_str().expect("text, as the object holds it")).expect("JSON"), json!({"mine": "new", "other": "another device's"}));}/// RULE (PHONE MEASURES): a fresh copy's first sync keeps its times beside the copy, page by page, and ends once the/// pull that leaves it level is folded; a later pass adds nothing.#[test]fn a_fresh_copys_first_sync_keeps_its_times_until_level() {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let replica = bed.replica.lock().expect("the copy").path.clone();    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let times = crate::first_sync::kept(&replica).expect("kept beside the copy");    assert_eq!((times.pages, times.rows), (1, 1), "{times:?}");    assert!(times.done_at_ms.is_some(), "level after its one page: {times:?}");    let exchange = ScriptedExchange::new([page(json!([]), 5)]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    assert_eq!(crate::first_sync::kept(&replica), Some(times), "nothing added after");}/// A clock the test moves (ms since the epoch), for the waits kept in the copy.fn moved_clock() -> (Arc<std::sync::atomic::AtomicI64>, impl Fn() -> i64 + Send + Sync + 'static) {    let now = Arc::new(std::sync::atomic::AtomicI64::new(1_800_000_000_000));    let read = Arc::clone(&now);    (now, move || read.load(std::sync::atomic::Ordering::SeqCst))}fn unread_wait_of(bed: &Bed) -> Option<(i64, u32)> {    crate::seal::unread_wait(bed.replica.lock().expect("the copy").driver.connection(), TABLE, "n-1").expect("read")}fn moved_wait_of(bed: &Bed) -> Option<(i64, u32)> {    crate::seal::moved_wait(bed.replica.lock().expect("the copy").driver.connection(), TABLE, "n-1").expect("read")}fn unopened_note(version: i64) -> Value {    served_row("n-1", version, Value::Object(stored(&DataKey::from_bytes([9; 32]), "n-1", 1, "another key's words").as_object().cloned().expect("a row")))}/// A copy holding n-1 at 5, edited here.fn edited_bed() -> (Bed, Arc<Sealer>) {    let bed = bed();    let (_keys, sealer) = sealer_with(Some(dk()));    let exchange = ScriptedExchange::new([page(json!([served_note(5, "calm")]), 5), served()]);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer)));    bed.pass(&mut object);    let mut words = Map::new();    words.insert("body".into(), json!("The words I wrote"));    edit(&bed, "cotton_garden_note", "n-1", words);    (bed, sealer)}/// RULE (UNSENT HEAL 7, review 6): the wait to read a row again doubles from a minute to an hour and stays at the/// hour, on the transport's clock, and goes once the row reads: the edit is then laid over it and sent.#[test]fn the_wait_to_read_a_row_doubles_to_the_hour_and_goes_once_it_reads() {    let (bed, sealer) = edited_bed();    let (now, clock) = moved_clock();    let clock = Arc::new(clock);    let mut minutes = Vec::new();    for _ in 0..8 {        let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([unopened_note(6)])), page(json!([]), 9), served()]);        let ticking = Arc::clone(&clock);        let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking());        bed.pass(&mut object);        let (until, _) = unread_wait_of(&bed).expect("it waits");        let at = now.load(std::sync::atomic::Ordering::SeqCst);        minutes.push((until - at) / 60_000);        now.store(until, std::sync::atomic::Ordering::SeqCst);    }    assert_eq!(minutes, [1, 2, 4, 8, 16, 32, 60, 60]);    assert_eq!(bed.pending(), 1);    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([served_note(6, "stormy")])), act_taken(), page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    let mut object = bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking());    bed.pass(&mut object);    assert_eq!(bed.pending(), 0, "{:?}", last_error(&bed));    assert_eq!(unread_wait_of(&bed), None, "the wait goes once the row reads");}/// RULE (UNSENT HEAL 7, review 2 and 6): Cotton not answering the read (a 503) neither clears the wait nor loses the/// edit: it stays queued, and the wait it had stands.#[test]fn an_edit_survives_a_5xx_on_its_read_and_its_wait_stands() {    let (bed, sealer) = edited_bed();    let (now, clock) = moved_clock();    let clock = Arc::new(clock);    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([unopened_note(6)])), page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    bed.pass(&mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()));    let (until, tries) = unread_wait_of(&bed).expect("it waits");    now.store(until, std::sync::atomic::Ordering::SeqCst);    let unavailable = Reply::json(503, r#"{"code": "unavailable", "message": "try again"}"#);    let exchange = ScriptedExchange::new([moved_answer(), unavailable, page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    let _ = run_cycle_paged(&bed.replica, &mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()), WORKSPACE, NOW);    assert_eq!(bed.pending(), 1, "the edit waits");    assert_eq!(unread_wait_of(&bed), Some((until, tries)), "a read Cotton did not answer clears nothing");    assert!(crate::unsent::discarded(&bed.layout, WORKSPACE).is_empty(), "nothing dropped");}/// RULE (UNSENT HEAL 7, review 3): an edit laid over a fresh read and refused as moved again, three times in a row,/// waits before the row is read again (a minute, doubling), under its own code, said after a day; taken, the count goes.#[test]fn an_edit_moved_again_after_every_fresh_read_backs_off() {    let (bed, sealer) = edited_bed();    let (now, clock) = moved_clock();    let clock = Arc::new(clock);    for tries in 1..=3u32 {        let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([served_note(6, "stormy")])), moved_answer(), page(json!([]), 9), served()]);        let ticking = Arc::clone(&clock);        bed.pass(&mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()));        assert_eq!(moved_wait_of(&bed).map(|(_, counted)| counted), Some(tries));    }    assert!(last_error(&bed).is_some_and(|error| error.starts_with("moved_again")), "{:?}", last_error(&bed));    assert!(!cotton_store::outbox::passing("moved_again"), "said after a day, as any code that does not pass");    let (until, _) = moved_wait_of(&bed).expect("it waits");    assert_eq!(until - now.load(std::sync::atomic::Ordering::SeqCst), 60_000, "a minute first");    // Within the wait: posted, refused as moved, and not read again.    let exchange = ScriptedExchange::new([moved_answer(), page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    bed.pass(&mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()));    assert_eq!(exchange.seen().iter().filter(|seen| seen.path.starts_with("/v1/rows")).count(), 0, "the read waits");    assert_eq!(bed.pending(), 1);    now.store(until, std::sync::atomic::Ordering::SeqCst);    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([served_note(7, "stormy")])), act_taken(), page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    bed.pass(&mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()));    assert_eq!(bed.pending(), 0, "{:?}", last_error(&bed));    assert_eq!(moved_wait_of(&bed), None, "taken: the count goes");}/// RULE (UNSENT HEAL 7, review 6): the wait lives in the copy's file: a copy closed and opened again (the app killed/// and launched) still waits out the read.#[test]fn the_wait_to_read_a_row_outlives_the_copy_being_opened_again() {    let (bed, sealer) = edited_bed();    let (_now, clock) = moved_clock();    let clock = Arc::new(clock);    let exchange = ScriptedExchange::new([moved_answer(), rows_answer(json!([unopened_note(6)])), page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    bed.pass(&mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()));    let waited = unread_wait_of(&bed).expect("it waits");    {        let mut copy = bed.replica.lock().expect("the copy");        let reopened = crate::open_replica(&bed.layout, WORKSPACE, &crate::seams::FixedClock::default_start(), &crate::seams::SeededRandom::default(), &mut |_: &std::path::Path| Err("the copy is there: never made again".to_string())).expect("opened again");        *copy = reopened;    }    assert_eq!(unread_wait_of(&bed), Some(waited), "kept in the file");    let exchange = ScriptedExchange::new([moved_answer(), page(json!([]), 9), served()]);    let ticking = Arc::clone(&clock);    bed.pass(&mut bed.transport(&exchange, Some(Arc::clone(&sealer))).on_clock(move || ticking()));    assert_eq!(exchange.seen().iter().filter(|seen| seen.path.starts_with("/v1/rows")).count(), 0, "still waits after the reopen");    assert_eq!(bed.pending(), 1);}