Cotton code
752 lines · 40.6 KB · RustRaw
//! A BIG INVENTED ACCOUNT ON THE DEV SERVER (`pnpm dev:big-account`, 21 Nov 2026): one//! invented number whose one personal database holds enough of Notes, Days, Story and Chat that a phone's first//! pull runs for about a minute, so the "Loading your data…" line can be watched counting on a device.//!//! Each app is its own phone here, as on a device: a core opened as that app's flavour over its own container,//! signed in on the one number (`personal.code`, `personal.signIn`, `personal.connect`), as the Kotlin shell does.//! The first (Notes) founds the account's key (`vault.unlock`, as `SealedKeys.unlock`) and makes a recovery code//! (`recovery.make`); the others open the key with that code (`recovery.open`), so every row is sealed under the//! account's own key. Each then writes through the app's own doors://!//! - Notes: `notes.import` of a folder of invented Markdown notes (COTTON_BIG_NOTES, default 6000).//! - Days: `days.add`, events and to-dos across 2025–2027 (COTTON_BIG_DAYS, default 3000).//! - Story: `story.bring_in` of an invented Fountain script (COTTON_BIG_SCENES scenes, default 400, about 25 lines//!   each).//! - Chat: `import.whatsappExport` of invented one-to-one WhatsApp exports (COTTON_BIG_CHATS chats, default 5, of//!   COTTON_BIG_MESSAGES messages each, default 3000).//! - Mail (COTTON_BIG_APPS "mail", a Comms phone): `developer.inventMail` (Cotton Dev only) of COTTON_BIG_EMAILS//!   invented emails (default 2000) in COTTON_BIG_MAIL_THREADS conversations (default 1500), one every//!   COTTON_BIG_MAIL_STEP minutes (default 57) back from 21 Nov 2026 over a mailbox of COTTON_BIG_MAIL_TOTAL (runs side//!   by side each write their part of it, from COTTON_BIG_FROM), newsletters, receipts and the chats' invented friends with an email in People; about 110,000//!   in 80,000 is the owner's size. Written as the Mac's reader lands mail, so it syncs up as theirs would.//!//! then `sync.now` until nothing is pending. COTTON_BIG_APPS picks which apps run (default "notes,days,story,//! messages"); COTTON_BIG_CODE (or COTTON_BIG_CODE_FILE, a file holding it) is the recovery code of an account made//! before, so a later run adds to it. A phone posts each row as its own request (about five a second on the dev//! server), so a big account is made by several runs side by side, each with its own COTTON_BIG_FROM (the first//! invented item it writes), as several phones of the one person would. The recovery code of a new account is printed on one `RECOVERY-CODE` line (the account is invented),//! for the device walk to type.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker), COTTON_WALK_CODE_FILE (the dev sign-in code's file: read,//! never printed; or COTTON_WALK_CODE, its words, as the script hands them to the box) and COTTON_BIG_NUMBER (a fresh invented number) are set. Never point it at the live server.use std::ffi::{c_char, CStr, CString};use std::path::{Path, PathBuf};use std::time::Instant;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};const APP_VERSION: &str = "headless-big-account";const ZONE: &str = "Asia/Kolkata";const ME: &str = "Mira Invented";struct Walk {    server: String,    code: String,    number: String,}impl Walk {    fn from_env() -> Option<Walk> {        let (server, number) = (var("COTTON_WALK_SERVER")?, var("COTTON_BIG_NUMBER")?);        assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "the big account is made on the dev server only, not {server}");        // On the box the file is not there: the script hands its words over as COTTON_WALK_CODE (never printed).        let code = match var("COTTON_WALK_CODE") {            Some(code) => code,            None => {                let file = var("COTTON_WALK_CODE_FILE")?;                std::fs::read_to_string(home(&file)).unwrap_or_else(|e| panic!("the dev code file {file} could not be read: {e}")).trim().to_string()            }        };        Some(Walk { server, code, number })    }}fn var(name: &str) -> Option<String> {    std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty())}fn count(name: &str, default: usize) -> usize {    var(name).and_then(|v| v.parse().ok()).unwrap_or(default)}/// Where this run's invented items start (COTTON_BIG_FROM, default 0): runs side by side over the same account each/// write their own items, as several phones would, so the account grows faster than one phone posts.fn from() -> usize {    count("COTTON_BIG_FROM", 0)}fn home(path: &str) -> PathBuf {    match path.strip_prefix("~/") {        Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),        None => PathBuf::from(path),    }}/// One app's phone: a core over its own container, as that app opens it.struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    flavour: String,    /// This phone's vault key (`SealedKeys.privateKey`), minted for the run.    private_key: String,}impl Phone {    fn open(walk: &Walk, flavour: &str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let seed = format!("cotton big account {} {flavour} {:?}", walk.number, std::time::SystemTime::now());        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": ZONE,            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),            "flavor": "dev",            "manifest": manifest(&walk.server, flavour),        });        let text = CString::new(config.to_string()).expect("no NUL");        let mut error: *mut c_char = std::ptr::null_mut();        // SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them.        let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };        assert!(!handle.is_null(), "cotton_open refused {flavour}: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, _container: container, flavour: flavour.to_string(), private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, String> {        let method_c = CString::new(method).expect("no NUL");        let request_c = CString::new(request.to_string()).expect("no NUL");        // SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`.        let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) });        let answer: Value = serde_json::from_str(&answer).map_err(|e| format!("{method}: the answer is not JSON ({e})"))?;        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err(format!("{} {method}: {} {}", self.flavour, error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?")))    }    fn must(&self, method: &str, request: Value) -> Value {        self.call(method, request).unwrap_or_else(|e| panic!("{e}"))    }    /// The SignIn form's calls, then `personal.connect`, as `shell/core/Session.kt` asks them.    fn sign_in(&self, walk: &Walk) -> String {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": walk.number }));        let mut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.must("personal.signIn", ask);        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("personal.signIn named no database").to_string();        let credential = answer["credential"].as_str().expect("personal.signIn granted no credential");        self.must("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": format!("big account {}", self.flavour), "appVersion": APP_VERSION }));        database    }    /// The account's key held here: founded on the account's first phone, else opened with the recovery code.    fn hold_key(&self, code: Option<&str>) {        let mut opened = false;        for attempt in 0..20 {            let status = self.must("seal.status", json!({}));            if status["keyHeld"] == json!(true) || status["keyHeld"] == json!("true") {                return;            }            let needs = status["needsKey"] == json!(true) || status["needsKey"] == json!("true");            let founds = status["founds"] == json!(true) || status["founds"] == json!("true");            let said = if needs && founds {                self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": format!("big account {}", self.flavour) }))            } else if let (true, Some(code)) = (needs, code) {                // Opened with the code once, this phone holds its own wrap of the vault: the data key, which may come                // with a later pass, is taken by opening the vault again with it (as the shell's Unlock does).                let name = format!("big account {}", self.flavour);                let again = if opened { self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": name })) } else { Err(String::new()) };                match again {                    Ok(said) => Ok(said),                    Err(_) => {                        let said = self.call("recovery.open", json!({ "code": code, "privateKey": self.private_key, "name": name }));                        opened |= said.is_ok();                        said                    }                }            } else {                Ok(status.clone())            };            eprintln!("KEY {} try {attempt}: needs {needs} founds {founds} → {}", self.flavour, short(&said.unwrap_or_else(|e| json!(e))));            let _ = self.call("sync.now", json!({}));            std::thread::sleep(std::time::Duration::from_secs(2));        }        panic!("{}: the account's key was never held", self.flavour);    }    /// `sync.now` until nothing waits to go up; the seconds it took.    fn push_all(&self) -> f64 {        let started = Instant::now();        for round in 0..400 {            let said = self.call("sync.now", json!({}));            let status = self.must("sync.status", json!({}));            let pending = status["pending"].as_u64().unwrap_or(0);            eprintln!("PUSH {} round {round}: pending {pending} ({:.0}s) {}", self.flavour, started.elapsed().as_secs_f64(), said.err().unwrap_or_default());            if pending == 0 {                break;            }        }        // What the object refused stays parked on this phone, not pending: said, so a refused table is seen.        if let Ok(rejected) = self.call("sync.rejected", json!({})) {            eprintln!("REJECTED {} {}", self.flavour, short(&rejected));        }        // Every write the object refused, counted off the copy: the list above stops at its first rows.        println!("PARKED {}: {} writes the object refused", self.flavour, parked_pushes(self._container.path()));        started.elapsed().as_secs_f64()    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: an owned string from the C ABI, freed once with its own free.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}fn manifest(server: &str, flavour: &str) -> Value {    let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(flavour).join("flavour.json");    let mut whole: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()))).expect("JSON");    if whole["business"]["server"].is_object() {        whole["business"]["server"] = json!(server);    }    // MAIL ALL ON PHONE (24 Nov 2026): COTTON_BIG_ALL_MAIL=1 keeps all mail on a Comms phone, as the switch does.    if flavour == "messages" && var("COTTON_BIG_ALL_MAIL").is_some_and(|on| on == "1") {        whole["all_history"] = json!(["email", "email_thread"]);    }    whole}fn short(v: &Value) -> String {    let s = v.to_string();    match s.char_indices().nth(300) {        Some((at, _)) => format!("{}…", &s[..at]),        None => s,    }}// ── invented words ──────────────────────────────────────────────────────────const WORDS: &[&str] = &[    "river", "lantern", "harbour", "quiet", "orange", "station", "letter", "garden", "morning", "bridge", "window", "market",    "copper", "winter", "ticket", "island", "pocket", "thunder", "meadow", "kettle", "violin", "pepper", "compass", "ladder",    "tram", "biscuit", "monsoon", "terrace", "notebook", "umbrella", "ferry", "pebble", "chalk", "saffron", "railway", "attic",];/// A sentence of `n` invented words, seeded by `seed`, so every run writes the same account.fn sentence(seed: usize, n: usize) -> String {    let mut out = String::new();    for i in 0..n {        let word = WORDS[(seed * 31 + i * 17 + i * i * 7) % WORDS.len()];        if i == 0 {            let mut c = word.chars();            out.push_str(&c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default());        } else {            out.push(' ');            out.push_str(word);        }    }    out.push('.');    out}// ── the four apps ───────────────────────────────────────────────────────────fn seed_notes(phone: &Phone, dir: &Path) -> usize {    let n = count("COTTON_BIG_NOTES", 6000);    let folder = dir.join("Invented notes");    std::fs::create_dir_all(&folder).unwrap();    for i in from()..from() + n {        let mut body = format!("# {} {i}\n\n", sentence(i, 3).trim_end_matches('.'));        for p in 0..(2 + i % 4) {            body.push_str(&sentence(i * 7 + p, 12 + (i + p) % 20));            body.push_str("\n\n");        }        std::fs::write(folder.join(format!("note-{i:05}.md")), body).unwrap();    }    let started = Instant::now();    let answer = phone.must("notes.import", json!({ "files": [{ "path": folder.to_string_lossy() }] }));    eprintln!("NOTES imported {n} files in {:.0}s: {}", started.elapsed().as_secs_f64(), short(&answer));    n}fn seed_days(phone: &Phone) -> usize {    let n = count("COTTON_BIG_DAYS", 3000);    let started = Instant::now();    let mut made = 0;    for i in 0..n {        // From the start of 2025 to the middle of 2027, a few things a day, about a fifth of them to-dos with no time.        let day = chrono::NaiveDate::from_ymd_opt(2025, 1, 1).unwrap() + chrono::Duration::days((i * 912 / n.max(1)) as i64);        let words = sentence(i + from(), 2 + i % 3).trim_end_matches('.').to_string();        let mut ask = json!({ "words": words, "today": "2026-11-21", "day": day.format("%Y-%m-%d").to_string(), "timezone": ZONE });        if i % 5 != 0 {            ask["time"] = json!(format!("{:02}:{:02}", 7 + i % 14, (i % 4) * 15));        }        match phone.call("days.add", ask) {            Ok(_) => made += 1,            Err(e) if i < 5 => eprintln!("DAYS refused: {e}"),            Err(_) => {}        }        if i % 500 == 499 {            eprintln!("DAYS {made} of {} ({:.0}s)", i + 1, started.elapsed().as_secs_f64());        }    }    eprintln!("DAYS added {made} of {n} in {:.0}s", started.elapsed().as_secs_f64());    made}fn seed_story(phone: &Phone, dir: &Path) -> usize {    let scenes = count("COTTON_BIG_SCENES", 400);    let people = ["ADA", "RAVI", "MEERA", "TOMAS", "LENA", "OSKAR"];    let places = ["KITCHEN", "HARBOUR", "STATION PLATFORM", "ATTIC", "MARKET", "FERRY DECK", "GARDEN", "TRAM"];    let title = if from() == 0 { "The Long Invented Night".to_string() } else { format!("The Long Invented Night, part {}", from()) };    let mut script = format!("Title: {title}\nAuthor: Mira Invented\n\n");    for s in 0..scenes {        let inside = if s % 3 == 0 { "EXT." } else { "INT." };        let time = if s % 2 == 0 { "NIGHT" } else { "DAY" };        script.push_str(&format!("{inside} {} - {time}\n\n", places[s % places.len()]));        script.push_str(&sentence(s + from(), 18));        script.push_str("\n\n");        for l in 0..11 {            script.push_str(people[(s + l) % people.len()]);            script.push('\n');            script.push_str(&sentence(s * 13 + l, 6 + (s + l) % 10));            script.push_str("\n\n");            if l % 4 == 3 {                script.push_str(&sentence(s * 3 + l, 14));                script.push_str("\n\n");            }        }    }    let path = dir.join(format!("{title}.fountain"));    std::fs::write(&path, script).unwrap();    let started = Instant::now();    let answer = phone.must("story.bring_in", json!({ "path": path.to_string_lossy(), "name": format!("{title}.fountain") }));    eprintln!("STORY brought in {scenes} scenes in {:.0}s: {}", started.elapsed().as_secs_f64(), short(&answer));    scenes}fn seed_mail(phone: &Phone) -> usize {    let (emails, threads) = (count("COTTON_BIG_EMAILS", 2000), count("COTTON_BIG_MAIL_THREADS", 1500));    // Runs side by side each write their own part of one mailbox: its whole size (COTTON_BIG_MAIL_TOTAL) dates every    // message, so the parts do not each end today. COTTON_BIG_MAIL_STEP is the minutes between two messages.    let (total, step) = (count("COTTON_BIG_MAIL_TOTAL", from() + emails).max(from() + emails), count("COTTON_BIG_MAIL_STEP", 57));    let people: Vec<Value> = ["Ada Invented", "Ravi Invented", "Lena Invented"]        .iter()        .enumerate()        .map(|(i, name)| json!({ "name": name, "email": format!("{}@invented.example", name.split(' ').next().unwrap_or("friend").to_lowercase()), "phone": var(&format!("COTTON_BIG_MAIL_PHONE_{i}")).unwrap_or_else(|| format!("+1555019{:04}", 9000 + i)) }))        .collect();    // The chats first: a person is linked to their chat by the chat's contact, which this phone must hold.    for _ in 0..4 {        let _ = phone.call("sync.now", json!({}));    }    let started = Instant::now();    let mut made = 0;    // A thousand at a time: each run of the door is one write of the phone's copy.    let mut at = from();    while at < from() + emails {        let n = 1000.min(from() + emails - at);        let generate = json!({ "emails": n, "threads": threads, "from": at, "total": total, "step": step, "end": "2026-11-21T09:00:00Z" });        // The first run also writes one mail by hand: Ada's plan, with a PDF another phone fetches when it is opened.        let by_hand = if at == from() {            json!([{ "thread": "lake-trip", "subject": "The lake trip", "from": { "address": "ada@invented.example", "name": "Ada Invented" }, "at": "2026-11-21T08:30:00Z",                     "body": "Here is the plan for Saturday: the early ferry, lunch at one, back by six.\n\nThe map is attached.", "unread": true,                     "attachments": [{ "name": "Lake trip plan.pdf", "text": "Lake trip plan: ferry at 7, lunch at 1, home by 6" }] }])        } else {            json!([])        };        let answer = phone.must("developer.inventMail", json!({ "me": { "address": "mira@invented.example" }, "people": if at == from() { people.clone() } else { Vec::new() }, "mail": by_hand, "generate": generate }));        made += answer["written"].as_u64().unwrap_or(0) as usize;        at += n;        eprintln!("MAIL {made} of {emails} ({:.0}s)", started.elapsed().as_secs_f64());    }    made}fn seed_chat(phone: &Phone, dir: &Path) -> usize {    let (chats, messages) = (count("COTTON_BIG_CHATS", 5), count("COTTON_BIG_MESSAGES", 3000));    let friends = ["Ada Invented", "Ravi Invented", "Lena Invented", "Tomas Invented", "Oskar Invented", "Priya Invented", "Jun Invented"];    let mut total = 0;    for c in from()..from() + chats {        let friend = if c < friends.len() { friends[c].to_string() } else { format!("{} {}", friends[c % friends.len()], c) };        let friend = friend.as_str();        let mut text = String::new();        let start = chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap().and_hms_opt(8, 0, 0).unwrap();        // Spread over almost three years up to this week, the newest last; chat 0 the most recent.        let span_minutes = 1_000_000i64 - (c as i64) * 20_000;        for m in 0..messages {            let at = start + chrono::Duration::minutes(span_minutes * m as i64 / messages as i64);            let who = if (m + c) % 3 == 0 { ME } else { friend };            text.push_str(&format!("[{}] {who}: {}\n", at.format("%d/%m/%Y, %H:%M:%S"), sentence(c * 100_000 + m, 3 + (m % 9))));        }        let name = format!("WhatsApp Chat with {friend}.txt");        let path = dir.join(&name);        std::fs::write(&path, text).unwrap();        let started = Instant::now();        let answer = phone.call("import.whatsappExport", json!({ "path": path.to_string_lossy(), "fileName": name, "ownerName": ME, "tzOffset": "+05:30" }));        eprintln!("CHAT {friend}: {messages} messages in {:.0}s: {}", started.elapsed().as_secs_f64(), short(&answer.unwrap_or_else(|e| json!(e))));        total += messages;    }    total}/// A new phone's first pull, pass by pass (COTTON_BIG_APPS "first-pull"): a Comms phone signed in with no key yet/// runs passes until it is caught up, saying after each what it holds open and parked by table and whether the key/// is asked for (the shell draws the recovery card on that); then it opens the key with the recovery code and says/// what each pass after opens, until nothing is parked.fn first_pull(phone: &Phone, code: Option<&str>) {    let started = Instant::now();    let say = |what: &str, said: &Value| {        let status = phone.call("seal.status", json!({})).unwrap_or_default();        println!(            "PASS {what} {:.1}s pages={} bytes={} copy={} said={} needsKey={} keyHeld={} {}",            started.elapsed().as_secs_f64(),            said["passPages"], said["passBytes"], copy_bytes(phone._container.path()),            short(said), status["needsKey"], status["keyHeld"],            table_counts(phone._container.path())        );        // A failed pass says its raw cause, which the person never reads (the core's log ring).        if said.get("error").is_some() {            let lines = phone.call("log.lines", json!({})).unwrap_or_default();            for line in lines.as_array().into_iter().flatten().rev().filter(|l| l.to_string().contains("failed")).take(2) {                println!("RAW {}", line.to_string().chars().take(1200).collect::<String>());            }        }    };    // Enough passes for all of a big mailbox (each pass is at most ten pages).    let passes = count("COTTON_BIG_PASSES", 30);    for pass in 0..passes {        let said = phone.call("sync.now", json!({})).unwrap_or_else(|e| json!({ "error": e }));        say(&format!("before-key {pass}"), &said);        if said["behind"] == json!(false) || said.get("error").is_some() {            break;        }    }    let name = format!("big account {}", phone.flavour);    let opened = phone.call("recovery.open", json!({ "code": code.expect("first-pull needs the account's recovery code"), "privateKey": phone.private_key, "name": name }));    println!("KEY opened at {:.1}s: {}", started.elapsed().as_secs_f64(), short(&opened.unwrap_or_else(|e| json!(e))));    for pass in 0..passes {        let said = phone.call("sync.now", json!({})).unwrap_or_else(|e| json!({ "error": e }));        say(&format!("after-key {pass}"), &said);        if said["behind"] == json!(false) && table_counts(phone._container.path()).contains("parked {}") {            break;        }    }}/// Post's first sync of a big mailbox (COTTON_BIG_APPS "post-first-pull", the coordinator's ask of 25 Nov 2026: how/// long, how much storage, and what the app shows meanwhile): a new Post phone opens the account's key with its/// recovery code at once, as the recovery card does, then runs passes until it is caught up. After each pass it says/// the time, the copy's bytes, the mail and conversations it holds, the one sync line every home draws (`seen`), and/// what Post's Home shows (its people, its groups' counts, and the count of mail the search field offers).fn post_first_pull(phone: &Phone, code: Option<&str>) {    let started = Instant::now();    let name = format!("big account {}", phone.flavour);    let passes = count("COTTON_BIG_PASSES", 400);    let mut opened_at = None;    for pass in 0..passes {        let said = phone.call("sync.now", json!({})).unwrap_or_else(|e| json!({ "error": e }));        let status = phone.call("sync.status", json!({})).unwrap_or_default();        let seal = phone.call("seal.status", json!({})).unwrap_or_default();        println!("POST FIRST seal needsKey={} keyHeld={}", seal["needsKey"], seal["keyHeld"]);        // The recovery card, the moment the copy asks for the key (as the shell draws it on needsKey).        if opened_at.is_none() && seal["needsKey"] == json!(true) {            let opened = phone.call("recovery.open", json!({ "code": code.expect("post-first-pull needs the account's recovery code"), "privateKey": phone.private_key, "name": name }));            opened_at = Some(started.elapsed().as_secs_f64());            let seal = phone.call("seal.status", json!({})).unwrap_or_default();            println!("POST FIRST key opened at {:.1}s: {} keyHeld={}", started.elapsed().as_secs_f64(), short(&opened.unwrap_or_else(|e| json!(e))), seal["keyHeld"]);        }        let t = Instant::now();        let home = phone.call("mail.home", json!({})).unwrap_or_else(|e| json!({ "error": e }));        let home_ms = t.elapsed().as_millis();        let people = home["people"]["rows"].as_array().map_or(0, Vec::len);        let groups: Vec<String> = home["groups"].as_array().into_iter().flatten().map(|g| format!("{}={}", g["id"].as_str().unwrap_or("?"), g["count"])).collect();        println!(            "POST FIRST pass {pass} {:.1}s copy={} MB {} seen={:?} home={}ms people={} groups=[{}] search={:?} behind={} err={}",            started.elapsed().as_secs_f64(),            copy_bytes(phone._container.path()) / (1024 * 1024),            post_mail_counts(phone._container.path()),            status["seen"]["line"].as_str().unwrap_or(""),            home_ms,            people,            groups.join(" "),            home["search"]["hint"].as_str().or(home["search"].as_str()).unwrap_or(""),            said["behind"],            said.get("error").map(short).unwrap_or_default(),        );        if said["behind"] == json!(false) && said.get("error").is_none() {            break;        }    }    println!("POST FIRST caught up at {:.1}s, copy {} MB", started.elapsed().as_secs_f64(), copy_bytes(phone._container.path()) / (1024 * 1024));    // The core's own words about the passes (its log ring), for a pass that failed or a row that stayed parked.    let lines = phone.call("log.lines", json!({})).unwrap_or_default();    for line in lines.as_array().into_iter().flatten().filter(|l| { let t = l.to_string(); t.contains("fail") || t.contains("park") || t.contains("refus") || t.contains("seal") || t.contains("took") }).rev().take(25) {        println!("POST FIRST log {}", line.to_string().chars().take(600).collect::<String>());    }}/// The mail a Post copy holds, its conversations and its sealed rows still parked: read off each SQLite file's first/// bytes and a count, never the whole file (a big copy is 1.7 GB).fn post_mail_counts(container: &Path) -> String {    let mut stack = vec![container.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);                continue;            }            let mut head = [0u8; 16];            let is_db = std::fs::File::open(&path).and_then(|mut f| std::io::Read::read_exact(&mut f, &mut head)).is_ok() && head.starts_with(b"SQLite format 3");            if !is_db {                continue;            }            let Ok(db) = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) else { continue };            let one = |sql: &str| db.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap_or(-1);            if one("SELECT count(*) FROM sqlite_master WHERE name = 'cotton_emails'") != 1 {                continue;            }            let why: Vec<String> = db                .prepare("SELECT tbl, code, count(*), min(reason) FROM _seal_parked GROUP BY tbl, code")                .and_then(|mut st| st.query_map([], |r| Ok(format!("{}:{}:{} ({})", r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?.chars().take(120).collect::<String>()))).map(|rows| rows.flatten().collect()))                .unwrap_or_default();            return format!("mail={} conversations={} parked={} why={why:?}", one("SELECT count(*) FROM cotton_emails"), one("SELECT count(*) FROM cotton_email_threads"), one("SELECT count(*) FROM _seal_parked"));        }    }    "mail=? (no copy yet)".to_string()}/// The bytes of every SQLite file under the container, its WAL and shared memory too: the phone's database size.fn copy_bytes(container: &Path) -> u64 {    let mut total = 0;    let mut stack = vec![container.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);            } else if path.extension().is_some_and(|e| e == "db" || e == "sqlite" || e == "sqlite3") || path.to_string_lossy().ends_with("-wal") || path.to_string_lossy().ends_with(".db-shm") {                total += entry.metadata().map(|m| m.len()).unwrap_or(0);            }        }    }    total}/// What a copy holds open of chats and mail, and what it holds parked by table.fn table_counts(container: &Path) -> String {    let mut out = String::new();    let mut stack = vec![container.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);                continue;            }            if !std::fs::read(&path).is_ok_and(|b| b.starts_with(b"SQLite format 3")) {                continue;            }            let Ok(db) = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) else { continue };            let one = |sql: &str| db.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap_or(-1);            if one("SELECT count(*) FROM sqlite_master WHERE name = 'cotton_msg_messages'") != 1 {                continue;            }            let parked: Vec<String> = db                .prepare("SELECT tbl, count(*) FROM _seal_parked GROUP BY tbl")                .and_then(|mut st| st.query_map([], |r| Ok(format!("{}:{}", r.get::<_, String>(0)?, r.get::<_, i64>(1)?))).map(|rows| rows.flatten().collect()))                .unwrap_or_default();            let cursors: Vec<String> = db                .prepare("SELECT author_device_id, hlc_seen FROM _cursors WHERE author_device_id LIKE 'object%'")                .and_then(|mut st| st.query_map([], |r| Ok(format!("{}={}", r.get::<_, String>(0)?, r.get::<_, String>(1)?.chars().take(160).collect::<String>()))).map(|rows| rows.flatten().collect()))                .unwrap_or_default();            out = format!(                "cursors [{}] open messages:{} chats:{} emails:{} threads:{} parked {{{}}}",                cursors.join(" | "),                one("SELECT count(*) FROM cotton_msg_messages"),                one("SELECT count(*) FROM cotton_msg_threads"),                one("SELECT count(*) FROM cotton_emails"),                one("SELECT count(*) FROM cotton_email_threads"),                parked.join(" ")            );        }    }    out}/// Comms' Mail tab searched as a phone does (COTTON_BIG_APPS "search-mail"): a Comms phone pulls its window, then/// asks `chat.mail` for each of COTTON_BIG_SEARCH's comma-separated words; mail beyond the window comes by its blind/// tokens (`GET /v1/blind`). Says what each search found, and any refusal.fn search_mail(phone: &Phone) {    for _ in 0..40 {        let said = phone.call("sync.now", json!({})).unwrap_or_default();        if said["behind"] != json!(true) {            break;        }    }    for words in var("COTTON_BIG_SEARCH").unwrap_or_default().split(',').map(str::trim).filter(|w| !w.is_empty()) {        let started = Instant::now();        match phone.call("chat.mail", json!({ "filter": "all", "text": words })) {            Ok(page) => {                let rows: Vec<String> = page["rows"].as_array().into_iter().flatten().map(|r| format!("{} | {}", r["subject"].as_str().unwrap_or(""), r["when"].as_str().unwrap_or(""))).collect();                println!("SEARCHED {words:?} ({:.1}s): {} rows {rows:?} older={} empty={}", started.elapsed().as_secs_f64(), rows.len(), page["older"], page["empty"]);            }            Err(e) => println!("SEARCHED {words:?}: refused {e}"),        }        // The object asked by blind tokens alone, as seal.search does: what it holds beyond the window, opened here.        match phone.call("seal.search", json!({ "table": "email", "query": words, "limit": 20 })) {            Ok(found) => {                let hits: Vec<String> = found["hits"].as_array().into_iter().flatten().map(|h| format!("{} | {}", h["row"]["subject"].as_str().unwrap_or(""), h["row"]["sent_at"].as_str().unwrap_or(""))).collect();                println!("BLIND {words:?}: {} hits {hits:?}, {} unopened {}", hits.len(), found["unopened"].as_array().map_or(0, Vec::len), found["unopened"]);            }            Err(e) => println!("BLIND {words:?}: refused {e}"),        }    }}/// The account's mail as the object holds it (COTTON_BIG_APPS "count-mail"): an Email phone, whose kit has no window,/// pulls until two passes bring nothing new, then its copy is counted. Said: the emails, the conversations, the/// emails in Comms' 90 days, and the conversations that name more mail than came (once, 600 invented emails did not/// reach the object while their conversations did).fn count_mail(phone: &Phone) {    let started = Instant::now();    let mut last = None;    let mut still = 0;    for pass in 0..600 {        let said = phone.call("sync.now", json!({}));        let counts = mail_counts(phone._container.path());        eprintln!("COUNT pass {pass} ({:.0}s): {counts:?} {}", started.elapsed().as_secs_f64(), said.err().unwrap_or_default());        still = if Some(counts) == last && counts.0 > 0 { still + 1 } else { 0 };        last = Some(counts);        if still >= 2 {            break;        }    }    let (emails, threads, window, short) = last.unwrap_or_default();    println!("COUNTED mail on the object: {emails} emails, {threads} conversations, {window} emails in the last 90 days, {short} conversations short of their mail");}/// (emails, conversations, emails in the last 90 days, conversations whose email_count is above the emails held)./// The writes this phone's copy holds parked because the object refused them (`_parked`, direction push).fn parked_pushes(container: &Path) -> i64 {    let mut found = 0;    let mut stack = vec![container.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);                continue;            }            if !std::fs::read(&path).is_ok_and(|b| b.starts_with(b"SQLite format 3")) {                continue;            }            let Ok(db) = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) else { continue };            found += db.query_row("SELECT count(*) FROM _parked WHERE direction = 'push'", [], |r| r.get::<_, i64>(0)).unwrap_or(0);        }    }    found}fn mail_counts(container: &Path) -> (i64, i64, i64, i64) {    let mut found = (0, 0, 0, 0);    let mut stack = vec![container.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);                continue;            }            let head = std::fs::read(&path).ok().filter(|b| b.starts_with(b"SQLite format 3"));            if head.is_none() {                continue;            }            let Ok(db) = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) else { continue };            let one = |sql: &str| db.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap_or(0);            if one("SELECT count(*) FROM sqlite_master WHERE name = 'cotton_emails'") == 0 {                continue;            }            let window = (chrono::Utc::now() - chrono::Duration::days(90)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);            found.0 += one("SELECT count(*) FROM cotton_emails");            found.1 += one("SELECT count(*) FROM cotton_email_threads");            found.2 += db.query_row("SELECT count(*) FROM cotton_emails WHERE sent_at >= ?", [&window], |r| r.get::<_, i64>(0)).unwrap_or(0);            found.3 += one("SELECT count(*) FROM cotton_email_threads t WHERE t.email_count > (SELECT count(*) FROM cotton_emails e WHERE e.thread_id = t.id)");        }    }    found}#[test]fn a_big_invented_account_is_made_on_the_dev_server() {    let Some(walk) = Walk::from_env() else {        eprintln!("SKIPPED: no COTTON_WALK_SERVER, COTTON_WALK_CODE_FILE and COTTON_BIG_NUMBER");        return;    };    let apps = var("COTTON_BIG_APPS").unwrap_or_else(|| "notes,days,story,messages".into());    let mut code = var("COTTON_BIG_CODE").or_else(|| var("COTTON_BIG_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the recovery code file").trim().to_string()));    let scratch = tempfile::tempdir().expect("a scratch dir");    let began = Instant::now();    for flavour in apps.split(',').map(str::trim).filter(|f| !f.is_empty()) {        let started = Instant::now();        // Mail is Comms' own: a Comms phone writes it.        // The count is the old Email app's phone: its kit pulls every row of mail, with no window.        let phone = Phone::open(&walk, match flavour { "mail" | "search-mail" | "first-pull" => "messages", "count-mail" => "email", "post-first-pull" => "mail", f => f });        let database = phone.sign_in(&walk);        eprintln!("SIGNED-IN {flavour} {} database {}", walk.number, &database[..8.min(database.len())]);        if flavour == "first-pull" {            first_pull(&phone, code.as_deref());            continue;        }        if flavour == "post-first-pull" {            post_first_pull(&phone, code.as_deref());            continue;        }        phone.hold_key(code.as_deref());        if code.is_none() {            let made = phone.must("recovery.make", json!({ "privateKey": phone.private_key }));            let made = made["code"].as_str().expect("recovery.make made no code").to_string();            println!("RECOVERY-CODE {made}");            code = Some(made);        }        let rows = match flavour {            "notes" => seed_notes(&phone, scratch.path()),            "days" => seed_days(&phone),            "story" => seed_story(&phone, scratch.path()),            "messages" => seed_chat(&phone, scratch.path()),            "mail" => seed_mail(&phone),            "count-mail" => {                count_mail(&phone);                continue;            }            "search-mail" => {                search_mail(&phone);                continue;            }            other => panic!("no seeding for {other}"),        };        let pushed = phone.push_all();        println!("MADE {flavour}: {rows} items, pushed in {pushed:.0}s, {:.0}s in all", started.elapsed().as_secs_f64());    }    println!("DONE {} in {:.0}s", walk.number, began.elapsed().as_secs_f64());}