//! UPGRADE PROOF, the old side (coordinator, 26 Nov 2026: five reviews in a day turned on what happens to the owner's//! phone at an upgrade). This file is copied verbatim into the core at an OLD sha (the build on his phone) by//! `scripts/upgrade-proof/old-core.sh`, so it uses only what every phone build since 24 Nov has: `CottonHandle::open`,//! the app's own methods, `personal.connect`, a pass to level, `rejected::park`. It fills a Words copy against the//! local test object (`wrangler dev`, started by `apps/business/scripts/__tests__/upgrade-proof.ts`) in the states that//! matter, then writes what it left (`UPGRADE_MANIFEST`) for the HEAD side (`upgrade_proof.rs`) to hold the new core//! to. Invented data only. Ignored unless that driver runs it.use std::collections::BTreeMap;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};usecrate::handle::{CottonHandle, OpenConfig, OpenMode};usecrate::methods::dispatch;pub(crate) fn given(name: &str) -> String { std::env::var(name).unwrap_or_else(|_| panic!("{name} is set by apps/business/scripts/__tests__/upgrade-proof.ts"))}/// Words, as the app sends its manifest.pub(crate) fn words_manifest() -> Value { json!({"genesis": "personal","flavour": "notes","name": "Cotton Words","databases": "single","database": "personal","fan": { "home": false, "tools": false, "opens": "notebook" },"kit": "notes","ground": "blank" })}/// The phone whose container is `container`, opened as Words.pub(crate) fn open_words(container: &str) -> CottonHandle {CottonHandle::open(OpenConfig { mode: OpenMode::Phone { container_path: container.to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(words_manifest()), }) .expect("an open core")}pub(crate) fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value { dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}pub(crate) fn level(handle: &CottonHandle) {let pass = handle.client().sync_now_until_level().expect("a pass with the object"); assert_ne!(pass["behind"], json!(true), "level after the pass: {pass}");}fn note(handle: &CottonHandle, text: &str) -> String {let id = ask(handle, "notes.new", json!({}))["id"].as_str().expect("a new note's id").to_string(); ask(handle, "notes.edit", json!({ "id": id, "text": text })); id}/// What the copy holds of its notes, its queue, its parks, its schema and its tables: read by SQL, as any build's.pub(crate) fn copy_state(handle: &CottonHandle) -> Value { handle .client() .with_writer(|file| {let db = file.driver;let text = |sql: &str, column: &str| -> Vec<String> { db.all(sql, &[]).map(|rows| rows.iter().filter_map(|row| row.text(column).map(str::to_string)).collect()).unwrap_or_default() };letmut notes = BTreeMap::new();for row in db.all("SELECT id, body FROM cotton_notes WHERE trashed_at IS NULL", &[]).map_err(|error| error.to_string())? {ifletSome(id) = row.text("id") { notes.insert(id.to_string(), row.text("body").unwrap_or_default().to_string()); } }letmut tables = BTreeMap::new();for name in text("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'cotton_%' ORDER BY name", "name") {let count = db.get(&format!("SELECT COUNT(*) AS n FROM \"{name}\""), &[]).ok().flatten().and_then(|row| row.int("n")).unwrap_or(-1); tables.insert(name, count); }// Every bookkeeping table that holds writes by op id (the queue, parks, a set-aside, history), counted:// where a write went when it left the queue.letmut op_tables = BTreeMap::new();for name in text("SELECT m.name FROM sqlite_master m WHERE m.type = 'table' AND substr(m.name, 1, 1) = '_' AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) WHERE name = 'op_id') ORDER BY m.name", "name") {let count = db.get(&format!("SELECT COUNT(*) AS n FROM \"{name}\""), &[]).ok().flatten().and_then(|row| row.int("n")).unwrap_or(-1); op_tables.insert(name, count); }let held = cotton_store::mint::clock::held_count(db).unwrap_or(-1);let user_version = db.get("PRAGMA user_version", &[]).ok().flatten().and_then(|row| row.int("user_version")).unwrap_or(-1);Ok(json!({"notes": notes,"outbox": text("SELECT op_id FROM _outbox WHERE tbl = 'cotton_notes' ORDER BY op_id", "op_id"),"outbox_all": text("SELECT op_id || ' ' || tbl || ' ' || row_id AS op FROM _outbox ORDER BY op_id", "op"),"parked_push": text("SELECT op_id FROM _parked WHERE direction = 'push' ORDER BY op_id", "op_id"),"parked_pull": text("SELECT op_id FROM _parked WHERE direction <> 'push' ORDER BY op_id", "op_id"),"user_version": user_version,"held": held,"op_tables": op_tables,"tables": tables, })) }) .expect("the copy read")}fn manifest_path() -> String { given("UPGRADE_MANIFEST")}/// The old build's first life: signed in, let in (the vault opened with an invented key, the data key minted; the/// shell keeps the key as the Keychain would, `key` in the manifest), three notes written and synced.#[test]#[ignore = "run by apps/business/scripts/__tests__/upgrade-proof.ts against wrangler dev"]fn upgrade_old_side_writes_a_words_copy_synced() {let (base, credential, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE"));let handle = open_words(&given("UPGRADE_CONTAINER")); ask(&handle, "personal.connect", json!({ "server": base, "databaseId": database, "credential": credential })); level(&handle);let client = handle.client(); client.vault().expect("a vault door").unlock(cotton_core::vault::Vmk::from_bytes([5; 32]), 1, client.now());let key = ask(&handle, "seal.mintKey", json!({}))["key"].as_str().expect("the key for the shell").to_string(); level(&handle);let synced: Vec<String> = ["An invented shopping list", "An invented reading list", "An invented plan for Sunday"].iter().map(|text| note(&handle, text)).collect(); level(&handle); level(&handle);let state = copy_state(&handle);let waiting: Vec<&str> = state["outbox_all"].as_array().expect("the queue").iter().filter_map(Value::as_str).collect();for id in &synced { assert!(!waiting.iter().any(|op| op.ends_with(id.as_str())), "{id} went: {waiting:?}"); }// Refused for good by the object: an edit of the third note, made and parked under one hold of the file (the// schedule cannot send it in between), as a pass parks a final 4xx. The object keeps the note's first words.let parked = synced[2].clone();let now_ms = client.clock().now().timestamp_millis();let now = chrono::Utc::now().to_rfc3339();letmut ids = cotton_client::seams::op_ids(client.random()); client .with_writer(|file| {let db = file.driver;letmut patch = serde_json::Map::new(); patch.insert("body".into(), json!("An invented plan for Sunday, an edit the object refused"));let change = cotton_store::mint::Change::update("cotton_notes", &parked, patch);let clock = cotton_store::mint::clock::writer_clock(db, now_ms, &mut ids).map_err(|error| error.to_string())?;let act = cotton_store::mint::Act { actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("upgrade_proof").map_err(|error| error.to_string())?), verb: "edit_note".into(), history: cotton_store::mint::History::None, changes: vec![change], }; cotton_store::mint::mint(db, &act, &clock, &mut ids, cotton_store::mint::Held::Replica).map_err(|error| error.to_string())?;let rows = db.all("SELECT op_id, bytes, sig FROM _outbox WHERE row_id = ?", &[SqlValue::Text(parked.clone())]).map_err(|error| error.to_string())?; assert!(!rows.is_empty(), "the edit is queued to be parked");for row in rows {let op = cotton_store::stored::outbox_row(&row)?; cotton_store::rejected::park(db, &op, cotton_store::rejected::Direction::Push, cotton_store::rejected::Class::Conflict, "bad_column: an invented refusal", &now).map_err(|error| error.to_string())?;// not a copy: a test writer's invented refusal: the op is parked in the same file first. db.run("DELETE FROM _outbox WHERE op_id = ?", &[SqlValue::Text(op.op_id.clone())]).map_err(|error| error.to_string())?; }Ok(()) }) .expect("the refused edit parked");let manifest = json!({ "app": "words", "database": database, "synced": synced, "parked": parked, "parked_on_object": "An invented plan for Sunday", "key": key });// not a copy: the upgrade manifest. std::fs::write(manifest_path(), serde_json::to_vec_pretty(&manifest).expect("JSON")).expect("the manifest written");}/// The old build's second life, launched with no network (never connected, so nothing can leave): the key handed/// back as a launch does, then an edit of a synced note and a new note, HELD in the file (`held = 1`) because this/// launch has no server time yet. Then what the copy holds is written for the HEAD side.#[test]#[ignore = "run by apps/business/scripts/__tests__/upgrade-proof.ts after the synced side"]fn upgrade_old_side_writes_a_words_copy_offline() {letmut manifest: Value = serde_json::from_slice(&std::fs::read(manifest_path()).expect("the synced side's manifest")).expect("JSON");let handle = open_words(&given("UPGRADE_CONTAINER")); ask(&handle, "seal.useKey", json!({ "key": manifest["key"] }));let synced: Vec<String> = manifest["synced"].as_array().expect("the synced notes").iter().filter_map(Value::as_str).map(str::to_string).collect(); ask(&handle, "notes.edit", json!({ "id": synced[0], "text": "An invented shopping list, edited offline" }));let queued = note(&handle, "An invented note written offline");let state = copy_state(&handle); assert!(state["held"].as_i64().unwrap_or(0) + state["outbox"].as_array().map_or(0, |q| q.len() as i64) > 0, "the edit and the new note wait: {state}"); assert!(!state["parked_push"].as_array().expect("the parks").is_empty(), "the refused edit is parked: {state}"); manifest["edited"] = json!(synced[0]); manifest["queued"] = json!(queued); manifest["state"] = state;// not a copy: the upgrade manifest. std::fs::write(manifest_path(), serde_json::to_vec_pretty(&manifest).expect("JSON")).expect("the manifest written");}/// AVATAR SEAL 2 (5), 27 Nov 2026: an old build is shown a face sealed by a new one. The old core has no `people` in/// its sealed kinds, so it fetches the face as any file; this launch asks for it as a picture is drawn/// (`media.ensure`, twice: fetched, then from the store) and says what came back (`UPGRADE-FACE`), so the driver/// (`apps/business/scripts/__tests__/upgrade-face.ts`) can hold it to: no panic, and never the picture's bytes;/// either a refusal or a file that is not an image, which the shells draw as the initials.#[test]#[ignore = "run by apps/business/scripts/__tests__/upgrade-face.ts against wrangler dev"]fn upgrade_old_side_is_shown_a_sealed_face() {let (base, credential, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE"));let face = given("UPGRADE_FACE_KEY");let handle = open_words(&given("UPGRADE_CONTAINER")); ask(&handle, "personal.connect", json!({ "server": base, "databaseId": database, "credential": credential })); level(&handle);letmut asked = Vec::new();for _ in0..2 {let said = match dispatch(&handle, "media.ensure", &json!({ "key": face })) {Ok(answer) => {let path = answer["path"].as_str().unwrap_or_default().to_string();let bytes = std::fs::read(&path).unwrap_or_default(); json!({ "answer": "path", "bytes": bytes.len(), "head": bytes.iter().take(4).map(|b| format!("{b:02x}")).collect::<String>() }) }Err(error) => json!({ "answer": "refused", "code": format!("{error:?}").chars().take(200).collect::<String>() }), }; asked.push(said); } println!("UPGRADE-FACE {}", json!({ "key": face, "asked": asked }));}