Cotton code
2580 lines · 157.9 KB · RustRaw
//! The Mac against a real Worker: the walk `apps/business/scripts/__tests__/e2e-mac.ts`//! runs by name, with `wrangler dev` up and its address in `COTTON_E2E_BASE`.//!//!   COTTON_E2E_BASE=http://127.0.0.1:<port> COTTON_E2E_PHONE=+91… \//!     cargo test -p cotton-mac --test object_e2e -- --ignored --nocapture//!//! A synthetic number signs in at the open host (the directory makes its//! database), the app's passes name the Mac, a messages batch lands once//! across two passes, message changes count a missing message, a synthetic//! mailbox lands through the mail importer. Each step is asserted against//! the object's own export; the last line, `E2E-MAC {…}`, hands the script//! what it checks again from outside.mod support;use std::collections::VecDeque;use std::io::{BufRead, BufReader, Write};use std::net::TcpListener;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use cotton_client::ingest::{IngestBatch, IngestMediaFile, IngestWork};use cotton_core::import::envelope::ImportBatch;use cotton_core::import::messages_engine::MessageChange;use cotton_mac::app::{App, Config};use cotton_mac::vault::{KeyRows, MemoryKeyring};use cotton_mac::importer::{Importer, Probe, Progress, RunContext, RunError, Schedule, SourceKey};use cotton_mac::mail::MailImporter;use cotton_mac::object::{Act, ObjectClient};use cotton_mac::sink::ObjectSink;use cotton_mac::store::Store;use serde_json::{json, Map, Value};use support::fixture;const DEVICE_ID: &str = "e2e-mac";const DEVICE_NAME: &str = "E2E Mac";const APP_VERSION: &str = "0.0.0 (e2e)";/// Sends what the walk queued, one batch a pass; a pass with nothing queued sends nothing.struct Scripted {    queue: Arc<Mutex<VecDeque<IngestBatch>>>,    runs: Arc<AtomicUsize>,}impl Importer for Scripted {    fn key(&self) -> SourceKey {        SourceKey::Whatsapp    }    fn schedule(&self) -> Schedule {        Schedule::Every(Duration::from_secs(3600))    }    fn probe(&self) -> Probe {        Probe::ready()    }    fn run(&self, cursor: Option<&str>, ctx: &mut RunContext<'_>) -> Result<String, RunError> {        let next = self.queue.lock().unwrap().pop_front();        if let Some(batch) = next {            ctx.send(batch)?;        }        self.runs.fetch_add(1, Ordering::SeqCst);        Ok(cursor.unwrap_or("e2e").to_string())    }}fn env(name: &str) -> String {    std::env::var(name).unwrap_or_else(|_| panic!("{name} is not set: run this walk from e2e-mac.ts"))}/// Every live row of the object, through the owner token's export.fn export(base: &str, token: &str) -> Vec<Value> {    let http = reqwest::blocking::Client::new();    let mut rows = Vec::new();    let mut after: Option<String> = None;    loop {        let mut request = http.get(format!("{base}/v1/admin/export")).bearer_auth(token).query(&[("limit", "10000")]);        if let Some(after) = &after {            request = request.query(&[("after", after.as_str())]);        }        let response = request.send().expect("the export");        assert!(response.status().is_success(), "the export: {}", response.status());        let page: Value = response.json().expect("the export parses");        rows.extend(page["rows"].as_array().cloned().unwrap_or_default());        match page["next"].as_str() {            Some(next) => after = Some(next.to_string()),            None => return rows,        }    }}fn of<'a>(rows: &'a [Value], table: &str) -> Vec<&'a Value> {    rows.iter().filter(|r| r["table"] == table && r["deleted"] != true).collect()}/// The rows as the owner reads them: a sealed row opened with the data key/// (its stored form is asserted where the walk says so).fn opened(reader: &cotton_mac::copy::Copy, rows: Vec<Value>) -> Vec<Value> {    rows.into_iter()        .map(|mut row| {            if row["data"]["sealed_enc"].is_string() {                let (table, id) = (row["table"].as_str().unwrap().to_string(), row["id"].as_str().unwrap().to_string());                let data = reader.open_served(&table, &id, row["data"].as_object().unwrap()).expect("a sealed row opens with the data key");                row["data"] = Value::Object(data);            }            row        })        .collect()}/// What a phone does for a new object, done here for the walk: this Mac's/// published key gets the first wrap of a fresh vault master key (the Mac/// founds the vault), and the database's data key is minted under it.fn found_and_mint(client: &ObjectClient) -> cotton_core::seal::DataKey {    use base64::Engine as _;    let (id, mut data) = client.key_row(DEVICE_ID).unwrap().expect("the Mac published its vault key");    let public: [u8; 32] = base64::engine::general_purpose::URL_SAFE_NO_PAD        .decode(data["public_key"].as_str().unwrap())        .unwrap()        .try_into()        .unwrap();    let vmk = cotton_core::vault::Vmk::mint();    data.insert("wrapped_vmk".into(), json!(cotton_core::vault::wrap::wrap(&public, vmk.expose()).unwrap()));    data.insert("vmk_version".into(), json!(1));    client.put_key_row(&id, &Value::Object(data)).unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-10-26T06:00:00.000Z").unwrap();    client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    dk}fn wait_for(app: &App, what: impl Fn(&Value) -> bool) -> Value {    let started = Instant::now();    loop {        let status = app.call("status", &json!({}));        if what(&status) {            return status;        }        assert!(started.elapsed() < Duration::from_secs(60), "timed out; last status {status}");        std::thread::sleep(Duration::from_millis(20));    }}/// One pass of the scripted source, run now, waited for, and its error none.fn pass(app: &App, runs: &AtomicUsize) {    let before = runs.load(Ordering::SeqCst);    assert_eq!(app.call("runNow", &json!({ "source": "whatsapp" }))["ok"], true);    let status = wait_for(app, |s| runs.load(Ordering::SeqCst) > before && s["sources"][0]["phase"] != "running");    assert_eq!(status["sources"][0]["error"], Value::Null, "the pass failed: {status}");}// ── mail ────────────────────────────────────────────────────────────────/// (uid, INTERNALDATE, raw).type Mailbox = Vec<(u32, &'static str, String)>;fn email(id: &str, date: &str, subject: &str, refs: Option<&str>, from: &str, text: &str) -> String {    let refs = refs.map(|r| format!("References: {r}\r\nIn-Reply-To: {r}\r\n")).unwrap_or_default();    format!(        "From: {from}\r\nTo: Owner <owner@example.com>\r\nSubject: {subject}\r\nDate: {date}\r\nMessage-ID: {id}\r\n{refs}Content-Type: text/plain\r\n\r\n{text}\r\n"    )}fn uids_of(set: &str, mailbox: &Mailbox) -> Vec<u32> {    let mut out = Vec::new();    for part in set.split(',') {        match part.split_once(':') {            Some((lo, hi)) => {                let lo: u32 = lo.parse().unwrap();                let hi: u32 = if hi == "*" { u32::MAX } else { hi.parse().unwrap() };                out.extend(mailbox.iter().map(|m| m.0).filter(|uid| *uid >= lo && *uid <= hi));            }            None => out.push(part.parse().unwrap()),        }    }    out}/// A plain IMAP server over `mailbox`, as tests/mail.rs serves one, each/// message with its own INTERNALDATE; no IDLE.fn imap(mailbox: Mailbox) -> u16 {    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let port = listener.local_addr().unwrap().port();    let mailbox = Arc::new(mailbox);    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { continue };            let held = Arc::clone(&mailbox);            std::thread::spawn(move || {                let mut writer = stream.try_clone().unwrap();                let mut reader = BufReader::new(stream);                writer.write_all(b"* OK e2e ready\r\n").unwrap();                loop {                    let mut line = String::new();                    if reader.read_line(&mut line).unwrap_or(0) == 0 {                        return;                    }                    let line = line.trim_end().to_string();                    let (tag, rest) = line.split_once(' ').unwrap();                    let words: Vec<&str> = rest.split(' ').collect();                    let mut out = String::new();                    match words[0] {                        "LOGIN" => out.push_str(&format!("{tag} OK signed in\r\n")),                        "CAPABILITY" => out.push_str(&format!("* CAPABILITY IMAP4rev1\r\n{tag} OK\r\n")),                        "EXAMINE" => {                            let next = held.iter().map(|m| m.0).max().unwrap_or(0) + 1;                            out.push_str(&format!(                                "* {} EXISTS\r\n* OK [UIDVALIDITY 9] v\r\n* OK [UIDNEXT {next}] n\r\n{tag} OK [READ-ONLY] done\r\n",                                held.len()                            ));                        }                        "UID" if words[1] == "SEARCH" => {                            let found: Vec<String> = if rest.contains("BEFORE") {                                Vec::new()                            } else {                                uids_of(words[3], &held).iter().map(u32::to_string).collect()                            };                            out.push_str(&format!("* SEARCH {}\r\n{tag} OK\r\n", found.join(" ")));                        }                        "UID" if words[1] == "FETCH" => {                            let bodies = rest.contains("BODY.PEEK[]");                            for (n, uid) in uids_of(words[2], &held).into_iter().enumerate() {                                let Some((_, received, raw)) = held.iter().find(|m| m.0 == uid) else { continue };                                if bodies {                                    out.push_str(&format!(                                        "* {} FETCH (UID {uid} INTERNALDATE \"{received}\" BODY[] {{{}}}\r\n{raw})\r\n",                                        n + 1,                                        raw.len()                                    ));                                } else {                                    out.push_str(&format!("* {} FETCH (UID {uid} FLAGS (\\Seen))\r\n", n + 1));                                }                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "LOGOUT" => {                            out.push_str(&format!("* BYE bye\r\n{tag} OK\r\n"));                            writer.write_all(out.as_bytes()).unwrap();                            return;                        }                        _ => out.push_str(&format!("{tag} BAD unknown\r\n")),                    }                    writer.write_all(out.as_bytes()).unwrap();                }            });        }    });    port}/// A mail run as the app's pass makes one: every write to a sealed table goes/// up sealed, through the copy (the sink's rows and the importer's own acts,/// through the client's seal door).fn run_mail(mail: &MailImporter, client: &ObjectClient, database_id: &str, store: &Store, copy: &Arc<cotton_mac::copy::Copy>) -> String {    let client = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(copy)));    let sink = ObjectSink::new(&client, database_id).with_copy(copy);    let cancel = AtomicBool::new(false);    let on_progress = |_: Progress| {};    let cursor = store.cursor("mail").unwrap();    let mut ctx = RunContext::new(&sink, store, SourceKey::Mail, &cancel, &on_progress);    mail.run(cursor.as_deref(), &mut ctx).expect("the mail run")}#[test]#[ignore = "needs wrangler dev: run by apps/business/scripts/__tests__/e2e-mac.ts"]fn the_mac_imports_into_its_object() {    let base = env("COTTON_E2E_BASE");    let phone = env("COTTON_E2E_PHONE");    let dir = tempfile::tempdir().unwrap();    // ── sign-in at the open host, then two quiet passes ──    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: DEVICE_ID.into(),        machine: "e2e-mac".into(),        device_name: DEVICE_NAME.into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let app = App::open(config, vec![Box::new(Scripted { queue: Arc::clone(&queue), runs: Arc::clone(&runs) })], Box::new(MemoryKeyring::default())).unwrap();    let asked = app.call("askCode", &json!({ "phone": phone }));    assert_eq!(asked["ok"], true, "askCode: {asked}");    let database_id = asked["databaseId"].as_str().expect("the open host names the database").to_string();    let signed = app.call(        "signIn",        &json!({ "databaseId": database_id, "challengeId": asked["challengeId"], "code": std::env::var("COTTON_E2E_CODE").unwrap_or_else(|_| "123456".into()) }),    );    assert_eq!(signed["ok"], true, "signIn: {signed}");    let credential = signed["credential"].as_str().unwrap().to_string();    assert!(credential.starts_with(&format!("ctd_{database_id}_")), "the credential names its database");    assert_eq!(signed["phone"], phone);    let client = ObjectClient::new(base.clone(), Some(credential.clone())).unwrap();    let http = reqwest::blocking::Client::new();    let token: Value = http        .post(format!("{base}/v1/act"))        .bearer_auth(&credential)        .json(&json!({ "act": "mint_token", "args": { "name": "e2e mac", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = token["token"].as_str().expect("an owner token for the export").to_string();    // The first pass starts with the app: it names the Mac and publishes its    // vault key (it has nothing to send yet). The vault is founded and the    // data key minted; the next pass opens it, and a third, quiet too, follows.    assert_eq!(app.call("start", &json!({ "token": credential, "phone": phone }))["ok"], true);    wait_for(&app, |s| s["vault"]["state"] == "waiting" && s["sources"][0]["phase"] != "running");    let dk = found_and_mint(&client);    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    let reader = cotton_mac::copy::Copy::open(&dir.path().join("reader.db"), &database_id, keys.clone()).unwrap();    reader.refresh(&client).unwrap();    let read = || opened(&reader, export(&base, &token));    pass(&app, &runs);    assert_eq!(app.call("status", &json!({}))["vault"]["state"], "open", "the vault opens once founded");    let rows = export(&base, &token);    let devices: Vec<&Value> = of(&rows, "device").into_iter().filter(|r| r["data"]["device_id"] == DEVICE_ID).collect();    assert_eq!(devices.len(), 1, "the first pass files the Mac's device row: {devices:?}");    let first = devices[0].clone();    assert_eq!(first["data"]["name"], DEVICE_NAME);    assert_eq!(first["data"]["platform"], "mac");    assert_eq!(first["data"]["app_version"], APP_VERSION);    std::thread::sleep(Duration::from_millis(20));    pass(&app, &runs);    let rows = export(&base, &token);    let devices: Vec<&Value> = of(&rows, "device").into_iter().filter(|r| r["data"]["device_id"] == DEVICE_ID).collect();    assert_eq!(devices.len(), 1, "a quiet pass makes no second row: {devices:?}");    assert_eq!(devices[0]["id"], first["id"], "the same row");    assert_ne!(devices[0]["updated_at"], first["updated_at"], "a quiet pass refreshes the row");    // ── messages: the same batch on two passes lands once ──    let mut batch: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    batch.workspace_id = database_id.clone();    batch.messages[1].media = None;    let picture = dir.path().join("trailhead.jpg");    std::fs::write(&picture, b"synthetic jpeg bytes").unwrap();    let held_external = batch.messages[1].external_id.clone();    let messages = IngestBatch {        work: IngestWork::Messages {            request: Box::new(batch.clone()),            media: vec![IngestMediaFile {                external_id: held_external.clone(),                path: picture,                name: Some("trailhead.jpg".into()),                content_type: Some("image/jpeg".into()),            }],        },        read: 2,        cursor: None,    };    queue.lock().unwrap().push_back(messages.clone());    pass(&app, &runs);    let stored = export(&base, &token);    for table in ["message", "thread", "message_contact", "message_reaction"] {        for row in of(&stored, table) {            assert!(row["data"]["sealed_enc"].is_string(), "{table} {} is stored sealed", row["id"]);        }    }    assert!(of(&stored, "message").iter().all(|m| m["data"].get("body").is_none() && m["data"].get("media").is_none()), "no body or media in the clear");    let landed = read();    let said: Vec<&Value> = of(&landed, "message");    assert_eq!(said.len(), 2, "two messages: {said:?}");    assert_eq!(of(&landed, "thread").len(), 1, "one thread");    assert_eq!(of(&landed, "message_reaction").len(), 1, "one reaction");    let with_media = said.iter().find(|m| m["data"]["external_id"] == held_external).expect("the message with media");    let media_key = with_media["data"]["media"][0]["key"].as_str().expect("a media key").to_string();    assert!(media_key.starts_with(&format!("{database_id}/sealed/")), "a sealed message's picture goes up sealed: {media_key}");    assert!(client.media_held(&media_key).unwrap(), "the picture is at the object");    queue.lock().unwrap().push_back(messages);    pass(&app, &runs);    let again = read();    for table in ["message", "thread", "message_contact", "message_reaction"] {        assert_eq!(of(&again, table).len(), of(&landed, table).len(), "a repeated pass adds no {table}");    }    app.stop();    // ── message changes: edit, revoke, reaction, and one missing ──    let first_external = batch.messages[0].external_id.clone();    let changes = vec![        MessageChange::Edit { external_id: first_external.clone(), body: "Leaving at seven?".into(), at: "2026-10-20T00:40:00Z".into() },        MessageChange::Revoke { external_id: held_external.clone(), at: "2026-10-20T00:41:00Z".into() },        MessageChange::Reaction { external_id: first_external.clone(), actor: "owner".into(), emoji: "🙏".into(), at: "2026-10-20T00:42:00Z".into() },        MessageChange::Edit { external_id: "3EB0A1B2C3D4E5F69999".into(), body: "never sent".into(), at: "2026-10-20T00:43:00Z".into() },    ];    // Decided over a copy of the Mac's own, as the app's pass decides them.    let copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("changes-copy.db"), &database_id, keys.clone()).unwrap());    let sent = ObjectSink::new(&client, database_id.clone())        .with_copy(&copy)        .send(IngestBatch { work: IngestWork::MessageChanges { workspace_id: database_id.clone(), channel: "whatsapp".into(), changes }, read: 4, cursor: None })        .unwrap();    assert_eq!(sent.rows, 4);    let changed = read();    let message = |external: &str| {        of(&changed, "message").into_iter().find(|m| m["data"]["external_id"] == external).cloned().expect("held")    };    assert_eq!(message(&first_external)["data"]["body"], "Leaving at seven?");    assert_eq!(message(&first_external)["data"]["edited_at"], "2026-10-20T00:40:00Z");    assert_eq!(message(&held_external)["data"]["body"], "");    assert_eq!(message(&held_external)["data"]["deleted_at"], "2026-10-20T00:41:00Z");    assert_eq!(of(&changed, "message_reaction").len(), 2, "the owner's reaction is added");    assert_eq!(of(&changed, "message").len(), 2, "the missing one is counted, never kept");    // ── mail: two believable messages land, one with no believable date does not ──    let port = imap(vec![        (1, "04-Oct-2026 10:00:05 +0000", email("<root@example.org>", "Sun, 4 Oct 2026 10:00:00 +0000", "Lunch?", None, "Owner <owner@example.com>", "Lunch tomorrow?")),        (            2,            "05-Oct-2026 09:30:05 +0000",            email("<r1@example.org>", "Mon, 5 Oct 2026 09:30:00 +0000", "Re: Lunch?", Some("<root@example.org>"), "Ada Example <ada@example.org>", "Noon works."),        ),        (3, "16-Sep-2611 18:03:30 +0000", email("<notice@example.net>", "Mon, 16 Sep 2611 18:03:30 +0000", "A notice from the future", None, "Notices <notices@example.net>", "Stamped 2611.")),    ]);    let mail = MailImporter::new(&dir.path().join("mail"));    mail.command(        "credentials",        &json!({ "address": "owner@example.com", "password": "app-pw", "imapHost": format!("127.0.0.1:{port}"), "imapTls": false }),    )    .unwrap();    let store = Store::open(&dir.path().join("mail-importer.db")).unwrap();    run_mail(&mail, &client, &database_id, &store, &copy);    let mailed = read();    let emails = of(&mailed, "email");    assert_eq!(emails.len(), 2, "the two believable emails, not the one stamped 2611: {emails:?}");    assert!(emails.iter().all(|e| e["data"]["subject"] != "A notice from the future"));    let threads = of(&mailed, "email_thread");    assert_eq!(threads.len(), 1, "{threads:?}");    assert_eq!(threads[0]["data"]["first_at"], "2026-10-04T10:00:00.000Z");    assert_eq!(threads[0]["data"]["last_at"], "2026-10-05T09:30:00.000Z");    // A second run reads nothing new and sends nothing.    run_mail(&mail, &client, &database_id, &store, &copy);    assert_eq!(of(&export(&base, &token), "email").len(), 2);    println!(        "E2E-MAC {}",        json!({ "database_id": database_id, "token": token, "device_id": DEVICE_ID, "device_row": first["id"] })    );}// ── the sealed walk on the dev Worker (step 4) ──/// The status line of the source at `index`, after a `runNow` of `name` that ran.fn pass_of(app: &App, runs: &AtomicUsize, index: usize, name: &str) -> Value {    let before = runs.load(Ordering::SeqCst);    assert_eq!(app.call("runNow", &json!({ "source": name }))["ok"], true);    let started = Instant::now();    loop {        let status = app.call("status", &json!({}));        let done = status["sources"][index]["phase"] != "running" && (name != "whatsapp" || runs.load(Ordering::SeqCst) > before);        if done && started.elapsed() > Duration::from_secs(1) {            return status;        }        assert!(started.elapsed() < Duration::from_secs(120), "{name} timed out; last status {status}");        std::thread::sleep(Duration::from_millis(200));    }}/// The Mac against the DEV Worker, synthetic rows only: it signs in with the/// walk's synthetic number into the object a phone founded the vault of and/// minted the data key on, publishes its vault key and waits (up to 15/// minutes) while the phone approves it in Keys › Devices, then lands a/// WhatsApp batch with a picture and a synthetic mailbox. Every message and/// email row is stored sealed (no body, no subject in the clear), the picture/// sits under `<db>/sealed/<hex>`, and the walk's owner token and database go/// to WALK_OUT (0600) for `pnpm seal:check p-<db>`; neither is printed.//////   WALK_BASE=<the dev Worker's address (config/dev-server.json)> WALK_PHONE=+1555… \///   WALK_OTP_FILE=~/.cotton-credentials/cotton/dev-otp WALK_OUT=<file> \///   WALK_PICTURE=<jpg> cargo test -p cotton-mac --test object_e2e \///     the_mac_lands_sealed_on_dev_once_the_phone_approves -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker and a phone to approve: run by hand"]fn the_mac_lands_sealed_on_dev_once_the_phone_approves() {    let base = env("WALK_BASE");    assert!(base.contains("cottondb-dev"), "the walk runs against the dev Worker only");    let phone = env("WALK_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = std::fs::read_to_string(shellexpand(&env("WALK_OTP_FILE"))).expect("the dev code").trim().to_string();    let out = env("WALK_OUT");    let dir = tempfile::tempdir().unwrap();    // The device the walk's tools run as (seal-device, music-import, seal-files): the same id and key file, so one    // approval on the phone serves them all. Unset, the walk is a device of its own with its key in memory.    let device_id = std::env::var("WALK_DEVICE_ID").unwrap_or_else(|_| "walk-mac".into());    let keyring: Box<dyn cotton_mac::vault::Keyring> = match std::env::var("WALK_KEY_FILE") {        Ok(file) => Box::new(cotton_mac::vault::FileKeyring(shellexpand(&file).into())),        Err(_) => Box::new(cotton_mac::vault::MemoryKeyring::default()),    };    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: device_id.clone(),        machine: "walk-mac".into(),        device_name: "Walk Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let mail = MailImporter::new(&dir.path().join("mail"));    let port = imap(vec![        (1, "04-Oct-2026 10:00:05 +0000", email("<root@example.org>", "Sun, 4 Oct 2026 10:00:00 +0000", "Lunch at the orchard?", None, "Owner <owner@example.com>", "Lunch tomorrow by the orchard gate?")),        (            2,            "05-Oct-2026 09:30:05 +0000",            email("<r1@example.org>", "Mon, 5 Oct 2026 09:30:00 +0000", "Re: Lunch at the orchard?", Some("<root@example.org>"), "Ada Example <ada@example.org>", "Noon works."),        ),    ]);    mail.command(        "credentials",        &json!({ "address": "owner@example.com", "password": "app-pw", "imapHost": format!("127.0.0.1:{port}"), "imapTls": false }),    )    .unwrap();    let app = App::open(        config,        vec![Box::new(Scripted { queue: Arc::clone(&queue), runs: Arc::clone(&runs) }), Box::new(mail)],        keyring,    )    .unwrap();    let asked = app.call("askCode", &json!({ "phone": phone }));    assert_eq!(asked["ok"], true, "askCode: {asked}");    let database_id = asked["databaseId"].as_str().expect("the open host names the database").to_string();    let signed = app.call("signIn", &json!({ "databaseId": database_id, "challengeId": asked["challengeId"], "code": code }));    assert_eq!(signed["ok"], true, "signIn refused");    let credential = signed["credential"].as_str().unwrap().to_string();    let client = ObjectClient::new(base.clone(), Some(credential.clone())).unwrap();    let token: Value = reqwest::blocking::Client::new()        .post(format!("{base}/v1/act"))        .bearer_auth(&credential)        .json(&json!({ "act": "mint_token", "args": { "name": "walk mac", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = token["token"].as_str().expect("an owner token for the export").to_string();    {        use std::os::unix::fs::OpenOptionsExt;        let mut file = std::fs::OpenOptions::new().create(true).truncate(true).write(true).mode(0o600).open(&out).unwrap();        writeln!(file, "{}", json!({ "database_id": database_id, "slug": format!("p-{database_id}"), "token": token })).unwrap();    }    println!("WALK database {database_id}");    // ── the vault: published, then approved from the phone ──    assert_eq!(app.call("start", &json!({ "token": credential, "phone": phone }))["ok"], true);    let started = Instant::now();    let mut said = String::new();    loop {        let status = app.call("status", &json!({}));        let vault = &status["vault"];        let line = format!("{} {}", vault["state"], vault["fingerprint"]);        if line != said {            println!("WALK vault {line} · {}", vault["detail"]);            said = line;        }        if vault["state"] == "open" {            break;        }        assert!(started.elapsed() < Duration::from_secs(900), "the phone did not approve this Mac in 15 minutes: {vault}");        std::thread::sleep(Duration::from_secs(5));        let _ = app.call("runNow", &json!({ "source": "whatsapp" }));    }    // ── a WhatsApp batch with a picture lands sealed ──    let mut batch: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    batch.workspace_id = database_id.clone();    batch.messages[1].media = None;    let picture = dir.path().join("trailhead.jpg");    match std::env::var("WALK_PICTURE") {        Ok(path) => std::fs::copy(path, &picture).map(|_| ()).unwrap(),        Err(_) => std::fs::write(&picture, b"synthetic jpeg bytes").unwrap(),    }    let held_external = batch.messages[1].external_id.clone();    queue.lock().unwrap().push_back(IngestBatch {        work: IngestWork::Messages {            request: Box::new(batch),            media: vec![IngestMediaFile {                external_id: held_external.clone(),                path: picture,                name: Some("trailhead.jpg".into()),                content_type: Some("image/jpeg".into()),            }],        },        read: 2,        cursor: None,    });    let status = pass_of(&app, &runs, 0, "whatsapp");    assert_eq!(status["sources"][0]["error"], Value::Null, "the WhatsApp pass failed: {status}");    let status = pass_of(&app, &runs, 1, "mail");    assert_eq!(status["sources"][1]["error"], Value::Null, "the mail pass failed: {status}");    // ── a photo from the library lands with its original sealed (e2e rulings R6) ──    let mut work: cotton_client::ingest::sources::photos::PhotoWork = serde_json::from_value(fixture("photos")).unwrap();    let library = dir.path().join("library");    let filename = work.assets[0].row.filename.clone().unwrap();    std::fs::create_dir_all(library.join("originals/B")).unwrap();    // Synthetic bytes that say what they are in the clear, and are this walk's own (a fresh digest each run).    let original = format!("\u{FFFD}synthetic heic of the walk {database_id} {}", std::process::id()).into_bytes();    std::fs::write(library.join("originals/B").join(&filename), &original).unwrap();    work.library_path = library;    work.assets[0].sha256 = None;    queue.lock().unwrap().push_back(IngestBatch { work: IngestWork::Photos(Box::new(work)), read: 1, cursor: None });    let status = pass_of(&app, &runs, 0, "whatsapp");    assert_eq!(status["sources"][0]["error"], Value::Null, "the photo pass failed: {status}");    let photo_key = cotton_mac::ids::photo_key(&database_id, &cotton_mac::ids::sha256_hex(&original), "heic");    let stored = client.media_stored(&photo_key).unwrap().expect("the photo's original is at the object");    assert!(stored.sealed(), "the photo is stored as {:?}, not sealed", stored.content_type);    let mut bytes = Vec::new();    client.get_media_to(&photo_key, stored.size, &mut bytes).unwrap();    assert!(bytes.starts_with(b"CTF1") && !bytes.windows(14).any(|w| w == b"synthetic heic"), "the object holds the picture's plaintext");    println!("WALK photo stored sealed ({} bytes) under <db>/photos/<sha256>.heic", stored.size);    app.stop();    let rows = export(&base, &token);    for (table, words) in [        ("thread", vec!["title"]),        ("message", vec!["body", "media"]),        ("message_contact", vec!["display_name", "phone_e164"]),        ("email", vec!["subject", "body", "from_email"]),        ("email_thread", vec!["subject"]),        ("email_participant", vec!["email"]),    ] {        let held = of(&rows, table);        assert!(!held.is_empty(), "no {table} landed");        for row in &held {            assert!(row["data"]["sealed_enc"].is_string(), "{table} {} is not sealed", row["id"]);            for word in &words {                assert!(row["data"].get(*word).is_none(), "{table} {} holds {word} in the clear", row["id"]);            }        }        println!("WALK sealed {table} {}", held.len());    }    // The picture's key, read from the Mac's own opened copy: random, under sealed/.    let copy = cotton_mac::copy::Copy::open(&dir.path().join("data/copy.db"), &database_id, cotton_client::seal::HeldDataKeys::new()).unwrap();    let id = of(&rows, "message")        .into_iter()        .map(|m| m["id"].as_str().unwrap().to_string())        .find(|id| copy.row("message", id).unwrap().is_some_and(|m| m["external_id"] == held_external.as_str()))        .expect("the message with media, in the copy");    let opened = copy.row("message", &id).unwrap().unwrap();    let media_key = opened["media"][0]["key"].as_str().expect("a media key").to_string();    assert!(media_key.starts_with(&format!("{database_id}/sealed/")), "{media_key}");    let hex = &media_key[database_id.len() + "/sealed/".len()..];    assert!(hex.len() == 32 && hex.bytes().all(|b| b.is_ascii_hexdigit()), "{media_key}");    assert!(client.media_held(&media_key).unwrap(), "the picture is at the object");    println!("WALK picture under {database_id}/sealed/<32 hex>");    assert!(!of(&rows, "photo").is_empty(), "the photo's row landed");    println!("WALK done");}fn shellexpand(path: &str) -> String {    match path.strip_prefix("~/") {        Some(rest) => format!("{}/{rest}", std::env::var("HOME").unwrap()),        None => path.to_string(),    }}/// `seal-land` against the DEV Worker, synthetic rows only: a Mac signs in/// with a fresh synthetic number (an object of its own), founds its vault on/// its own published key and mints the data key (as a phone would), then/// lands a recovered file of threads, messages, a reaction and an email/// thread with its email through `seal_land::land`. Every table reads back/// opened to the file's columns, the object holds every row sealed with no/// sealed word in the clear, and a second run sends nothing. WALK_OUT (0600)/// gets the database and an owner token for `pnpm seal:check p-<db>`.//////   WALK_BASE=<the dev Worker's address (config/dev-server.json)> WALK_PHONE=+1555… \///   WALK_OTP_FILE=<file> WALK_OUT=<file> cargo test -p cotton-mac --test object_e2e \///     seal_land_lands_recovered_rows_sealed_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker: run by hand"]fn seal_land_lands_recovered_rows_sealed_on_dev() {    use cotton_mac::seal_land::{land, open_file, open_progress, report, LandOptions};    const WORD: &str = "kestrel";    let base = env("WALK_BASE");    assert!(base.contains("cottondb-dev"), "the walk runs against the dev Worker only");    let phone = env("WALK_PHONE");    assert!(phone.starts_with("+1555010"), "a synthetic number only");    let code = std::fs::read_to_string(shellexpand(&env("WALK_OTP_FILE"))).expect("the dev code").trim().to_string();    let out = env("WALK_OUT");    let dir = tempfile::tempdir().unwrap();    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: DEVICE_ID.into(),        machine: DEVICE_ID.into(),        device_name: "Seal-land Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let app = App::open(config, vec![Box::new(Scripted { queue, runs: Arc::clone(&runs) })], Box::new(MemoryKeyring::default())).unwrap();    let asked = app.call("askCode", &json!({ "phone": phone }));    assert_eq!(asked["ok"], true, "askCode: {asked}");    let database_id = asked["databaseId"].as_str().expect("the open host names the database").to_string();    let signed = app.call("signIn", &json!({ "databaseId": database_id, "challengeId": asked["challengeId"], "code": code }));    assert_eq!(signed["ok"], true, "signIn refused");    let credential = signed["credential"].as_str().unwrap().to_string();    let client = ObjectClient::new(base.clone(), Some(credential.clone())).unwrap();    let token: Value = reqwest::blocking::Client::new()        .post(format!("{base}/v1/act"))        .bearer_auth(&credential)        .json(&json!({ "act": "mint_token", "args": { "name": "seal-land walk", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = token["token"].as_str().expect("an owner token for the export").to_string();    {        use std::os::unix::fs::OpenOptionsExt;        let mut file = std::fs::OpenOptions::new().create(true).truncate(true).write(true).mode(0o600).open(&out).unwrap();        writeln!(file, "{}", json!({ "database_id": database_id, "slug": format!("p-{database_id}"), "token": token })).unwrap();    }    println!("WALK database {database_id}");    assert_eq!(app.call("start", &json!({ "token": credential, "phone": phone }))["ok"], true);    let started = Instant::now();    while app.call("status", &json!({}))["vault"]["state"] != "waiting" {        assert!(started.elapsed() < Duration::from_secs(120), "the Mac never published its vault key");        std::thread::sleep(Duration::from_secs(2));        let _ = app.call("runNow", &json!({ "source": "whatsapp" }));    }    app.stop();    let dk = found_and_mint(&client);    // The recovered file: children first, as a recovery would write them.    let file_path = dir.path().join("recovered.db");    {        let conn = rusqlite::Connection::open(&file_path).unwrap();        conn.execute_batch("CREATE TABLE rows (table_id TEXT NOT NULL, id TEXT NOT NULL, data TEXT NOT NULL, created_at TEXT, updated_at TEXT, deleted INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (table_id, id));").unwrap();        let put = |table: &str, id: &str, data: Value| {            conn.execute("INSERT INTO rows VALUES (?1, ?2, ?3, '2026-11-01T00:00:00Z', '2026-11-01T00:00:00Z', 0)", rusqlite::params![table, id, data.to_string()]).unwrap();        };        let thread = "21111111-1111-4111-8111-111111111111";        for i in 0..5 {            put("message", &format!("20000000-0000-4000-8000-00000000000{i}"), json!({"thread_id": thread, "sent_at": format!("2026-11-01T0{i}:00:00Z"), "channel": "whatsapp", "body": format!("{WORD} recovered {i}"), "external_id": format!("rec-{i}")}));        }        put("message_reaction", "react:20000000-0000-4000-8000-000000000001:15550100999", json!({"thread_id": thread, "message_id": "20000000-0000-4000-8000-000000000001", "actor": "15550100999", "emoji": "👍"}));        put("thread", thread, json!({"last_message_at": "2026-11-01T04:00:00Z", "kind": "dm", "title": format!("{WORD} hide")}));        let mail = "23333333-3333-4333-8333-333333333333";        put("email", "24444444-4444-4444-8444-444444444444", json!({"thread_id": mail, "sent_at": "2026-11-01T05:00:00Z", "subject": format!("{WORD} survey"), "body": format!("The {WORD} came back."), "from_email": "ada@example.org", "external_id": "<rec@example.org>"}));        put("email_thread", mail, json!({"first_at": "2026-11-01T05:00:00Z", "last_at": "2026-11-01T05:00:00Z", "subject": format!("{WORD} survey"), "external_key": "<rec@example.org>"}));    }    let file = open_file(&file_path).unwrap();    let progress = open_progress(&dir.path().join("recovered.db.landed.db")).unwrap();    let options = LandOptions { batch: 2, ..LandOptions::default() };    let landed = land(&client, &file, &progress, &database_id, &dk, &options).expect("a run");    println!("WALK land {}", report(&landed));    for run in &landed {        assert!(run.done() && run.sent == run.in_file, "{run:?}");    }    let again = land(&client, &file, &progress, &database_id, &dk, &options).expect("a second run");    for run in &again {        assert!(run.done() && run.sent == 0 && run.already == run.in_file, "a second run sends nothing: {run:?}");    }    let rows = export(&base, &token);    for (table, count) in [("thread", 1), ("message", 5), ("message_reaction", 1), ("email", 1), ("email_thread", 1)] {        let held = of(&rows, table);        assert_eq!(held.len(), count, "{table}");        for row in &held {            assert!(row["data"]["sealed_enc"].is_string(), "{table} {} is not sealed", row["id"]);            let text = row.to_string();            assert!(!text.contains(WORD) && !text.contains("15550100999") && !text.contains("ada@example.org"), "{table} {} holds a sealed word in the clear", row["id"]);        }        println!("WALK sealed {table} {}", held.len());    }    println!("WALK done");}/// Sends the batch at the head of its queue each pass and drops it only once/// the object took it, as the WhatsApp helper acks a page only after its/// batches landed: a refused batch is offered again on the next pass.struct Acking {    queue: Arc<Mutex<VecDeque<IngestBatch>>>,    runs: Arc<AtomicUsize>,}impl Importer for Acking {    fn key(&self) -> SourceKey {        SourceKey::Whatsapp    }    fn schedule(&self) -> Schedule {        Schedule::Every(Duration::from_secs(3600))    }    fn probe(&self) -> Probe {        Probe::ready()    }    fn run(&self, cursor: Option<&str>, ctx: &mut RunContext<'_>) -> Result<String, RunError> {        let head = self.queue.lock().unwrap().front().cloned();        let sent = match head {            Some(batch) => ctx.send(batch),            None => Ok(()),        };        self.runs.fetch_add(1, Ordering::SeqCst);        sent?;        self.queue.lock().unwrap().pop_front();        Ok(cursor.unwrap_or("e2e").to_string())    }}/// The owner's Mac, on the DEV Worker with a synthetic number (22 Nov 2026):/// a phone founded the vault, minted the data key and saved a recovery code;/// then a Mac signs in afresh. Its passes publish its vault key and wait; a/// WhatsApp batch queued meanwhile is refused (`seal_key_missing`, said on the/// card as words),/// never sent in the clear and never dropped; the recovery code typed once/// opens the vault; then that same batch, a mailbox and a page of calls land,/// every row of a sealed table sealed (`sealed_enc`, no sealed column in the/// clear) — the Worker's sealed_in_clear rule passed by every sink.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e a_mac_joins_a_vault_a_phone_founded -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker: run by hand"]fn a_mac_joins_a_vault_a_phone_founded() {    use base64::Engine as _;    use cotton_core::vault::recovery_code as rc;    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev") || base.contains("127.0.0.1"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let dir = tempfile::tempdir().unwrap();    // ── the phone: signs in, founds the vault on its own row, mints the data key, saves a recovery code ──    let open = ObjectClient::new(base.clone(), None).unwrap();    let phone_device = format!("walk-phone-{}", std::process::id());    let asked = open.ask_code(&phone, &phone_device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &phone_device).unwrap();    let database_id = asked.database_id.clone();    let phone_client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let held_keys = phone_client.sync_page(0, &[cotton_client::seal::SEAL_KEY_TABLE], None).unwrap();    assert!(        held_keys["rows"].as_array().is_none_or(|rows| rows.is_empty()),        "a fresh synthetic number: this one already holds a vault ({database_id})"    );    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    let wrapped = cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap();    phone_client        .put_key_row(            &cotton_mac::ids::row_id("walk-phone-key", &phone_device),            &json!({ "device_id": phone_device, "name": "Walk phone", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": wrapped, "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-22T06:00:00.000Z").unwrap();    phone_client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let recovery = rc::mint();    let salt = rc::salt();    let kdf = rc::Kind::Code.kdf();    let keys = rc::derive(rc::normalize(&recovery).unwrap().as_bytes(), &salt, kdf).unwrap();    phone_client        .post_route(            "/v1/recovery/set",            &json!({ "kind": "code", "salt": b64.encode(salt), "kdf": kdf.text(), "auth_hash": rc::auth_hash(&keys.auth), "wrapped": rc::wrap(&keys.wrap, rc::Kind::Code, 1, vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .expect("the phone saves its recovery code");    let owner: Value = reqwest::blocking::Client::new()        .post(format!("{base}/v1/act"))        .bearer_auth(&signed.credential)        .json(&json!({ "act": "mint_token", "args": { "name": "walk mac", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = owner["token"].as_str().expect("an owner token for the export").to_string();    println!("WALK phone founded the vault, minted the data key and saved a recovery code");    // ── the Mac signs in afresh; its vault waits ──    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let port = imap(vec![        (1, "04-Oct-2026 10:00:05 +0000", email("<root@example.org>", "Sun, 4 Oct 2026 10:00:00 +0000", "Lunch at the orchard?", None, "Owner <owner@example.com>", "Lunch tomorrow by the orchard gate?")),        (2, "05-Oct-2026 09:30:05 +0000", email("<r1@example.org>", "Mon, 5 Oct 2026 09:30:00 +0000", "Re: Lunch at the orchard?", Some("<root@example.org>"), "Ada Example <ada@example.org>", "Noon works.")),    ]);    let mail = MailImporter::new(&dir.path().join("mail"));    mail.command("credentials", &json!({ "address": "owner@example.com", "password": "app-pw", "imapHost": format!("127.0.0.1:{port}"), "imapTls": false })).unwrap();    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: format!("walk-mac-{}", std::process::id()),        machine: "walk-mac".into(),        device_name: "Walk Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let app = App::open(config, vec![Box::new(Acking { queue: Arc::clone(&queue), runs: Arc::clone(&runs) }), Box::new(mail)], Box::new(MemoryKeyring::default())).unwrap();    let asked = app.call("askCode", &json!({ "phone": phone }));    let signed = app.call("signIn", &json!({ "databaseId": asked["databaseId"], "challengeId": asked["challengeId"], "code": code }));    assert_eq!(signed["ok"], true, "signIn: {signed}");    let mut batch: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    batch.workspace_id = database_id.clone();    batch.messages[1].media = None;    queue.lock().unwrap().push_back(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: vec![] }, read: 2, cursor: None });    let calls: Value = fixture("calls");    let calls: Vec<cotton_client::ingest::DeviceCall> = serde_json::from_value(calls["calls"].clone()).unwrap();    let call_count = calls.len();    queue.lock().unwrap().push_back(IngestBatch { work: IngestWork::Calls { calls }, read: call_count as i64, cursor: None });    assert_eq!(app.call("start", &json!({ "token": signed["credential"], "phone": phone }))["ok"], true);    let status = wait_for(&app, |s| s["vault"]["state"] == "waiting" && runs.load(Ordering::SeqCst) > 0 && s["sources"][0]["phase"] != "running");    println!("WALK vault {} · {}", status["vault"]["state"], status["vault"]["detail"]);    let refused = status["sources"][0]["error"].as_str().unwrap_or_default().to_string();    println!("WALK the queued WhatsApp batch while the vault waits: {refused}");    assert_eq!(refused, cotton_mac::importer::WAITS_FOR_THE_VAULT, "a sealed write waits, said in words, while the vault is shut: {status}");    assert_eq!(queue.lock().unwrap().len(), 2, "nothing queued was dropped");    let held = export(&base, &token);    for table in ["message", "thread", "email", "email_thread", "call"] {        assert!(of(&held, table).is_empty(), "nothing of {table} went up while the vault was shut");    }    // ── the recovery code, typed once, opens the vault ──    let opened_vault = app.call("openByCode", &json!({ "code": recovery }));    assert_eq!(opened_vault["ok"], true, "openByCode: {opened_vault}");    assert_eq!(app.call("status", &json!({}))["vault"]["state"], "open");    println!("WALK the recovery code opened the vault on the Mac");    // ── the same batch, then the calls, then the mailbox land sealed ──    let status = pass_of(&app, &runs, 0, "whatsapp");    assert_eq!(status["sources"][0]["error"], Value::Null, "the queued WhatsApp batch: {status}");    let status = pass_of(&app, &runs, 0, "whatsapp");    assert_eq!(status["sources"][0]["error"], Value::Null, "the calls: {status}");    assert!(queue.lock().unwrap().is_empty(), "every queued batch landed");    let status = pass_of(&app, &runs, 1, "mail");    assert_eq!(status["sources"][1]["error"], Value::Null, "the mail pass: {status}");    app.stop();    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    let client = ObjectClient::new(base.clone(), Some(signed["credential"].as_str().unwrap().to_string())).unwrap();    let reader = cotton_mac::copy::Copy::open(&dir.path().join("reader.db"), &database_id, keys.clone()).unwrap();    reader.refresh(&client).unwrap();    let rows = export(&base, &token);    let definitions = client.definitions().unwrap();    for table in ["thread", "message", "message_contact", "email", "email_thread", "email_participant", "call"] {        let held = of(&rows, table);        assert!(!held.is_empty(), "no {table} landed");        let sealed_columns: Vec<String> = definitions["tables"]            .as_array()            .unwrap()            .iter()            .find(|t| t["id"] == table)            .map(|t| {                let clear: Vec<&str> = t["seal"]["clear"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();                t["columns"].as_array().into_iter().flatten().filter_map(|c| c["key"].as_str()).filter(|k| !clear.contains(k)).map(str::to_string).collect()            })            .unwrap_or_default();        for row in &held {            assert!(row["data"]["sealed_enc"].is_string(), "{table} {} is not sealed", row["id"]);            for column in &sealed_columns {                assert!(row["data"].get(column).is_none(), "{table} {} holds {column} in the clear", row["id"]);            }        }        println!("WALK sealed {table} {}", held.len());    }    let read = opened(&reader, rows);    assert_eq!(of(&read, "message").len(), 2, "both queued messages, opened");    assert_eq!(of(&read, "call").len(), call_count, "every call, opened");    assert_eq!(of(&read, "email").len(), 2, "both emails, opened");    assert!(of(&read, "email_thread").iter().any(|t| t["data"]["subject"].as_str().is_some_and(|s| s.contains("orchard"))), "the thread's subject opens");    println!("WALK done");}/// This Mac approved from the phone on the DEV Worker (synthetic number): a/// phone founds the vault and mints the data key; a Mac with a device key asks/// to be approved; the phone opens the ask, works out the code from the Mac's/// reveal, the code the Mac shows is the same, the phone approves and wraps the/// vault's key for the Mac's vault key on the Mac's own row (as/// `signin.approve` does); the Mac claims its credential, its first pass opens/// the vault with no recovery code, and a WhatsApp batch lands sealed.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e a_mac_is_approved_from_the_phone_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker: run by hand"]fn a_mac_is_approved_from_the_phone_on_dev() {    use base64::Engine as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev") || base.contains("127.0.0.1"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let dir = tempfile::tempdir().unwrap();    // ── the phone founds the vault ──    let open = ObjectClient::new(base.clone(), None).unwrap();    let phone_device = format!("walk-phone-{}", std::process::id());    let asked = open.ask_code(&phone, &phone_device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &phone_device).unwrap();    let database_id = asked.database_id.clone();    let phone_client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    phone_client        .put_key_row(            &cotton_mac::ids::row_id("walk-phone-key", &phone_device),            &json!({ "device_id": phone_device, "name": "Walk phone", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-22T06:00:00.000Z").unwrap();    phone_client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let owner: Value = reqwest::blocking::Client::new()        .post(format!("{base}/v1/act"))        .bearer_auth(&signed.credential)        .json(&json!({ "act": "mint_token", "args": { "name": "walk mac", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = owner["token"].as_str().expect("an owner token for the export").to_string();    // ── the Mac asks ──    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: "install-uuid".into(),        machine: "walk-mac".into(),        device_name: "Walk Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let device = cotton_mac::approval::DeviceKey::load_or_mint(&MemoryKeyring::default()).unwrap();    let mac_device = device.id();    let app = App::open_as(config, vec![Box::new(Acking { queue: Arc::clone(&queue), runs: Arc::clone(&runs) })], Box::new(MemoryKeyring::default()), Some(device)).unwrap();    let asking = app.call("askApproval", &json!({ "phone": phone }));    assert_eq!(asking["ok"], true, "askApproval: {asking}");    println!("WALK the Mac asks: {}", asking["line"]);    // ── the phone opens the ask: its nonce, then the Mac's reveal, then the code ──    let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap();    let ask = approvals["asks"].as_array().unwrap().iter().find(|a| a["device_id"] == mac_device.as_str()).cloned().expect("the phone sees the Mac's ask");    let ask_id = ask["ask_id"].as_str().unwrap().to_string();    assert_eq!(ask["device_name"], "Walk Mac");    let vault_key = ask["vault_key"].as_str().expect("the ask names the Mac's vault key").to_string();    let nonce_b = [21u8; 32];    phone_client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();    let shown = app.call("askPoll", &json!({}));    let mac_code = shown["code"].as_str().expect("the Mac shows a code once the phone opened the ask").to_string();    println!("WALK the Mac shows: {} {mac_code}", shown["line"]);    let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap();    let ask = approvals["asks"].as_array().unwrap().iter().find(|a| a["ask_id"] == ask_id.as_str()).cloned().unwrap();    let reveal: [u8; 32] = b64.decode(ask["reveal"].as_str().expect("the Mac revealed")).unwrap().try_into().unwrap();    let device_bytes: [u8; 32] = b64.decode(&mac_device).unwrap().try_into().unwrap();    let vault_bytes: [u8; 32] = b64.decode(&vault_key).unwrap().try_into().unwrap();    let phone_code = shown_code(&sas_of(&device_bytes, Some(&vault_bytes), &reveal, &nonce_b));    assert_eq!(mac_code, phone_code, "both screens show the same code");    // ── the phone approves and lets the Mac into the vault ──    phone_client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();    phone_client        .act(            Act::Create,            cotton_mac::vault::VAULT_KEY_TABLE,            &cotton_mac::copy::uuid_v4(),            &json!({ "device_id": mac_device, "name": "Walk Mac", "public_key": vault_key, "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .expect("the phone's approval keeps the Mac's wrap");    let approved = app.call("askPoll", &json!({}));    assert_eq!(approved["state"], "approved", "{approved}");    let credential = approved["credential"].as_str().unwrap().to_string();    println!("WALK the Mac is approved: {}", approved["line"]);    // ── signed in and let in: a batch lands sealed, no recovery code ──    let mut batch: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    batch.workspace_id = database_id.clone();    batch.messages[1].media = None;    queue.lock().unwrap().push_back(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: vec![] }, read: 2, cursor: None });    assert_eq!(app.call("start", &json!({ "token": credential, "phone": phone }))["ok"], true);    let status = wait_for(&app, |s| runs.load(Ordering::SeqCst) > 0 && s["sources"][0]["phase"] != "running");    assert_eq!(status["vault"]["state"], "open", "the first pass opens the vault: {status}");    assert_eq!(status["sources"][0]["error"], Value::Null, "{status}");    assert!(queue.lock().unwrap().is_empty());    app.stop();    let rows = export(&base, &token);    let devices: Vec<&Value> = of(&rows, "device").into_iter().filter(|r| r["data"]["device_id"] == mac_device.as_str()).collect();    assert_eq!(devices.len(), 1, "the Mac's device row names its device key");    for table in ["thread", "message"] {        let held = of(&rows, table);        assert!(!held.is_empty() && held.iter().all(|r| r["data"]["sealed_enc"].is_string()), "{table} sealed");    }    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    let reader = cotton_mac::copy::Copy::open(&dir.path().join("reader.db"), &database_id, keys).unwrap();    reader.refresh(&ObjectClient::new(base.clone(), Some(credential)).unwrap()).unwrap();    assert_eq!(of(&opened(&reader, rows), "message").len(), 2);    println!("WALK done: the Mac opened the vault and landed 2 messages sealed");}/// The owner's path on 22 Nov 2026, on the DEV Worker (synthetic number): the Mac signs in BY A CODE (no approval),/// so its passes publish its vault key row with no wrap and wait; then from the not-let-in panel it asks with no/// number typed, the phone opens the ask, the codes match, the phone approves and wraps the vault's key onto the/// Mac's OWN row (what `signin.approve` does when its copy holds that row), and the Mac, started with the new/// credential, opens the vault at once and lands its batch sealed.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e a_mac_signed_in_by_code_is_let_in_by_one_approval_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker: run by hand"]fn a_mac_signed_in_by_code_is_let_in_by_one_approval_on_dev() {    use base64::Engine as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev") || base.contains("127.0.0.1"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let dir = tempfile::tempdir().unwrap();    // ── the phone founds the vault ──    let open = ObjectClient::new(base.clone(), None).unwrap();    let phone_device = format!("walk-phone-{}", std::process::id());    let asked = open.ask_code(&phone, &phone_device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &phone_device).unwrap();    let database_id = asked.database_id.clone();    let phone_client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    phone_client        .put_key_row(            &cotton_mac::ids::row_id("walk-phone-key", &phone_device),            &json!({ "device_id": phone_device, "name": "Walk phone", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-22T06:00:00.000Z").unwrap();    phone_client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    // ── the Mac signs in by a code: signed in, not let in ──    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: "install-uuid".into(),        machine: "walk-mac".into(),        device_name: "Walk Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let device = cotton_mac::approval::DeviceKey::load_or_mint(&MemoryKeyring::default()).unwrap();    let mac_device = device.id();    let app = App::open_as(config, vec![Box::new(Acking { queue: Arc::clone(&queue), runs: Arc::clone(&runs) })], Box::new(MemoryKeyring::default()), Some(device)).unwrap();    let challenge = app.call("askCode", &json!({ "phone": phone }));    assert_eq!(challenge["ok"], true, "askCode: {challenge}");    let by_code = app.call("signIn", &json!({ "databaseId": challenge["databaseId"], "challengeId": challenge["challengeId"], "code": code }));    assert_eq!(by_code["ok"], true, "signIn: {by_code}");    let mut batch: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    batch.workspace_id = database_id.clone();    batch.messages[1].media = None;    queue.lock().unwrap().push_back(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: vec![] }, read: 2, cursor: None });    assert_eq!(app.call("start", &json!({ "token": by_code["credential"], "phone": by_code["phone"] }))["ok"], true);    let waiting = wait_for(&app, |s| runs.load(Ordering::SeqCst) > 0 && s["sources"][0]["phase"] != "running");    assert_eq!(waiting["vault"]["state"], "waiting", "signed in by a code, not let in: {waiting}");    assert_eq!(waiting["vault"]["ask"], "Show a code to scan");    println!("WALK signed in by a code, waiting: {}", waiting["sources"][0]["error"]);    // ── Approve on another device, from the panel: no number typed ──    let asking = app.call("askApproval", &json!({}));    assert_eq!(asking["ok"], true, "askApproval: {asking}");    let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap();    let ask = approvals["asks"].as_array().unwrap().iter().find(|a| a["device_id"] == mac_device.as_str()).cloned().expect("the phone sees the Mac's ask");    let ask_id = ask["ask_id"].as_str().unwrap().to_string();    let vault_key = ask["vault_key"].as_str().expect("the ask names the Mac's vault key").to_string();    let nonce_b = [21u8; 32];    phone_client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();    let shown = app.call("askPoll", &json!({}));    let mac_code = shown["code"].as_str().expect("the Mac shows a code").to_string();    let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap();    let ask = approvals["asks"].as_array().unwrap().iter().find(|a| a["ask_id"] == ask_id.as_str()).cloned().unwrap();    let reveal: [u8; 32] = b64.decode(ask["reveal"].as_str().expect("the Mac revealed")).unwrap().try_into().unwrap();    let device_bytes: [u8; 32] = b64.decode(&mac_device).unwrap().try_into().unwrap();    let vault_bytes: [u8; 32] = b64.decode(&vault_key).unwrap().try_into().unwrap();    assert_eq!(mac_code, shown_code(&sas_of(&device_bytes, Some(&vault_bytes), &reveal, &nonce_b)), "both screens show the same code");    // ── the phone approves and wraps onto the Mac's own row, as its copy holds it ──    phone_client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();    let page = phone_client.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], None).unwrap();    let mac_rows: Vec<&Value> = page["rows"].as_array().into_iter().flatten().filter(|r| r["data"]["device_id"] == mac_device.as_str() && r["deleted"] != true).collect();    println!("WALK the Mac's vault rows before the wrap: {}", mac_rows.len());    assert_eq!(mac_rows.len(), 1, "the Mac published one row");    assert_eq!(mac_rows[0]["data"]["public_key"], vault_key.as_str(), "the row names the key the ask named");    let row_id = mac_rows[0]["id"].as_str().unwrap().to_string();    let wrapped = phone_client.act(        Act::Update,        cotton_mac::vault::VAULT_KEY_TABLE,        &row_id,        &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }),    );    println!("WALK the phone's wrap onto the Mac's row: {wrapped:?}");    wrapped.expect("the object keeps the approved wrap on the Mac's own row");    // ── the Mac claims, starts with the credential, and opens at once ──    let approved = app.call("askPoll", &json!({}));    assert_eq!(approved["state"], "approved", "{approved}");    let before = runs.load(Ordering::SeqCst);    let started = Instant::now();    assert_eq!(app.call("start", &json!({ "token": approved["credential"], "phone": approved["phone"] }))["ok"], true);    let status = wait_for(&app, |s| runs.load(Ordering::SeqCst) > before && s["sources"][0]["phase"] != "running");    println!("WALK after the approval, {:?}: vault {} source {}", started.elapsed(), status["vault"]["state"], status["sources"][0]["error"]);    assert_eq!(status["vault"]["state"], "open", "one approval lets the Mac in: {status}");    assert_eq!(status["sources"][0]["error"], Value::Null, "{status}");    assert!(started.elapsed() < Duration::from_secs(20), "the approval ran a pass at once");    assert!(queue.lock().unwrap().is_empty(), "the waiting batch landed");    app.stop();    let _ = dk;    // ── the approving phone's state on 22 Nov: a second, unwrapped row under its own device id and key, as another    // copy on the same phone published. Its own re-wrap of that row (`take_own_key`) is no founding.    let phone_public = b64.encode(cotton_core::vault::wrap::public_of(&secret));    let second = format!("walk-phone-second-{}", std::process::id());    phone_client.put_key_row(&second, &json!({ "device_id": phone_device, "name": "Walk phone", "public_key": phone_public, "wrapped_vmk": Value::Null, "vmk_version": 0 })).unwrap();    let rewrap = phone_client.act(        Act::Update,        cotton_mac::vault::VAULT_KEY_TABLE,        &second,        &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),    );    println!("WALK the phone's own re-wrap of its second row: {}", match &rewrap { Ok(_) => "kept".to_string(), Err(error) => format!("{error:?}") });    println!("WALK done");}/// GETTING-IN.md and OWNER.md (22 Nov 2026) on the DEV Worker: a Mac signed in by a code shows its square code; a/// phone that holds the key scans it (the nonce read optically, checked against the ask's commitment), approves with/// `scanned` and hands the key over; the Mac claims and opens, and says nothing of "Approved" before. A second phone/// signed in without the key sees `holds: false` and its approval is refused `approver_locked`.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e a_mac_is_let_in_by_a_scan_of_its_square_code_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker: run by hand"]fn a_mac_is_let_in_by_a_scan_of_its_square_code_on_dev() {    use base64::Engine as _;    use cotton_core::vault::approval::{commit_of, read_scan};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev") || base.contains("127.0.0.1"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let dir = tempfile::tempdir().unwrap();    // ── the phone founds the vault ──    let open = ObjectClient::new(base.clone(), None).unwrap();    let phone_device = format!("scan-phone-{}", std::process::id());    let asked = open.ask_code(&phone, &phone_device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &phone_device).unwrap();    let phone_client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [9u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    phone_client        .put_key_row(            &cotton_mac::ids::row_id("scan-phone-key", &phone_device),            &json!({ "device_id": phone_device, "name": "Scan phone", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (_dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-22T06:00:00.000Z").unwrap();    phone_client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    // ── a second phone, signed in, holding no key ──    let other_device = format!("scan-other-{}", std::process::id());    let asked_other = open.ask_code(&phone, &other_device).unwrap();    let signed_other = open.sign_in(&asked_other.database_id, &asked_other.challenge_id, &code, &other_device).unwrap();    let other_client = ObjectClient::new(base.clone(), Some(signed_other.credential.clone())).unwrap();    // ── the Mac signs in by a code, waits, and asks by itself with a square code ──    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: "install-uuid".into(),        machine: "scan-mac".into(),        device_name: "Scan Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let device = cotton_mac::approval::DeviceKey::load_or_mint(&MemoryKeyring::default()).unwrap();    let mac_device = device.id();    let app = App::open_as(config, vec![Box::new(Acking { queue: Arc::clone(&queue), runs: Arc::clone(&runs) })], Box::new(MemoryKeyring::default()), Some(device)).unwrap();    let challenge = app.call("askCode", &json!({ "phone": phone }));    let by_code = app.call("signIn", &json!({ "databaseId": challenge["databaseId"], "challengeId": challenge["challengeId"], "code": code }));    assert_eq!(by_code["ok"], true, "signIn: {by_code}");    assert_eq!(app.call("start", &json!({ "token": by_code["credential"], "phone": by_code["phone"] }))["ok"], true);    let waiting = wait_for(&app, |s| runs.load(Ordering::SeqCst) > 0 && s["sources"][0]["phase"] != "running");    assert_eq!(waiting["vault"]["state"], "waiting", "{waiting}");    let card = app.call("askApproval", &json!({}));    assert_eq!(card["ok"], true, "askApproval: {card}");    assert_eq!(card["heading"], "One more step: open another device of yours");    assert!(card["code"].is_null(), "no digits before the phone opens the ask");    let text = card["qr"]["text"].as_str().expect("a square code").to_string();    assert!(!text.contains("://"), "never a link: {text}");    println!("WALK the Mac shows its square code ({} modules)", card["qr"]["size"]);    // ── the keyless phone sees no ask to approve, and is refused if it tries ──    let theirs = other_client.get_json("/v1/approvals", &[]).unwrap();    assert_eq!(theirs["holds"], false, "a phone with no key does not hold: {theirs}");    let (ask_id, nonce) = read_scan(&text).expect("a Cotton code");    let refused = other_client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id, "scanned": b64.encode(nonce) }));    println!("WALK the keyless phone's approval: {refused:?}");    assert!(format!("{refused:?}").contains("approver_locked"), "{refused:?}");    // ── the holding phone scans: checks the commitment itself, approves with the scan, wraps onto the Mac's row ──    let mine = phone_client.get_json("/v1/approvals", &[]).unwrap();    assert_eq!(mine["holds"], true);    let ask = mine["asks"].as_array().unwrap().iter().find(|a| a["ask_id"] == ask_id.as_str()).cloned().expect("the phone sees the Mac's ask");    assert_eq!(ask["device_kind"], "mac", "the card can say Your Mac");    let vault_key = ask["vault_key"].as_str().unwrap().to_string();    let device_bytes = b64.decode(&mac_device).unwrap();    let vault_bytes: [u8; 32] = b64.decode(&vault_key).unwrap().try_into().unwrap();    assert_eq!(ask["commit"].as_str().unwrap(), b64.encode(commit_of(&device_bytes, Some(&vault_bytes), &nonce)), "the scanned nonce is the one the Mac committed to");    phone_client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id, "scanned": b64.encode(nonce) })).expect("approved by the scan");    let page = phone_client.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], None).unwrap();    let row_id = page["rows"].as_array().into_iter().flatten().find(|r| r["data"]["device_id"] == mac_device.as_str() && r["deleted"] != true).expect("the Mac's row")["id"].as_str().unwrap().to_string();    phone_client        .act(Act::Update, cotton_mac::vault::VAULT_KEY_TABLE, &row_id, &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }))        .expect("the key handed over");    // ── the Mac: said yes, never "Approved"; then open ──    let approved = app.call("askPoll", &json!({}));    assert_eq!(approved["state"], "approved", "{approved}");    assert!(!approved.to_string().contains("Approved"), "{approved}");    let before = runs.load(Ordering::SeqCst);    let started = Instant::now();    assert_eq!(app.call("start", &json!({ "token": approved["credential"], "phone": approved["phone"] }))["ok"], true);    let status = wait_for(&app, |s| runs.load(Ordering::SeqCst) > before && s["sources"][0]["phase"] != "running");    println!("WALK after the scan, {:?}: vault {}", started.elapsed(), status["vault"]["state"]);    assert_eq!(status["vault"]["state"], "open", "one scan lets the Mac in: {status}");    app.stop();    println!("WALK done");}/// The Mac's half of a walk with a REAL phone app on the DEV Worker (an emulator's Words, say): the Mac signs in to/// `COTTON_E2E_PHONE` by a code, so it is signed in and not let in, asks from the not-let-in panel, prints the code it/// shows once the phone opens the ask, and waits up to `COTTON_E2E_WAIT` seconds (300) for the approval; approved,/// it starts with the credential and prints whether its vault opened.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e the_mac_asks_a_real_phone_by_hand -- --ignored --nocapture#[test]#[ignore = "the Mac's half of a walk by hand on the dev Worker"]fn the_mac_asks_a_real_phone_by_hand() {    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let wait = std::env::var("COTTON_E2E_WAIT").ok().and_then(|w| w.parse().ok()).unwrap_or(300u64);    let dir = tempfile::tempdir().unwrap();    let queue = Arc::new(Mutex::new(VecDeque::new()));    let runs = Arc::new(AtomicUsize::new(0));    let config = Config {        data_dir: dir.path().join("data"),        object_url: base.clone(),        device_id: "install-uuid".into(),        machine: "walk-mac".into(),        device_name: "Walk Mac".into(),        app_version: APP_VERSION.into(),        home: dir.path().to_path_buf(),        helpers_dir: None,    };    std::fs::create_dir_all(&config.data_dir).unwrap();    let device = cotton_mac::approval::DeviceKey::load_or_mint(&MemoryKeyring::default()).unwrap();    let app = App::open_as(config, vec![Box::new(Acking { queue: Arc::clone(&queue), runs: Arc::clone(&runs) })], Box::new(MemoryKeyring::default()), Some(device)).unwrap();    let challenge = app.call("askCode", &json!({ "phone": phone }));    assert_eq!(challenge["ok"], true, "askCode: {challenge}");    let by_code = app.call("signIn", &json!({ "databaseId": challenge["databaseId"], "challengeId": challenge["challengeId"], "code": code }));    assert_eq!(by_code["ok"], true, "signIn: {by_code}");    let database_id = challenge["databaseId"].as_str().unwrap().to_string();    let mut batch: ImportBatch = serde_json::from_value(fixture("messages")).unwrap();    batch.workspace_id = database_id;    batch.messages[1].media = None;    queue.lock().unwrap().push_back(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: vec![] }, read: 2, cursor: None });    assert_eq!(app.call("start", &json!({ "token": by_code["credential"], "phone": by_code["phone"] }))["ok"], true);    let waiting = wait_for(&app, |s| runs.load(Ordering::SeqCst) > 0 && s["sources"][0]["phase"] != "running");    println!("HAND Mac signed in by a code: vault {} / {}", waiting["vault"]["state"], waiting["sources"][0]["error"]);    let asking = app.call("askApproval", &json!({}));    assert_eq!(asking["ok"], true, "askApproval: {asking}");    println!("HAND Mac asks: {} | {}", asking["line"], asking["heading"]);    let started = Instant::now();    let mut last = String::new();    let approved = loop {        assert!(started.elapsed() < Duration::from_secs(wait), "no approval in {wait} s; last: {last}");        std::thread::sleep(Duration::from_secs(3));        let card = app.call("askPoll", &json!({}));        let said = format!("state {} code {} line {}", card["state"], card["code"], card["line"]);        if said != last {            println!("HAND {:>4}s Mac card: {said}", started.elapsed().as_secs());            last = said;        }        if card["state"] == "approved" {            break card;        }        if card["done"] == true {            panic!("the ask ended: {card}");        }    };    let before = runs.load(Ordering::SeqCst);    assert_eq!(app.call("start", &json!({ "token": approved["credential"], "phone": approved["phone"] }))["ok"], true);    let status = wait_for(&app, |s| runs.load(Ordering::SeqCst) > before && s["sources"][0]["phase"] != "running");    println!("HAND after the approval: vault {} / source error {}", status["vault"]["state"], status["sources"][0]["error"]);    app.stop();}/// The phone's half of a walk of the built Mac app by hand (the dev flavour,/// `com.decemberfm.cotton.mac.dev`, pointed at the DEV Worker): signs in the/// synthetic number, founds the vault and mints the data key, then waits up to/// ten minutes for a Mac's approval ask, opens it, prints the code to compare/// with the Mac's screen, approves and wraps the vault's key for the Mac. Then/// it waits for the Mac's device row and prints what the Mac landed.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e the_phone_approves_a_mac_by_hand -- --ignored --nocapture#[test]#[ignore = "the phone's half of a walk by hand on the dev Worker"]fn the_phone_approves_a_mac_by_hand() {    use base64::Engine as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let open = ObjectClient::new(base.clone(), None).unwrap();    let phone_device = format!("hand-phone-{}", std::process::id());    let asked = open.ask_code(&phone, &phone_device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &phone_device).unwrap();    let phone_client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    phone_client        .put_key_row(            &cotton_mac::ids::row_id("hand-phone-key", &phone_device),            &json!({ "device_id": phone_device, "name": "Hand phone", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (_dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-22T06:00:00.000Z").unwrap();    phone_client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    println!("HAND phone ready: ask from the Mac now");    let started = Instant::now();    let ask = loop {        assert!(started.elapsed() < Duration::from_secs(600), "no ask in ten minutes");        let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap();        if let Some(ask) = approvals["asks"].as_array().and_then(|asks| asks.first()).cloned() {            break ask;        }        std::thread::sleep(Duration::from_secs(2));    };    let ask_id = ask["ask_id"].as_str().unwrap().to_string();    println!("HAND the phone sees: {} wants to sign in", ask["device_name"]);    let nonce_b = [21u8; 32];    phone_client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();    let ask = loop {        let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap();        let ask = approvals["asks"].as_array().unwrap().iter().find(|a| a["ask_id"] == ask_id.as_str()).cloned().unwrap();        if ask["reveal"].is_string() {            break ask;        }        std::thread::sleep(Duration::from_secs(1));    };    let bytes = |text: &str| -> [u8; 32] { b64.decode(text).unwrap().try_into().unwrap() };    let vault_key = ask["vault_key"].as_str().expect("the ask names the Mac's vault key").to_string();    let shown = shown_code(&sas_of(&bytes(ask["device_id"].as_str().unwrap()), Some(&bytes(&vault_key)), &bytes(ask["reveal"].as_str().unwrap()), &nonce_b));    println!("HAND the phone's code: {shown}");    std::thread::sleep(Duration::from_secs(8));    phone_client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();    phone_client        .act(            Act::Create,            cotton_mac::vault::VAULT_KEY_TABLE,            &cotton_mac::copy::uuid_v4(),            &json!({ "device_id": ask["device_id"], "name": ask["device_name"], "public_key": vault_key, "wrapped_vmk": cotton_core::vault::wrap::wrap(&bytes(&vault_key), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    println!("HAND approved");    let started = Instant::now();    while started.elapsed() < Duration::from_secs(120) {        let page = phone_client.sync_page(0, &["device", "vault_key"], None).unwrap();        let mac = page["rows"].as_array().into_iter().flatten().any(|r| r["table"] == "device" && r["data"]["device_id"] == ask["device_id"]);        if mac {            println!("HAND the Mac's device row is filed");            return;        }        std::thread::sleep(Duration::from_secs(3));    }    panic!("the Mac filed no device row in two minutes");}/// The WhatsApp link's reader itself on the DEV Worker (synthetic number): a/// fake helper on the Go link's socket holds three messages of one chat. While/// the Mac holds no data key the page is refused and never acked (it waits in/// the helper); with the key the same page lands sealed and is acked.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///     cargo test -p cotton-mac --test object_e2e the_whatsapp_link_lands_sealed_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker: run by hand"]fn the_whatsapp_link_lands_sealed_on_dev() {    use base64::Engine as _;    use cotton_client::ingest::sources::whatsapp_link::{WhatsappLinkSource, WhatsappLinkSourceInput};    use cotton_client::ingest::IngestSource as _;    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let dir = tempfile::tempdir().unwrap();    let open = ObjectClient::new(base.clone(), None).unwrap();    let device = format!("wa-mac-{}", std::process::id());    let asked = open.ask_code(&phone, &device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &device).unwrap();    let database_id = asked.database_id.clone();    let client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    client        .put_key_row(            &cotton_mac::ids::row_id("wa-mac-key", &device),            &json!({ "device_id": device, "name": "WA Mac", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-22T06:00:00.000Z").unwrap();    client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let owner: Value = reqwest::blocking::Client::new()        .post(format!("{base}/v1/act"))        .bearer_auth(&signed.credential)        .json(&json!({ "act": "mint_token", "args": { "name": "wa walk", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = owner["token"].as_str().unwrap().to_string();    let account = "15550009999@s.whatsapp.net";    let friend = "15550001111@s.whatsapp.net";    let event = |seq: i64, id: &str, text: &str| {        json!({ "seq": seq, "event": "message", "account": account, "message": { "id": id, "chat": friend, "sender": friend, "from_me": false, "is_group": false, "ts": 1_763_000_000 + seq, "kind": "text", "text": text, "origin": "live" } })    };    let helper = Arc::new(Mutex::new(support::helper::Helper {        outbox: vec![event(1, "WA1", "Are we still on for Sunday?"), event(2, "WA2", "Bring the blue tent."), event(3, "WA3", "Leaving at seven.")],        ..Default::default()    }));    support::helper::fake_helper(dir.path(), Arc::clone(&helper));    let source = WhatsappLinkSource::new(WhatsappLinkSourceInput {        workspace_id: database_id.clone(),        namespace: cotton_store::file_identity::Namespace::of_database(&database_id),        device: "WA Mac".to_string(),        dir: dir.path().to_path_buf(),        media_dir: dir.path().join("media"),    });    let read = |keys: &Arc<cotton_client::seal::HeldDataKeys>, name: &str| {        let copy = cotton_mac::copy::Copy::open(&dir.path().join(name), &database_id, keys.clone()).unwrap();        let sink = ObjectSink::new(&client, database_id.clone()).with_copy(&copy);        source.read(None, &mut |batch| sink.send(batch).map(|_| ()).map_err(|error| error.to_string()))    };    // No data key on this Mac: refused, nothing up, nothing acked.    let locked = read(&cotton_client::seal::HeldDataKeys::new(), "locked.db");    println!("WALK locked: {:?}", locked.as_ref().err());    assert!(locked.is_err(), "the page waits while the vault is shut");    assert!(helper.lock().unwrap().acks.is_empty(), "nothing acked: the messages stay in the helper");    assert_eq!(helper.lock().unwrap().outbox.len(), 3);    assert!(of(&export(&base, &token), "message").is_empty(), "nothing went up");    // The key held: the same page lands sealed and is acked.    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    let landed = read(&keys, "open.db").expect("the page lands");    assert_eq!(landed.cursor, "seq:3");    assert_eq!(helper.lock().unwrap().acks, vec![3]);    let rows = export(&base, &token);    for table in ["thread", "message", "message_contact"] {        let held = of(&rows, table);        assert!(!held.is_empty() && held.iter().all(|r| r["data"]["sealed_enc"].is_string()), "{table} sealed");        println!("WALK sealed {table} {}", held.len());    }    let reader = cotton_mac::copy::Copy::open(&dir.path().join("reader.db"), &database_id, keys).unwrap();    reader.refresh(&client).unwrap();    let opened_rows = opened(&reader, rows);    let bodies: Vec<&str> = of(&opened_rows, "message").iter().filter_map(|m| m["data"]["body"].as_str()).collect();    assert_eq!(bodies.len(), 3, "{bodies:?}");    assert!(bodies.contains(&"Bring the blue tent."));    // Comms queues a text in that chat (sealed, as a phone writes it, its WhatsApp id fixed at the tap); the Mac    // sends it once through its link, marks it sent, and the sent text lands as the owner's message under that id.    let fixed = "3EB0WALKFIXEDATTAP01";    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    let phone_copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("phone.db"), &database_id, keys.clone()).unwrap());    let phone_side = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&phone_copy)));    phone_side        .act(cotton_mac::object::Act::Create, "outbox", "ob-walk-1", &json!({ "channel": "whatsapp", "to": friend, "account": account, "body": "See you at seven.", "status": "queued", "sent_external_id": fixed }))        .expect("the phone queues a sealed text");    let queued_row = of(&export(&base, &token), "outbox").into_iter().find(|r| r["id"] == "ob-walk-1").cloned().expect("queued");    println!("WALK outbox queued {}", queued_row["data"]);    assert!(queued_row["data"]["sealed_enc"].is_string(), "the words go up sealed");    assert!(!queued_row.to_string().contains("See you at seven"), "the object never reads them");    helper.lock().unwrap().accounts = vec![account.to_string()];    let mac_copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("mac-send.db"), &database_id, keys.clone()).unwrap());    let mac = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&mac_copy)));    let socket = dir.path().join(cotton_client::ingest::sources::whatsapp_link::SOCKET_NAME);    let drained = cotton_mac::outbox::drain_whatsapp(&mac, &socket).expect("the Mac drains");    println!("WALK drained {drained:?}");    assert_eq!(drained.sent, 1);    {        let held = helper.lock().unwrap();        assert_eq!(held.sends.len(), 1);        assert_eq!(held.sends[0]["message_id"], fixed, "under the id fixed at the tap");        assert_eq!(held.sends[0]["text"], "See you at seven.");        assert_eq!(held.sends[0]["chat"], friend);    }    assert_eq!(cotton_mac::outbox::drain_whatsapp(&mac, &socket).unwrap().sent, 0, "never twice");    assert_eq!(helper.lock().unwrap().sends.len(), 1);    let landed = read(&keys, "open.db").expect("the sent text lands");    println!("WALK echo cursor {}", landed.cursor);    let rows = export(&base, &token);    let sent_row = of(&rows, "outbox").into_iter().find(|r| r["id"] == "ob-walk-1").cloned().unwrap();    println!("WALK outbox after {}", sent_row["data"]);    assert_eq!(sent_row["data"]["status"], "sent");    assert!(sent_row["data"]["sealed_enc"].is_string());    let reader = cotton_mac::copy::Copy::open(&dir.path().join("reader2.db"), &database_id, keys).unwrap();    reader.refresh(&client).unwrap();    let opened_rows = opened(&reader, rows);    let messages = of(&opened_rows, "message");    let mine: Vec<&Value> = messages.into_iter().filter(|m| m["data"]["external_id"] == fixed).collect();    assert_eq!(mine.len(), 1, "the sent text stands once");    assert_eq!(mine[0]["data"]["body"], "See you at seven.");    assert_eq!(mine[0]["data"]["direction"], "out");    println!("WALK sent text landed once, direction out");    println!("WALK done");}/// A fake Mac for a phone walk of FEEDBACK-2 A (23 Nov 2026), on the DEV Worker with a/// synthetic number: it signs in first, founds the vault and mints the data key, and lands two messages through a fake/// WhatsApp link (so the account is linked, as the owner's is). It prints `WALK READY`; sign the phone in to the same/// number then, ask to be let in, and the walk approves it (printing the six digits the phone shows) and wraps the/// vault's key onto the phone's row. It then waits, the Mac away, for the phone's outbox rows and prints each as the/// Mac reads it (opened: to, account, words, status, the id fixed at the tap). `WALK_HOLD` seconds (default 150) after/// the first row, time for the phone to be seen saying "Waiting to send", it plays the Mac's half for a number with no WhatsApp: the row is marked failed with `send::NOT_ON_WHATSAPP`, as/// mac-import's drain will (whatsmeow `IsOnWhatsApp`). Nothing is sent anywhere.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///   WALK_HOLD=150 cargo test -p cotton-mac --test object_e2e a_fake_mac_for_a_phone_writing_to_a_number_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker and a phone: run by hand"]fn a_fake_mac_for_a_phone_writing_to_a_number_on_dev() {    use base64::Engine as _;    use cotton_client::ingest::sources::whatsapp_link::{WhatsappLinkSource, WhatsappLinkSourceInput};    use cotton_client::ingest::IngestSource as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let hold = Duration::from_secs(std::env::var("WALK_HOLD").ok().and_then(|h| h.parse().ok()).unwrap_or(150u64));    let wait = Duration::from_secs(std::env::var("COTTON_E2E_WAIT").ok().and_then(|w| w.parse().ok()).unwrap_or(2400u64));    let dir = tempfile::tempdir().unwrap();    let open = ObjectClient::new(base.clone(), None).unwrap();    let device = format!("fb2a-mac-{}", std::process::id());    let asked = open.ask_code(&phone, &device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &device).unwrap();    let database_id = asked.database_id.clone();    let client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    client        .put_key_row(            &cotton_mac::ids::row_id("fb2a-mac-key", &device),            &json!({ "device_id": device, "name": "Walk Mac", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-23T06:00:00.000Z").unwrap();    client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    // The link: two messages from an invented friend, through an invented linked number.    let account = "15550190900@s.whatsapp.net";    let friend = "15550190901@s.whatsapp.net";    let event = |seq: i64, id: &str, text: &str| {        json!({ "seq": seq, "event": "message", "account": account, "message": { "id": id, "chat": friend, "sender": friend, "from_me": false, "is_group": false, "ts": 1_763_880_000 + seq, "kind": "text", "text": text, "origin": "live" } })    };    let helper = Arc::new(Mutex::new(support::helper::Helper { outbox: vec![event(1, "WAFB2A1", "Are you coming on Sunday?"), event(2, "WAFB2A2", "Bring the blue tent. Noor is coming too, her number is +1 555 019 0177")], ..Default::default() }));    support::helper::fake_helper(dir.path(), Arc::clone(&helper));    let source = WhatsappLinkSource::new(WhatsappLinkSourceInput {        workspace_id: database_id.clone(),        namespace: cotton_store::file_identity::Namespace::of_database(&database_id),        device: "Walk Mac".to_string(),        dir: dir.path().to_path_buf(),        media_dir: dir.path().join("media"),    });    let copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("copy.db"), &database_id, keys.clone()).unwrap());    let sink = ObjectSink::new(&client, database_id.clone()).with_copy(&copy);    source.read(None, &mut |batch| sink.send(batch).map(|_| ()).map_err(|error| error.to_string())).expect("the link's messages land");    println!("WALK linked: the link's two messages landed sealed");    // WALK_POLLS (CONTRACT "Polls shown"): two invented polls in the same chat, as the Mac's link will land them    // (meta.poll with its voters), and later votes as the link's changes.    let polls = std::env::var("WALK_POLLS").is_ok();    if polls {        let ns = cotton_store::file_identity::Namespace::of_database(&database_id);        // Keyed as the link keys this chat, so the polls land in the chat its words are in.        let phone = cotton_core::import::adapters::wce::phone_from_jid(friend).expect("the friend's number");        let source = |id: &str| json!({ "service": "whatsapp", "account": account, "externalId": id, "chat": friend, "sender": friend, "messageType": "poll", "origin": "live" });        let batch: ImportBatch = serde_json::from_value(json!({            "workspaceId": database_id, "channel": "whatsapp",            "dm": { "label": phone, "phone": phone },            "messages": [                { "direction": "in", "body": "Dinner on Friday?", "sentAt": "2026-11-23T08:00:00.000Z", "externalId": "WAFB2APOLL1",                  "meta": { "source": source("WAFB2APOLL1"), "poll": { "question": "Dinner on Friday?", "selectable": 0,                    "options": [{ "text": "Thai", "votes": 1 }, { "text": "Pizza", "votes": 0 }, { "text": "Stay in and cook", "votes": 0 }],                    "voters": [{ "who": "15550190901", "options": [0], "at": "2026-11-23T08:01:00.000Z" }] } } },                { "direction": "in", "body": "Which day for the trek?", "sentAt": "2026-11-23T08:05:00.000Z", "externalId": "WAFB2APOLL2",                  "meta": { "source": source("WAFB2APOLL2"), "poll": { "question": "Which day for the trek?", "selectable": 1,                    "options": [{ "text": "Saturday", "votes": 0 }, { "text": "Sunday", "votes": 0 }] } } }            ],            "newThreadId": cotton_core::import::whatsapp_keys::whatsapp_thread_id(&ns, &format!("dm:{phone}")),        }))        .unwrap();        sink.send(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: Vec::new() }, read: 2, cursor: None }).expect("the polls land");        println!("WALK polls: two polls landed in the chat with +15550190901");    }    println!("WALK READY: sign the phone in to the same number now and ask to be let in");    // The phone asks to be let in: approved from here, the vault's key wrapped onto its row.    let started = Instant::now();    let nonce_b = [23u8; 32];    let mut opened: Option<(String, String, String)> = None;    'approve: loop {        assert!(started.elapsed() < wait, "no phone asked in time");        let approvals = client.get_json("/v1/approvals", &[]).unwrap_or(Value::Null);        let asks = approvals["asks"].as_array().cloned().unwrap_or_default();        match &opened {            None => {                if let Some(ask) = asks.iter().find(|a| a["vault_key"].is_string()) {                    let ask_id = ask["ask_id"].as_str().unwrap().to_string();                    client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();                    println!("WALK opened the phone's ask ({})", ask["device_name"]);                    opened = Some((ask_id, ask["device_id"].as_str().unwrap().to_string(), ask["vault_key"].as_str().unwrap().to_string()));                }            }            Some((ask_id, asker, vault_key)) => {                let Some(ask) = asks.iter().find(|a| a["ask_id"] == ask_id.as_str()) else {                    opened = None;                    continue;                };                let Some(reveal) = ask["reveal"].as_str() else {                    std::thread::sleep(Duration::from_secs(2));                    continue;                };                let reveal: [u8; 32] = b64.decode(reveal).unwrap().try_into().unwrap();                let device_bytes: [u8; 32] = b64.decode(asker).unwrap().try_into().unwrap();                let vault_bytes: [u8; 32] = b64.decode(vault_key).unwrap().try_into().unwrap();                println!("WALK the phone must show: {}", shown_code(&sas_of(&device_bytes, Some(&vault_bytes), &reveal, &nonce_b)));                std::thread::sleep(Duration::from_secs(5));                client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();                for _ in 0..30 {                    let page = client.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], None).unwrap();                    let row = page["rows"].as_array().into_iter().flatten()                        .find(|r| r["data"]["device_id"] == asker.as_str() && r["data"]["public_key"] == vault_key.as_str() && r["deleted"] != true)                        .and_then(|r| r["id"].as_str().map(str::to_string));                    if let Some(row) = row {                        client                            .act(Act::Update, cotton_mac::vault::VAULT_KEY_TABLE, &row, &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }))                            .expect("the wrap onto the phone's row");                        println!("WALK approved the phone and wrapped the key onto its row");                        break 'approve;                    }                    std::thread::sleep(Duration::from_secs(2));                }                panic!("the phone published no vault key row");            }        }        std::thread::sleep(Duration::from_secs(2));    }    // WALK_LIVE=<n> (23 Nov 2026: how late a Mac's write reaches an open phone): once the    // phone is in, every WALK_HOLD seconds the link lands one incoming text in the friend's chat, then one vote on the    // dinner poll (WALK_POLLS is implied), n of each, and prints the wall-clock time of each write as it is answered,    // so the phone's drawing of each can be timed against it. The text says its own number ("Live text 3").    if let Some(times) = std::env::var("WALK_LIVE").ok().and_then(|n| n.parse::<u32>().ok()) {        assert!(polls, "WALK_LIVE votes on the dinner poll: set WALK_POLLS too");        let phone = cotton_core::import::adapters::wce::phone_from_jid(friend).expect("the friend's number");        let ns = cotton_store::file_identity::Namespace::of_database(&database_id);        let now_ms = || std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis();        for k in 1..=times {            std::thread::sleep(hold);            let id = format!("WAFB2ALIVE{k}-{}", std::process::id());            let at = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();            let batch: ImportBatch = serde_json::from_value(json!({                "workspaceId": database_id, "channel": "whatsapp",                "dm": { "label": phone, "phone": phone },                "messages": [{ "direction": "in", "body": format!("Live text {k}"), "sentAt": at, "externalId": id,                  "meta": { "source": { "service": "whatsapp", "account": account, "externalId": id, "chat": friend, "sender": friend, "messageType": "text", "origin": "live" } } }],                "newThreadId": cotton_core::import::whatsapp_keys::whatsapp_thread_id(&ns, &format!("dm:{phone}")),            }))            .unwrap();            let asked = now_ms();            sink.send(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: Vec::new() }, read: 1, cursor: None }).expect("the text lands");            println!("WALK LIVE text {k} written asked_ms {asked} answered_ms {}", now_ms());            std::thread::sleep(hold);            // Each vote a different set of the friend's, so each one moves the bars: Thai, Pizza, Stay in, in turn.            let options = vec![(k - 1) % 3];            let change = MessageChange::Vote { external_id: "WAFB2APOLL1".into(), voter: "+15550190901".into(), options, at: at.clone() };            let asked = now_ms();            sink.send(IngestBatch { work: IngestWork::MessageChanges { workspace_id: database_id.clone(), channel: "whatsapp".into(), changes: vec![change] }, read: 1, cursor: None }).expect("the vote lands");            println!("WALK LIVE vote {k} option {} written asked_ms {asked} answered_ms {}", (k - 1) % 3, now_ms());        }        std::thread::sleep(hold);        println!("WALK done");        return;    }    if polls {        // Votes come, WALK_HOLD seconds after the phone is in: the owner votes from his own WhatsApp, a person Cotton        // has no name for votes, and the friend changes their mind.        std::thread::sleep(hold);        let at = "2026-11-23T09:00:00.000Z".to_string();        let vote = |voter: &str, options: &[u32]| MessageChange::Vote { external_id: "WAFB2APOLL1".into(), voter: voter.into(), options: options.to_vec(), at: at.clone() };        let changes = vec![vote("owner", &[0, 1]), vote("+15550190977", &[1]), vote("+15550190901", &[1, 2])];        sink.send(IngestBatch { work: IngestWork::MessageChanges { workspace_id: database_id.clone(), channel: "whatsapp".into(), changes }, read: 3, cursor: None }).expect("the votes land");        println!("WALK votes: three votes changed the dinner poll");        std::thread::sleep(hold);        println!("WALK done");        return;    }    // The Mac is away: whatever the phone queues waits. Each row as the Mac reads it.    let mac = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&copy)));    let mut seen = std::collections::BTreeSet::new();    let started = Instant::now();    let mut first: Option<Instant> = None;    while first.is_none_or(|at| at.elapsed() < hold) {        assert!(started.elapsed() < wait, "the phone queued nothing in time");        for row in mac.outbox("queued").unwrap_or_default() {            let Some(queued) = cotton_mac::outbox::Queued::from_row(&row) else { continue };            if seen.insert(queued.id.clone()) {                first.get_or_insert_with(Instant::now);                println!(                    "WALK outbox row {} for the Mac: channel {} to {} account {:?} words {:?} status queued id fixed at the tap {:?}",                    queued.id, queued.channel, queued.to, queued.account, queued.body, queued.sent_external_id                );            }        }        std::thread::sleep(Duration::from_secs(3));    }    // The Mac's half for a number WhatsApp holds no account for: failed, in the words the phones draw.    for id in &seen {        mac.act(Act::Update, "outbox", id, &json!({ "status": "failed", "error": cotton_core::messages::send::NOT_ON_WHATSAPP })).expect("the Mac marks it");        println!("WALK marked {id} failed: {}", cotton_core::messages::send::NOT_ON_WHATSAPP);    }    assert!(helper.lock().unwrap().sends.is_empty(), "nothing was sent anywhere");    println!("WALK done");}/// The phone half of a walk by hand (build 4): on the dev Worker, a phone signs in to/// `COTTON_E2E_PHONE` (a fresh synthetic number), founds the vault and waits. A Mac app signed in to the same number/// by hand asks by itself; the phone opens the ask, prints the six digits the Mac's panel must show, then approves/// and wraps the key onto the Mac's own row, as a phone does. Run it beside the app: `-- --ignored --nocapture`.#[test]#[ignore]fn a_phone_lets_a_mac_in_by_hand_on_dev() {    use base64::Engine as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev") || base.contains("127.0.0.1"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let wait = std::env::var("COTTON_E2E_WAIT").ok().and_then(|w| w.parse().ok()).unwrap_or(600u64);    let open = ObjectClient::new(base.clone(), None).unwrap();    let phone_device = format!("walk-phone-{}", std::process::id());    let asked = open.ask_code(&phone, &phone_device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &phone_device).unwrap();    let phone_client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    phone_client        .put_key_row(            &cotton_mac::ids::row_id("walk-phone-key", &phone_device),            &json!({ "device_id": phone_device, "name": "Walk phone", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (_dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-23T00:00:00.000Z").unwrap();    phone_client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    println!("PHONE READY: the vault is founded; sign the Mac in to the same number now");    let started = Instant::now();    let nonce_b = [21u8; 32];    let mut opened: Option<(String, String, String)> = None;    while started.elapsed() < Duration::from_secs(wait) {        let approvals = phone_client.get_json("/v1/approvals", &[]).unwrap_or(Value::Null);        let asks = approvals["asks"].as_array().cloned().unwrap_or_default();        match &opened {            None => {                if let Some(ask) = asks.iter().find(|a| a["vault_key"].is_string()) {                    let ask_id = ask["ask_id"].as_str().unwrap().to_string();                    phone_client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();                    println!("PHONE opened the ask from {}: the Mac shows six digits now", ask["device_name"]);                    opened = Some((ask_id, ask["device_id"].as_str().unwrap().to_string(), ask["vault_key"].as_str().unwrap().to_string()));                }            }            Some((ask_id, device, vault_key)) => {                let Some(ask) = asks.iter().find(|a| a["ask_id"] == ask_id.as_str()) else {                    println!("PHONE the ask is gone (ended, or the Mac asked again): waiting for the next");                    opened = None;                    continue;                };                let Some(reveal) = ask["reveal"].as_str() else {                    std::thread::sleep(Duration::from_secs(2));                    continue;                };                let reveal: [u8; 32] = b64.decode(reveal).unwrap().try_into().unwrap();                let device_bytes: [u8; 32] = b64.decode(device).unwrap().try_into().unwrap();                let vault_bytes: [u8; 32] = b64.decode(vault_key).unwrap().try_into().unwrap();                println!("PHONE the Mac must show: {}", shown_code(&sas_of(&device_bytes, Some(&vault_bytes), &reveal, &nonce_b)));                let hold = std::env::var("COTTON_E2E_HOLD").ok().and_then(|h| h.parse().ok()).unwrap_or(20u64);                std::thread::sleep(Duration::from_secs(hold));                phone_client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();                let page = phone_client.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], None).unwrap();                let mac_row = page["rows"].as_array().into_iter().flatten()                    .find(|r| r["data"]["device_id"] == device.as_str() && r["data"]["public_key"] == vault_key.as_str() && r["deleted"] != true)                    .and_then(|r| r["id"].as_str().map(str::to_string))                    .expect("the Mac published its row");                phone_client                    .act(Act::Update, cotton_mac::vault::VAULT_KEY_TABLE, &mac_row, &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }))                    .expect("the wrap onto the Mac's row");                println!("PHONE approved and wrapped the key onto the Mac's row: the Mac opens your things now");                return;            }        }        std::thread::sleep(Duration::from_secs(2));    }    panic!("no Mac asked within {wait} s");}/// A fake Mac for a phone walk of FEEDBACK-3 (23 Nov 2026: pictures, video and voice notes/// from Comms to WhatsApp), on the DEV Worker with a synthetic number, set up as the FEEDBACK-2 A walk's fake Mac/// is: it signs in first, founds the vault and mints the data key, lands two messages through a fake WhatsApp link/// (so the chat is linked), prints `WALK READY`, and approves the phone that asks to be let in. Then, the Mac away,/// it prints each outbox row as the Mac reads it (opened: kind, voice, caption, type, size, length, waveform,/// preview, part, the id fixed at the tap) and opens each row's file from the object with this Mac's own key/// (`files::fetch_opened`), as mac-import's drain will: a file not up yet is said and left queued. `WALK_HOLD`/// seconds (default 150) after the first row is read, it marks every row failed with one of the contract's words,/// then waits for the phone's Retry and prints that the same row came back queued under the same WhatsApp id, with/// no second row. Nothing is sent anywhere.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///   WALK_HOLD=150 cargo test -p cotton-mac --test object_e2e a_fake_mac_for_a_phone_sending_media_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker and a phone: run by hand"]fn a_fake_mac_for_a_phone_sending_media_on_dev() {    use base64::Engine as _;    use cotton_client::ingest::sources::whatsapp_link::{WhatsappLinkSource, WhatsappLinkSourceInput};    use cotton_client::ingest::IngestSource as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let hold = Duration::from_secs(std::env::var("WALK_HOLD").ok().and_then(|h| h.parse().ok()).unwrap_or(150u64));    let wait = Duration::from_secs(std::env::var("COTTON_E2E_WAIT").ok().and_then(|w| w.parse().ok()).unwrap_or(2400u64));    let dir = tempfile::tempdir().unwrap();    let open = ObjectClient::new(base.clone(), None).unwrap();    let device = format!("wamedia-mac-{}", std::process::id());    let asked = open.ask_code(&phone, &device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &device).unwrap();    let database_id = asked.database_id.clone();    let client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    client        .put_key_row(            &cotton_mac::ids::row_id("wamedia-mac-key", &device),            &json!({ "device_id": device, "name": "Walk Mac", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-23T06:00:00.000Z").unwrap();    client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    // The link: two messages from an invented friend, through an invented linked number.    let account = "15550190910@s.whatsapp.net";    let friend = "15550190911@s.whatsapp.net";    let event = |seq: i64, id: &str, text: &str| {        json!({ "seq": seq, "event": "message", "account": account, "message": { "id": id, "chat": friend, "sender": friend, "from_me": false, "is_group": false, "ts": 1_763_880_000 + seq, "kind": "text", "text": text, "origin": "live" } })    };    let helper = Arc::new(Mutex::new(support::helper::Helper { outbox: vec![event(1, "WAMEDIA1", "Send me the beach pictures?"), event(2, "WAMEDIA2", "And a voice note when you can.")], ..Default::default() }));    support::helper::fake_helper(dir.path(), Arc::clone(&helper));    let source = WhatsappLinkSource::new(WhatsappLinkSourceInput {        workspace_id: database_id.clone(),        namespace: cotton_store::file_identity::Namespace::of_database(&database_id),        device: "Walk Mac".to_string(),        dir: dir.path().to_path_buf(),        media_dir: dir.path().join("media"),    });    let copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("copy.db"), &database_id, keys.clone()).unwrap());    let sink = ObjectSink::new(&client, database_id.clone()).with_copy(&copy);    source.read(None, &mut |batch| sink.send(batch).map(|_| ()).map_err(|error| error.to_string())).expect("the link's messages land");    println!("WALK linked: the link's two messages landed sealed");    println!("WALK READY: sign the phone in to the same number now and ask to be let in");    // The phone asks to be let in: approved from here, the vault's key wrapped onto its row.    let started = Instant::now();    let nonce_b = [29u8; 32];    let mut opened_ask: Option<(String, String, String)> = None;    'approve: loop {        assert!(started.elapsed() < wait, "no phone asked in time");        let approvals = client.get_json("/v1/approvals", &[]).unwrap_or(Value::Null);        let asks = approvals["asks"].as_array().cloned().unwrap_or_default();        match &opened_ask {            None => {                if let Some(ask) = asks.iter().find(|a| a["vault_key"].is_string()) {                    let ask_id = ask["ask_id"].as_str().unwrap().to_string();                    client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();                    println!("WALK opened the phone's ask ({})", ask["device_name"]);                    opened_ask = Some((ask_id, ask["device_id"].as_str().unwrap().to_string(), ask["vault_key"].as_str().unwrap().to_string()));                }            }            Some((ask_id, asker, vault_key)) => {                let Some(ask) = asks.iter().find(|a| a["ask_id"] == ask_id.as_str()) else {                    opened_ask = None;                    continue;                };                let Some(reveal) = ask["reveal"].as_str() else {                    std::thread::sleep(Duration::from_secs(2));                    continue;                };                let reveal: [u8; 32] = b64.decode(reveal).unwrap().try_into().unwrap();                let device_bytes: [u8; 32] = b64.decode(asker).unwrap().try_into().unwrap();                let vault_bytes: [u8; 32] = b64.decode(vault_key).unwrap().try_into().unwrap();                println!("WALK the phone must show: {}", shown_code(&sas_of(&device_bytes, Some(&vault_bytes), &reveal, &nonce_b)));                std::thread::sleep(Duration::from_secs(5));                client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();                for _ in 0..30 {                    let page = client.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], None).unwrap();                    let row = page["rows"].as_array().into_iter().flatten()                        .find(|r| r["data"]["device_id"] == asker.as_str() && r["data"]["public_key"] == vault_key.as_str() && r["deleted"] != true)                        .and_then(|r| r["id"].as_str().map(str::to_string));                    if let Some(row) = row {                        client                            .act(Act::Update, cotton_mac::vault::VAULT_KEY_TABLE, &row, &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }))                            .expect("the wrap onto the phone's row");                        println!("WALK approved the phone and wrapped the key onto its row");                        break 'approve;                    }                    std::thread::sleep(Duration::from_secs(2));                }                panic!("the phone published no vault key row");            }        }        std::thread::sleep(Duration::from_secs(2));    }    // The Mac is away: whatever the phone queues waits. Each row as the Mac reads it, and its file opened here.    let store: Arc<dyn cotton_client::seal::DataKeyStore> = keys.clone();    let files = Arc::new(cotton_client::media::sealed::PersonFiles::new(database_id.clone(), store));    let mac = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&copy))).sealing_files(files);    let fields = |row: &Value| -> Map<String, Value> { row.get("data").filter(|d| d.is_object()).unwrap_or(row).as_object().cloned().unwrap_or_default() };    let mut seen: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();    let mut fetched = std::collections::BTreeSet::new();    let started = Instant::now();    let mut first: Option<Instant> = None;    while first.is_none_or(|at| at.elapsed() < hold) {        assert!(started.elapsed() < wait, "the phone queued nothing in time");        for row in mac.outbox("queued").unwrap_or_default() {            let Some(id) = row["id"].as_str().map(str::to_string) else { continue };            let data = fields(&row);            if data.get("sealed_enc").and_then(Value::as_str).is_some_and(|s| !s.is_empty()) {                continue;            }            let field = |key: &str| data.get(key).cloned().unwrap_or(Value::Null);            if !seen.contains_key(&id) {                first.get_or_insert_with(Instant::now);                let waveform = data.get("waveform").and_then(Value::as_str).and_then(|w| base64::engine::general_purpose::STANDARD.decode(w).ok());                println!(                    "WALK outbox row {id} for the Mac: channel {} to {} account {} kind {} voice {} caption {} mime {} size {} {}x{} length {} waveform {:?} preview {} chars part {} media_key {} status queued, id fixed at the tap {}",                    field("channel"), field("to"), field("account"), field("kind"), field("voice"), field("body"), field("mime"), field("size_bytes"), field("width"), field("height"), field("duration_ms"),                    waveform.as_ref().map(|w| (w.len(), w.iter().copied().max())), data.get("preview").and_then(Value::as_str).map_or(0, str::len), field("part"), field("media_key"), field("sent_external_id"),                );                seen.insert(id.clone(), data.get("sent_external_id").and_then(Value::as_str).unwrap_or_default().to_string());            }            let Some(key) = data.get("media_key").and_then(Value::as_str).filter(|k| !k.is_empty()) else { continue };            if fetched.contains(&id) {                continue;            }            let out = dir.path().join(format!("opened-{id}"));            match cotton_mac::files::fetch_opened(&mac, key, &out) {                Ok(bytes) => {                    let plain = std::fs::read(&out).unwrap();                    let sha = cotton_mac::ids::sha256_hex(&plain);                    let named = key.rsplit('/').next().unwrap_or_default().split('.').next().unwrap_or_default().to_string();                    println!("WALK opened {key} on the Mac with its own key: {bytes} bytes, its sha256 {} the key's name", if sha == named { "matches" } else { "DOES NOT match" });                    assert_eq!(sha, named, "the file the phone kept is the file the Mac opens");                    let _ = std::fs::remove_file(&out);                    fetched.insert(id.clone());                }                Err(why) if why.contains("holds no such file") => println!("WALK {key} is not up yet: the row stays queued"),                Err(why) => panic!("the Mac could not open {key}: {why}"),            }        }        std::thread::sleep(Duration::from_secs(3));    }    // The Mac's half failing, in the contract's words; then the phone's Retry brings the same row back, once.    const WHY: &str = "This file is too large for WhatsApp.";    for id in seen.keys() {        mac.act(Act::Update, "outbox", id, &json!({ "status": "failed", "error": WHY })).expect("the Mac marks it");        println!("WALK marked {id} failed: {WHY}");    }    // Each row's Retry (a picture, a voice note and a video in one walk): every row comes back once, the same.    println!("WALK waiting for Retry on the phone, {} rows", seen.len());    let started = Instant::now();    let mut retried = std::collections::BTreeSet::new();    while retried.len() < seen.len() {        assert!(started.elapsed() < wait, "no Retry in time");        let queued = mac.outbox("queued").unwrap_or_default();        let failed = mac.outbox("failed").unwrap_or_default();        let back: Vec<(String, String)> = queued.iter().filter_map(|row| Some((row["id"].as_str()?.to_string(), fields(row).get("sent_external_id")?.as_str()?.to_string()))).collect();        let fresh: Vec<&(String, String)> = back.iter().filter(|(id, _)| seen.contains_key(id) && !retried.contains(id)).collect();        for (id, external) in fresh {            let new_rows = queued.iter().chain(failed.iter()).filter_map(|row| row["id"].as_str()).filter(|id| !seen.contains_key(*id)).count();            println!("WALK retry: row {id} queued again, WhatsApp id {external} ({}), rows the Mac had not seen: {new_rows}", if seen[id] == *external { "the same" } else { "CHANGED" });            assert_eq!(&seen[id], external, "the same WhatsApp id");            assert_eq!(new_rows, 0, "Retry makes no second entry");            retried.insert(id.clone());        }        std::thread::sleep(Duration::from_secs(3));    }    assert!(helper.lock().unwrap().sends.is_empty(), "nothing was sent anywhere");    println!("WALK done");}/// A fake Mac for a phone walk of FEEDBACK-3's replies and reactions (23 Nov 2026; CONTRACT/// "Replies and reactions"), on the DEV Worker with a synthetic number, set up as the media walk's fake Mac is: it/// signs in first, founds the vault and mints the data key, lands messages through a fake WhatsApp link (a one-to-one/// chat with an invented friend, and an invented group), prints `WALK READY`, and approves the phone that asks to be/// let in. Then, the Mac away, it prints each outbox row as the Mac reads it (opened: a text, a reply with its/// `quoted_id`, a reaction with `reaction_to` and `emoji`, the id fixed at the tap), again when a waiting row is/// rewritten (a reaction changed before the Mac comes), and the quoted message as the Mac's own copy holds it./// `WALK_HOLD` seconds (default 150) after the first row, it marks every row failed in words, then waits for the/// phone's Retry and prints that the same row came back queued under the same WhatsApp id, with no second row./// Nothing is sent anywhere. Needs a dev Worker serving the outbox's `quoted_id`, `reaction_to` and `emoji`.//////   COTTON_E2E_BASE=<the dev Worker's address (config/dev-server.json)> COTTON_E2E_PHONE=+1555… COTTON_E2E_CODE=<dev code> \///   WALK_HOLD=150 cargo test -p cotton-mac --test object_e2e a_fake_mac_for_a_phone_replying_and_reacting_on_dev -- --ignored --nocapture#[test]#[ignore = "needs the dev Worker and a phone: run by hand"]fn a_fake_mac_for_a_phone_replying_and_reacting_on_dev() {    use base64::Engine as _;    use cotton_client::ingest::sources::whatsapp_link::{WhatsappLinkSource, WhatsappLinkSourceInput};    use cotton_client::ingest::IngestSource as _;    use cotton_core::vault::approval::{sas_of, shown_code};    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let hold = Duration::from_secs(std::env::var("WALK_HOLD").ok().and_then(|h| h.parse().ok()).unwrap_or(150u64));    let wait = Duration::from_secs(std::env::var("COTTON_E2E_WAIT").ok().and_then(|w| w.parse().ok()).unwrap_or(2400u64));    let dir = tempfile::tempdir().unwrap();    let open = ObjectClient::new(base.clone(), None).unwrap();    let device = format!("wareply-mac-{}", std::process::id());    let asked = open.ask_code(&phone, &device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &device).unwrap();    let database_id = asked.database_id.clone();    let client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [7u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    client        .put_key_row(            &cotton_mac::ids::row_id("wareply-mac-key", &device),            &json!({ "device_id": device, "name": "Walk Mac", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-23T06:00:00.000Z").unwrap();    client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    // The link: two messages from an invented friend, and two in an invented group, through an invented linked number.    let account = "15550190920@s.whatsapp.net";    let friend = "15550190921@s.whatsapp.net";    let group = "120363000000090922@g.us";    let member = "15550190923@s.whatsapp.net";    let event = |seq: i64, id: &str, chat: &str, sender: &str, text: &str| {        let is_group = chat.ends_with("@g.us");        json!({ "seq": seq, "event": "message", "account": account, "message": { "id": id, "chat": chat, "chat_name": if is_group { "Walk club" } else { "" }, "sender": sender, "push_name": if is_group { "Chitra Walk" } else { "" }, "from_me": false, "is_group": is_group, "ts": 1_763_880_000 + seq, "kind": "text", "text": text, "origin": "live" } })    };    let helper = Arc::new(Mutex::new(support::helper::Helper {        outbox: vec![            event(1, "WAREPLY1", friend, friend, "Lunch on Friday?"),            event(2, "WAREPLY2", friend, friend, "The new place by the river."),            event(3, "WAREPLY3", group, member, "Who is in for Sunday's walk?"),            event(4, "WAREPLY4", group, member, "Start at eight."),        ],        ..Default::default()    }));    support::helper::fake_helper(dir.path(), Arc::clone(&helper));    let source = WhatsappLinkSource::new(WhatsappLinkSourceInput {        workspace_id: database_id.clone(),        namespace: cotton_store::file_identity::Namespace::of_database(&database_id),        device: "Walk Mac".to_string(),        dir: dir.path().to_path_buf(),        media_dir: dir.path().join("media"),    });    let copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("copy.db"), &database_id, keys.clone()).unwrap());    let sink = ObjectSink::new(&client, database_id.clone()).with_copy(&copy);    source.read(None, &mut |batch| sink.send(batch).map(|_| ()).map_err(|error| error.to_string())).expect("the link's messages land");    println!("WALK linked: the link's four messages landed sealed");    println!("WALK READY: sign the phone in to the same number now and ask to be let in");    // The phone asks to be let in: approved from here, the vault's key wrapped onto its row.    let started = Instant::now();    let nonce_b = [29u8; 32];    let mut opened_ask: Option<(String, String, String)> = None;    'approve: loop {        assert!(started.elapsed() < wait, "no phone asked in time");        let approvals = client.get_json("/v1/approvals", &[]).unwrap_or(Value::Null);        let asks = approvals["asks"].as_array().cloned().unwrap_or_default();        match &opened_ask {            None => {                if let Some(ask) = asks.iter().find(|a| a["vault_key"].is_string()) {                    let ask_id = ask["ask_id"].as_str().unwrap().to_string();                    client.post_route("/v1/approvals/nonce", &json!({ "ask_id": ask_id, "nonce": b64.encode(nonce_b) })).unwrap();                    println!("WALK opened the phone's ask ({})", ask["device_name"]);                    opened_ask = Some((ask_id, ask["device_id"].as_str().unwrap().to_string(), ask["vault_key"].as_str().unwrap().to_string()));                }            }            Some((ask_id, asker, vault_key)) => {                let Some(ask) = asks.iter().find(|a| a["ask_id"] == ask_id.as_str()) else {                    opened_ask = None;                    continue;                };                let Some(reveal) = ask["reveal"].as_str() else {                    std::thread::sleep(Duration::from_secs(2));                    continue;                };                let reveal: [u8; 32] = b64.decode(reveal).unwrap().try_into().unwrap();                let device_bytes: [u8; 32] = b64.decode(asker).unwrap().try_into().unwrap();                let vault_bytes: [u8; 32] = b64.decode(vault_key).unwrap().try_into().unwrap();                println!("WALK the phone must show: {}", shown_code(&sas_of(&device_bytes, Some(&vault_bytes), &reveal, &nonce_b)));                std::thread::sleep(Duration::from_secs(5));                client.post_route("/v1/approvals/approve", &json!({ "ask_id": ask_id })).unwrap();                for _ in 0..30 {                    let page = client.sync_page(0, &[cotton_mac::vault::VAULT_KEY_TABLE], None).unwrap();                    let row = page["rows"].as_array().into_iter().flatten()                        .find(|r| r["data"]["device_id"] == asker.as_str() && r["data"]["public_key"] == vault_key.as_str() && r["deleted"] != true)                        .and_then(|r| r["id"].as_str().map(str::to_string));                    if let Some(row) = row {                        client                            .act(Act::Update, cotton_mac::vault::VAULT_KEY_TABLE, &row, &json!({ "wrapped_vmk": cotton_core::vault::wrap::wrap(&vault_bytes, vmk.expose()).unwrap(), "vmk_version": 1 }))                            .expect("the wrap onto the phone's row");                        println!("WALK approved the phone and wrapped the key onto its row");                        break 'approve;                    }                    std::thread::sleep(Duration::from_secs(2));                }                panic!("the phone published no vault key row");            }        }        std::thread::sleep(Duration::from_secs(2));    }    // The Mac is away: whatever the phone queues waits. Each row as the Mac reads it (opened), and again whenever it    // changes while it waits (a reaction changed before the Mac comes rewrites its row: only the last goes).    let mac = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&copy)));    let fields = |row: &Value| -> Map<String, Value> { row.get("data").filter(|d| d.is_object()).unwrap_or(row).as_object().cloned().unwrap_or_default() };    let mut seen: std::collections::BTreeMap<String, (String, String)> = std::collections::BTreeMap::new();    let started = Instant::now();    let mut first: Option<Instant> = None;    while first.is_none_or(|at| at.elapsed() < hold) {        assert!(started.elapsed() < wait, "the phone queued nothing in time");        for row in mac.outbox("queued").unwrap_or_default() {            let Some(id) = row["id"].as_str().map(str::to_string) else { continue };            let data = fields(&row);            if data.get("sealed_enc").and_then(Value::as_str).is_some_and(|s| !s.is_empty()) {                continue;            }            let field = |key: &str| data.get(key).cloned().unwrap_or(Value::Null);            let external = field("sent_external_id").as_str().unwrap_or_default().to_string();            let now = format!("{}|{}|{}", field("body"), field("quoted_id"), field("emoji"));            if seen.get(&id).map(|(_, was)| was) == Some(&now) {                continue;            }            first.get_or_insert_with(Instant::now);            let what = if field("reaction_to").as_str().is_some_and(|r| !r.is_empty()) { "reaction" } else if field("quoted_id").as_str().is_some_and(|q| !q.is_empty()) { "reply" } else { "text" };            println!(                "WALK outbox row {id} for the Mac{}: {what} to {} account {} words {} quoted_id {} reaction_to {} emoji {} status queued, id fixed at the tap {external}",                if seen.contains_key(&id) { " (rewritten while it waits)" } else { "" },                field("to"), field("account"), field("body"), field("quoted_id"), field("reaction_to"), field("emoji"),            );            // The quote the Mac draws from its own copy, by the id the row names.            if let Some(quoted) = field("quoted_id").as_str().filter(|q| !q.is_empty()) {                let db = rusqlite::Connection::open_with_flags(dir.path().join("copy.db"), rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();                let held: Option<(String, String)> = db                    .query_row(                        "SELECT json_extract(data, '$.body'), json_extract(data, '$.direction') FROM rows WHERE table_id = 'message' AND deleted = 0 AND json_extract(data, '$.external_id') = ?1",                        [quoted],                        |r| Ok((r.get::<_, Option<String>>(0)?.unwrap_or_default(), r.get::<_, Option<String>>(1)?.unwrap_or_default())),                    )                    .ok();                println!("WALK the Mac's copy holds the quoted message {quoted}: {}", held.map_or("NOT HELD".to_string(), |(body, direction)| format!("{body:?}, direction {direction}")));            }            seen.insert(id.clone(), (external, now));        }        std::thread::sleep(Duration::from_secs(3));    }    // The Mac's half failing, in words; then the phone's Retry brings the same row back, once.    const WHY: &str = "WhatsApp did not take it: the walk's Mac sends nothing";    for id in seen.keys() {        mac.act(Act::Update, "outbox", id, &json!({ "status": "failed", "error": WHY })).expect("the Mac marks it");        println!("WALK marked {id} failed: {WHY}");    }    println!("WALK waiting for Retry on the phone");    let started = Instant::now();    loop {        assert!(started.elapsed() < wait, "no Retry in time");        let queued = mac.outbox("queued").unwrap_or_default();        let failed = mac.outbox("failed").unwrap_or_default();        let back: Vec<(String, String)> = queued.iter().filter_map(|row| Some((row["id"].as_str()?.to_string(), fields(row).get("sent_external_id")?.as_str()?.to_string()))).collect();        if let Some((id, external)) = back.iter().find(|(id, _)| seen.contains_key(id)) {            let new_rows = queued.iter().chain(failed.iter()).filter_map(|row| row["id"].as_str()).filter(|id| !seen.contains_key(*id)).count();            println!("WALK retry: row {id} queued again, WhatsApp id {external} ({}), rows the Mac had not seen: {new_rows}", if seen[id].0 == *external { "the same" } else { "CHANGED" });            assert_eq!(&seen[id].0, external, "the same WhatsApp id");            assert_eq!(new_rows, 0, "Retry makes no second entry");            break;        }        std::thread::sleep(Duration::from_secs(3));    }    assert!(helper.lock().unwrap().sends.is_empty(), "nothing was sent anywhere");    println!("WALK done");}/// Every kind the owner can send to WhatsApp from Comms, from a phone's sealed outbox row to WhatsApp's door, on the/// DEV Worker with a synthetic number and invented files (owner, FEEDBACK-3, 23 Nov 2026; CONTRACT "WhatsApp through/// the Mac"). The phone's half is done here as a phone does it: each file put sealed under the person's own file key/// at `<db>/messages/<thread>/<sha>.<ext>`, each row written sealed. The Mac's half is the real one: the drain reads/// each row, fetches and opens its file, finds a reply's quote and a reaction's message in its copy, and hands the/// send to the link. Only WhatsApp is stood in for: the stand-in link keeps what it is asked and the bytes of each/// file, and keeps each send as the real link does, so the reader lands it. The real helper's own conversions (HEIC/// to JPEG, QuickTime to MP4, AAC to an Ogg Opus voice note) are its Go tests', on the same kinds of files.#[test]#[ignore = "needs the dev Worker: run by hand (build 6)"]fn every_kind_goes_from_a_phone_to_whatsapps_door_on_dev() {    use base64::Engine as _;    use cotton_client::ingest::sources::whatsapp_link::{WhatsappLinkSource, WhatsappLinkSourceInput};    use cotton_client::ingest::IngestSource as _;    let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;    let std64 = base64::engine::general_purpose::STANDARD;    let base = env("COTTON_E2E_BASE");    assert!(base.contains("cottondb-dev"), "the dev Worker only");    let phone = env("COTTON_E2E_PHONE");    assert!(phone.starts_with("+1555"), "a synthetic number only");    let code = env("COTTON_E2E_CODE");    let dir = tempfile::tempdir().unwrap();    let open = ObjectClient::new(base.clone(), None).unwrap();    let device = format!("wa-kinds-{}", std::process::id());    let asked = open.ask_code(&phone, &device).unwrap();    let signed = open.sign_in(&asked.database_id, &asked.challenge_id, &code, &device).unwrap();    let database_id = asked.database_id.clone();    let client = ObjectClient::new(base.clone(), Some(signed.credential.clone())).unwrap();    let secret = [9u8; 32];    let vmk = cotton_core::vault::Vmk::mint();    client        .put_key_row(            &cotton_mac::ids::row_id("wa-kinds-key", &device),            &json!({ "device_id": device, "name": "WA Kinds Mac", "public_key": b64.encode(cotton_core::vault::wrap::public_of(&secret)), "wrapped_vmk": cotton_core::vault::wrap::wrap(&cotton_core::vault::wrap::public_of(&secret), vmk.expose()).unwrap(), "vmk_version": 1 }),        )        .unwrap();    let (dk, row): (_, Map<String, Value>) = cotton_client::seal::mint_data_key(&vmk, 1, "2026-11-23T06:00:00.000Z").unwrap();    client.upsert(cotton_client::seal::SEAL_KEY_TABLE, cotton_client::seal::DK_ROW, &Value::Object(row)).unwrap();    let owner: Value = reqwest::blocking::Client::new()        .post(format!("{base}/v1/act"))        .bearer_auth(&signed.credential)        .json(&json!({ "act": "mint_token", "args": { "name": "wa kinds walk", "scopes": ["owner"], "allow": "all" } }))        .send()        .unwrap()        .json()        .unwrap();    let token = owner["token"].as_str().unwrap().to_string();    let keys = cotton_client::seal::HeldDataKeys::new();    keys.hold(&database_id, &dk);    // The chat as the link brought it: a friend's text, and a poll in a group.    let account = "15550009999@s.whatsapp.net";    let friend = "15550001111@s.whatsapp.net";    let group = "120363000000000077@g.us";    let helper = Arc::new(Mutex::new(support::helper::Helper {        outbox: vec![            json!({ "seq": 1, "event": "message", "account": account, "message": { "id": "WAK1", "chat": friend, "sender": friend, "from_me": false, "is_group": false, "ts": 1_763_000_001, "kind": "text", "text": "Dinner on Friday?", "origin": "live" } }),            json!({ "seq": 2, "event": "chat", "account": account, "chat": group, "name": "Quokka walkers", "is_group": true }),            json!({ "seq": 3, "event": "message", "account": account, "message": { "id": "WAKPOLL", "chat": group, "sender": friend, "push_name": "Asha Example", "from_me": false, "is_group": true, "ts": 1_763_000_002, "kind": "poll", "text": "Which day for the walk?", "poll": { "options": ["Thursday", "Friday"], "selectable": 1 }, "origin": "live" } }),        ],        accounts: vec![account.to_string()],        ..Default::default()    }));    support::helper::fake_helper(dir.path(), Arc::clone(&helper));    let source = WhatsappLinkSource::new(WhatsappLinkSourceInput {        workspace_id: database_id.clone(),        namespace: cotton_store::file_identity::Namespace::of_database(&database_id),        device: "WA Kinds Mac".to_string(),        dir: dir.path().to_path_buf(),        media_dir: dir.path().join("media"),    });    let mac_copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("mac.db"), &database_id, keys.clone()).unwrap());    let files = Arc::new(cotton_client::media::sealed::PersonFiles::new(database_id.clone(), keys.clone()));    let mac = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&mac_copy))).sealing_files(files.clone());    let read = || {        let sink = ObjectSink::new(&mac, database_id.clone()).with_copy(&mac_copy);        source.read(None, &mut |batch| sink.send(batch).map(|_| ()).map_err(|error| error.to_string())).expect("the page lands")    };    read();    mac_copy.refresh(&client).unwrap();    let thread = mac_copy.held_message_id("whatsapp", "WAK1").unwrap().and_then(|id| mac_copy.row("message", &id).unwrap()).unwrap()["thread_id"].as_str().unwrap().to_string();    println!("WALK chat landed");    // Invented files, as a phone would have them, put sealed by the phone (it holds the data key).    let phone_copy = Arc::new(cotton_mac::copy::Copy::open(&dir.path().join("phone.db"), &database_id, keys.clone()).unwrap());    let phone_side = client.sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&phone_copy))).sealing_files(files.clone());    phone_copy.refresh(&client).unwrap();    let make = |args: &[&str]| {        let out = std::process::Command::new("ffmpeg").args(["-loglevel", "error", "-y"]).args(args).output().expect("ffmpeg makes the invented files");        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));    };    let path = |name: &str| dir.path().join(name);    make(&["-f", "lavfi", "-i", "testsrc=size=320x240", "-frames:v", "1", path("pic.png").to_str().unwrap()]);    let sips = std::process::Command::new("/usr/bin/sips").args(["-s", "format", "heic", path("pic.png").to_str().unwrap(), "--out", path("pic.heic").to_str().unwrap()]).output().unwrap();    assert!(sips.status.success());    make(&["-f", "lavfi", "-i", "testsrc=size=320x240:rate=25", "-f", "lavfi", "-i", "sine=frequency=440", "-t", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", path("clip.mov").to_str().unwrap()]);    make(&["-f", "lavfi", "-i", "sine=frequency=330", "-t", "3", "-c:a", "aac", path("voice.m4a").to_str().unwrap()]);    make(&["-f", "lavfi", "-i", "sine=frequency=550", "-t", "2", "-c:a", "aac", path("song.m4a").to_str().unwrap()]);    std::fs::write(path("plan.pdf"), b"%PDF-1.4\n% an invented plan for the quokka walk\n%%EOF\n").unwrap();    let put = |name: &str, ext: &str, mime: &str| -> (String, Vec<u8>) {        use sha2::Digest as _;        let bytes = std::fs::read(path(name)).unwrap();        let key = format!("{database_id}/messages/{thread}/{}.{ext}", hex::encode(sha2::Sha256::digest(&bytes)));        phone_side.put_person_bytes(&key, bytes.clone(), mime).expect("the phone puts the file sealed");        (key, bytes)    };    let (pic_key, pic) = put("pic.heic", "heic", "image/heic");    let (clip_key, clip) = put("clip.mov", "mov", "video/quicktime");    let (voice_key, voice) = put("voice.m4a", "m4a", "audio/mp4");    let (song_key, song) = put("song.m4a", "m4a", "audio/mp4");    let (plan_key, _plan) = put("plan.pdf", "pdf", "application/pdf");    for key in [&pic_key, &clip_key, &voice_key, &song_key, &plan_key] {        let stored = client.media_stored(key).unwrap().expect("the file is in his Cotton");        assert!(cotton_mac::object::is_sealed_type(&stored.content_type), "{key} rests sealed");    }    println!("WALK five files up, sealed");    // The phone's rows, sealed, each with its WhatsApp id fixed at the tap.    let queue = |id: &str, extra: Value| {        let mut data = json!({ "thread_id": thread, "channel": "whatsapp", "to": friend, "account": account, "body": "", "status": "queued", "sent_external_id": format!("3EB0K{}", id.to_uppercase().replace('-', "")) });        data.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());        phone_side.act(Act::Create, "outbox", id, &data).unwrap_or_else(|e| panic!("the phone queues {id}: {e}"));    };    let waveform = std64.encode([10u8, 40, 80, 100, 60, 20]);    queue("k-photo", json!({ "kind": "photo", "body": "The view from the top", "media_key": pic_key, "mime": "image/heic", "size_bytes": pic.len(), "width": 320, "height": 240, "preview": std64.encode([0xff, 0xd8, 0xff, 0xd9]) }));    queue("k-video", json!({ "kind": "video", "body": "", "media_key": clip_key, "mime": "video/quicktime", "size_bytes": clip.len(), "width": 320, "height": 240, "duration_ms": 2000 }));    queue("k-voice", json!({ "kind": "audio", "voice": true, "media_key": voice_key, "mime": "audio/mp4", "size_bytes": voice.len(), "duration_ms": 3000, "waveform": waveform }));    queue("k-audio", json!({ "kind": "audio", "media_key": song_key, "mime": "audio/mp4", "size_bytes": song.len(), "duration_ms": 2000 }));    queue("k-text", json!({ "body": "Friday works" }));    queue("k-group", json!({ "kind": "photo", "to": group, "body": "For the walkers", "media_key": pic_key, "mime": "image/heic", "size_bytes": pic.len(), "width": 320, "height": 240 }));    // The outbox the object serves today has no column for a document's name, a reply's quote, a reaction, an edit,    // a delete, a poll or a vote (kits/personal/tables/outbox.json): a phone cannot queue those yet, and the object    // refuses the row. Said, not faked.    let refused = phone_side.act(Act::Create, "outbox", "k-document", &json!({ "thread_id": thread, "channel": "whatsapp", "to": friend, "body": "", "status": "queued", "kind": "document", "file_name": "plan.pdf" }));    println!("WALK a document row today: {}", refused.as_ref().err().map(|e| e.to_string()).unwrap_or_else(|| "taken".into()));    let rows = export(&base, &token);    for row in of(&rows, "outbox") {        assert!(row["data"]["sealed_enc"].is_string() && !row.to_string().contains("Friday works"), "outbox rows rest sealed");    }    let socket = dir.path().join(cotton_client::ingest::sources::whatsapp_link::SOCKET_NAME);    let find = |external_id: &str| -> Option<cotton_mac::outbox::Held> {        let id = mac_copy.held_message_id("whatsapp", external_id).ok().flatten()?;        mac_copy.row("message", &id).ok().flatten().map(|data| cotton_mac::outbox::Held::of(&Value::Object(data)))    };    let drained = cotton_mac::outbox::drain_whatsapp_with(&mac, &socket, &find).expect("the Mac drains");    println!("WALK drained {drained:?}");    let failed: Vec<Value> = opened(&mac_copy, export(&base, &token)).into_iter().filter(|r| r["table"] == "outbox" && r["data"]["status"] == "failed").map(|r| json!({ "id": r["id"], "error": r["data"]["error"] })).collect();    assert!(failed.is_empty(), "nothing failed: {failed:?}");    assert_eq!(drained.sent, 6);    {        let held = helper.lock().unwrap();        let by = |kind: &str| held.sends.iter().find(|s| s["kind"].as_str().unwrap_or("text") == kind).unwrap_or_else(|| panic!("no {kind} send")).clone();        let file_of = |send: &Value| held.files.iter().find(|(id, _)| Some(id.as_str()) == send["message_id"].as_str()).map(|(_, b)| b.clone()).unwrap();        let photo = by("picture");        assert_eq!((photo["text"].as_str(), photo["mimetype"].as_str(), photo["width"].as_u64()), (Some("The view from the top"), Some("image/heic"), Some(320)));        assert_eq!(file_of(&photo), pic, "the picture reached the link byte for byte, opened on the Mac");        assert_eq!(photo["landed"][0]["key"], pic_key.as_str());        let video = by("video");        assert_eq!((video["mimetype"].as_str(), video["seconds"].as_u64()), (Some("video/quicktime"), Some(2)));        assert_eq!(file_of(&video), clip);        let voice_send = by("voice");        assert_eq!((voice_send["seconds"].as_u64(), voice_send["waveform"].as_str()), (Some(3), Some(waveform.as_str())));        assert_eq!(file_of(&voice_send), voice);        let audio = by("audio");        assert_eq!(file_of(&audio), song);        assert!(audio.get("waveform").is_none(), "an audio file goes as a file");        let text = held.sends.iter().find(|s| s["text"] == "Friday works").unwrap();        assert_eq!((text["chat"].as_str(), text["message_id"].as_str()), (Some(friend), Some("3EB0KKTEXT")));        let in_group = held.sends.iter().find(|s| s["text"] == "For the walkers").unwrap();        assert_eq!(in_group["chat"], group);        assert_eq!(file_of(in_group), pic);        println!("WALK each send reached the link as itself: {}", held.sends.len());    }    // The sends come back, as the owner's own messages, his phone's files with them (never fetched from WhatsApp).    read();    mac_copy.refresh(&client).unwrap();    let asks_before = helper.lock().unwrap().media_asks;    assert_eq!(asks_before, 0, "no file was fetched from WhatsApp");    let mine = |external_id: &str| mac_copy.held_message_id("whatsapp", external_id).unwrap().and_then(|id| mac_copy.row("message", &id).unwrap()).unwrap_or_else(|| panic!("{external_id} landed"));    let photo_msg = mine("3EB0KKPHOTO");    assert_eq!((photo_msg["body"].as_str(), photo_msg["direction"].as_str()), (Some("The view from the top"), Some("out")));    assert_eq!(photo_msg["media"][0]["key"], pic_key.as_str(), "the sent picture is his phone's own file");    for (id, key) in [("3EB0KKVIDEO", &clip_key), ("3EB0KKVOICE", &voice_key), ("3EB0KKAUDIO", &song_key), ("3EB0KKGROUP", &pic_key)] {        assert_eq!(mine(id)["media"][0]["key"], key.as_str(), "{id}");    }    assert_eq!(mine("3EB0KKTEXT")["body"], "Friday works");    println!("WALK the sends landed as his, files his phone's own");    // He deletes the video for everyone from WhatsApp on his phone: the link reports the delete, and the video goes    // from the chat, the row and his storage (ERASES), and only it.    {        let mut held = helper.lock().unwrap();        let seq = held.outbox.iter().filter_map(|e| e["seq"].as_i64()).max().unwrap_or(0).max(held.acks.last().copied().unwrap_or(0)) + 1;        held.outbox.push(json!({ "seq": seq, "event": "revoke", "account": account, "chat": friend, "target": "3EB0KKVIDEO",            "message": { "id": "3EB0REVOKE01", "chat": friend, "from_me": true, "is_group": false, "ts": 1_763_200_000, "kind": "text", "origin": "live" } }));    }    read();    mac_copy.refresh(&client).unwrap();    let deleted = mine("3EB0KKVIDEO");    assert!(deleted["deleted_at"].as_str().is_some_and(|d| !d.is_empty()), "the video is deleted for everyone: {deleted:?}");    assert!(deleted["media"].as_array().map_or(true, |m| m.is_empty()), "and its file left the row");    assert!(client.media_stored(&clip_key).unwrap().is_none(), "and his storage");    assert!(client.media_stored(&voice_key).unwrap().is_some(), "only that file");    assert!(client.media_stored(&pic_key).unwrap().is_some(), "the pictures stay");    println!("WALK the delete for everyone took the video and its file, only it");    // Once WhatsApp has them, the outbox keeps no second copy of the words.    let emptied = cotton_mac::outbox::empty_landed(&mac, |id| mac_copy.held_message_id("whatsapp", id).ok().flatten().is_some()).unwrap();    let left: Vec<Value> = opened(&mac_copy, export(&base, &token)).into_iter().filter(|r| r["table"] == "outbox" && r["data"]["body"].as_str().is_some_and(|b| !b.is_empty())).map(|r| r["id"].clone()).collect();    println!("WALK outbox words emptied {emptied}; still holding words {left:?}");    assert!(cotton_mac::outbox::drain_whatsapp_with(&mac, &socket, &find).unwrap().sent == 0, "never twice");    println!("WALK done");}