Cotton code
2019 lines · 89.0 KB · RustRaw
//! The 4d reads — and 4k's one addition to Home — against a seeded synthetic//! replica.//!//! EVERY FIXTURE IS SYNTHETIC — no real name, number or sentence anywhere in//! this tree ([nothing-real-ever-goes-in-cotton-s-public-tree]). The rows here//! are the ones the reads have opinions about: one row per To-decide key, a//! memory in each band, an agent's question and a person's remark on the same//! record, two active projects that must come out in activity order and an//! archived one that must not appear at all.//!//! `workspace` alone is `pub(crate)`, for one reader outside this file: 4k's//! `activity_tests.rs`, which needs the same seeded replica behind the same//! unmoving clock. `workspace_in` stays private — nothing outside names a zone//! — so the widening is exactly as wide as its one caller. One place a fixture//! phone is assembled beats two that could come to disagree about what one//! looks like.//!//! The clock is the CONTROLLER's seam, fixed at `2026-09-08T10:00:00Z`//! (`FixedClock::default_start`), so every band, every due date and every//! "today" below is assertable rather than a time bomb with a computable//! detonation date.use std::sync::Arc;use cotton_client::layout::Layout;use cotton_client::seams::{FixedClock, SeededRandom};use cotton_store::driver::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::events::EventBus;use crate::fixture;use crate::shell::client::ClientController;/// The instant the controller's clock is fixed at.const NOW: &str = "2026-09-08T10:00:00.000Z";fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// A replica with the fixture's synthetic life in it, plus whatever the test/// adds, behind a controller whose clock does not move.////// The seeding driver is DROPPED before the controller opens the file: one/// file, one connection, one writer is the store's discipline, and a test that/// held a second handle open would be testing something the app never does.pub(crate) fn workspace(    seed: impl FnOnce(&Driver),) -> (tempfile::TempDir, Arc<ClientController>) {    workspace_in(Some("UTC"), seed)}/// The same, with the DEVICE'S ZONE named — the one the app hands down at open/// (`OpenConfig.timeZone`) and the one every banding read below draws its day/// from. `None` is the phone that named none, which refuses.fn workspace_in(    time_zone: Option<&str>,    seed: impl FnOnce(&Driver),) -> (tempfile::TempDir, Arc<ClientController>) {    let dir = tempfile::tempdir().expect("a data directory");    let layout = Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    let path = layout.replica(fixture::WORKSPACE);    std::fs::create_dir_all(path.parent().expect("the replica has a folder"))        .expect("the replica folder");    {        let db = fixture::seeded(&path);        seed(&db);    }    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&serde_json::json!({            "mode": "remote",            "baseUrl": "https://api.cottondb.example.invalid",            "workspaceId": fixture::WORKSPACE,            "ownerId": fixture::OWNER,            "connectedAt": "2026-09-08T09:00:00.000Z",        }))        .expect("json"),    )    .expect("the connection record");    let events = Arc::new(EventBus::new());    let time_zone = time_zone.map(str::to_string);    // A machine to read, on every build: the sources it names are only    // registered where the host feature compiles them, and the fixture is    // the same shape either way.    let controller = ClientController::new(        layout,        events,        time_zone,        Some(crate::shell::client::MachineSources {            device: "A synthetic machine".to_string(),            home: dir.path().to_path_buf(),        }),    );    let controller = Arc::new(        controller            .with_seams(Arc::new(FixedClock::default_start()), Arc::new(SeededRandom::default()))            .heard_the_serving_mac(),    );    (dir, controller)}/// [`workspace`] with the kit's tools imported, through the one helper a/// synthetic household gets its tools by (`import_kit_tools`): no tool is/// built in (72nd amendment), so a household with tools imported them./// A workspace holding the kit's tools: `fixture::seeded` writes the shell/// and imports the kit, as a database this build made and a person filled.fn kit_workspace(seed: impl FnOnce(&Driver)) -> (tempfile::TempDir, Arc<ClientController>) {    workspace(seed)}fn home_of(client: &ClientController) -> Value {    super::home(client, &Map::new()).expect("home answers")}/// RULE: Tools answers its arrangement without Home's counts or projects band; it preserves the saved project order, and answers the database's tools and Home's tiles alphabetically by name (owner, 17 Oct 2026), whatever order the row holds them in.#[test]fn tool_order_does_not_read_the_household_home_data() {    let (_dir, client) = kit_workspace(|db| {        an_arrangement(            db,            r#"["garden","retired-project"]"#,            r#"["notebook","todos"]"#,            r#"["tool/notebook","tool/todos"]"#,        );    });    let read = super::read_for("read.toolOrder").expect("Tools has a focused read");    let super::ReadSource::Controller(answer) = read.source else {        panic!("the read names its database");    };    let order = answer(&client, &Map::new()).expect("Tools still reads");    assert_eq!(        order["projectSlugs"],        serde_json::json!(["garden", "retired-project"])    );    let keys: Vec<String> = order["tools"].as_array().unwrap().iter().map(|tool| tool["key"].as_str().unwrap().to_string()).collect();    assert_eq!(keys, editorial(), "the database's tools, alphabetical");    let views = view_ids(&order);    assert!(views.contains(&"tool/notebook".to_string()) && views.contains(&"tool/todos".to_string()), "{views:?}");    let borrowed: Vec<&str> = views.iter().map(String::as_str).collect();    assert_eq!(views, by_name(&borrowed), "Home's tiles, alphabetical");    assert!(order.get("counts").is_none());    assert!(order.get("projects").is_none());}// RULE: Tools and Home agree on the database's tools and on which tiles are on Home; a tool holding records says so, every tool is removable (removing one leaves its tables and data — 72nd amendment), and Add tool offers only a kit tool the database does not hold.#[test]fn tool_directory_agrees_with_home() {    let (_dir, client) = kit_workspace(|_| {});    let directory = super::tool_order(&client, &Map::new()).expect("Tools answers");    let home = home_of(&client);    let keys: Vec<Value> = directory["tools"].as_array().unwrap().iter().map(|tool| tool["key"].clone()).collect();    assert_eq!(Value::from(keys), home["arrangement"]["tools"]);    assert_eq!(directory["viewIds"], home["arrangement"]["viewIds"]);    let tool = |key: &str| directory["tools"].as_array().unwrap().iter().find(|tool| tool["key"] == key).cloned().unwrap();    assert_eq!(tool("todos")["holds"], Value::Bool(true), "the fixture's todos");    assert!(directory["tools"].as_array().unwrap().iter().all(|tool| tool["removable"] == Value::Bool(true)));    assert!(directory["tools"].as_array().unwrap().iter().all(|tool| tool["onHome"] == Value::Bool(true)));    assert_eq!(directory["addable"], serde_json::json!([]), "every kit tool is here already");    let unfilled = crate::fixture::bare();    let (_bare, bare) = workspace(|_| {});    drop(unfilled);    let empty = super::tool_order(&bare, &Map::new()).expect("a database with no tools answers");    let keys: Vec<&Value> = empty["tools"].as_array().unwrap().iter().map(|tool| &tool["key"]).collect();    assert_eq!(keys, [&Value::from(cotton_tools::home_arrangement::SHELL_BIN)], "no tool but the shell's Bin");    assert_eq!(empty["addable"], serde_json::json!(cotton_core::kit::ids()), "every kit tool");}/// The Asked-of-you rows as `key -> count`, which is what every list test asks.fn asked(answer: &Value) -> Vec<(String, u64)> {    answer["askedOfYou"]["rows"]        .as_array()        .expect("rows is an array")        .iter()        .map(|row| {            (                row["key"].as_str().expect("a key").to_string(),                row["count"].as_u64().expect("a count"),            )        })        .collect()}fn count_for(answer: &Value, key: &str) -> Option<u64> {    asked(answer)        .into_iter()        .find(|(name, _)| name == key)        .map(|(_, count)| count)}// ── the seeders, one per To-decide key ────────────────────────────────────fn a_pending_capture(db: &Driver) {    db.run(        "INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, route_status, \         created_at, updated_at) VALUES (?,?,?,?,'pending',?,?)",        &[            text("capture-a"),            text(fixture::WORKSPACE),            text("A synthetic thought about an alpaca."),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),        ],    )    .expect("a pending capture");}/// One memory row, live or archived. Memory has no review state, so nothing/// on Home bands it.fn a_memory(db: &Driver, id: &str, slug: &str, status: &str, created_at: &str) {    db.run(        "INSERT INTO cotton_memories (id, workspace_id, slug, title, body, status, visibility, \         origin_kind, archived_at, created_at, updated_at) \         VALUES (?,?,?,?,'A synthetic body.',?,'private','user',?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(slug),            text("A synthetic sentence about an alpaca."),            text(status),            // The file admits an archived entry only with the moment it was            // archived, and any other only without one.            if status == "archived" { text(created_at) } else { SqlValue::Null },            text(created_at),            text(created_at),        ],    )    .expect("a memory");}/// One mood moment stamped with a named day.fn a_mood(db: &Driver, id: &str, day: &str, at: &str, emotions: &str) {    db.run(        "INSERT INTO cotton_moods (id, workspace_id, at, line, emotions, emotions_by, local_day, \         created_at, updated_at) VALUES (?,?,?,?,?,'user',?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(at),            text("a synthetic moment"),            text(emotions),            text(day),            text(at),            text(at),        ],    )    .expect("a mood");}fn an_agents_question(db: &Driver) {    an_agents_question_on(db, "comment-agent");}fn an_agents_question_on(db: &Driver, id: &str) {    db.run(        "INSERT INTO cotton_comments (id, workspace_id, record_kind, record_id, body, \         author_kind, author_label, created_at, updated_at, kind) VALUES (?,?,?,?,?,'agent',?,?,?, 'question')",        &[            text(id),            text(fixture::WORKSPACE),            text("note"),            text("note-b"),            text("A synthetic question waiting on the owner."),            text("A synthetic assistant"),            text("2026-09-02T00:00:00.000Z"),            text("2026-09-02T00:00:00.000Z"),        ],    )    .expect("an agent's question");}fn a_session(db: &Driver, id: &str) {    db.run(        "INSERT INTO cotton_sessions (id, workspace_id, tool, external_id, machine, started_at, \         last_active_at, created_at, updated_at) VALUES (?,?,'claude-code',?,?,?,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(id),            text("A synthetic machine"),            text("2026-09-08T08:00:00.000Z"),            text("2026-09-08T08:30:00.000Z"),            text("2026-09-08T08:00:00.000Z"),            text("2026-09-08T08:30:00.000Z"),        ],    )    .expect("a session");}fn an_open_owner_question(db: &Driver, id: &str, from_session: &str, created_at: &str) {    db.run(        "INSERT INTO cotton_session_messages (id, workspace_id, to_kind, from_kind, \         from_session_id, kind, body, status, created_at, updated_at) \         VALUES (?,?,'owner','session',?,'question',?,'open',?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(from_session),            text("A synthetic question only the owner can settle."),            text(created_at),            text(created_at),        ],    )    .expect("an owner question");}fn a_failed_document(db: &Driver) {    db.run(        "INSERT INTO cotton_documents (id, workspace_id, original_name, mime, byte_size, sha256, \         storage_path, status, failed_stage, status_changed_at, created_at, updated_at) \         VALUES (?,?,?,?,1,?,?,'failed','extract',?,?,?)",        &[            text("document-failed"),            text(fixture::WORKSPACE),            text("synthetic.pdf"),            text("application/pdf"),            text(&"a".repeat(64)),            text("documents/synthetic.pdf"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),        ],    )    .expect("a failed document");}fn an_unanswered_invitation(db: &Driver, starts_at: &str) {    db.run(        "INSERT INTO cotton_collections (id, workspace_id, kind, name, created_at) \         VALUES (?,?,'calendar',?,?)",        &[            text("collection-a"),            text(fixture::WORKSPACE),            text("A synthetic calendar"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("a calendar");    db.run(        "INSERT INTO cotton_events (id, collection_id, title, starts_at, my_response, organizer_is_self, created_at, updated_at) \         VALUES (?,?,?,?,'needs_action',0,?,?)",        &[            text("event-a"),            text("collection-a"),            text("A synthetic meeting"),            text(starts_at),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("an event");}/// Two of the owner's own events ahead, as Google sync writes them: no/// organizer (so the owner's), no attendees, no reply.fn the_owners_own_events(db: &Driver) {    db.run(        "INSERT INTO cotton_collections (id, workspace_id, kind, name, created_at) \         VALUES (?,?,'calendar',?,?)",        &[            text("collection-own"),            text(fixture::WORKSPACE),            text("A synthetic calendar"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("a calendar");    for id in ["own-a", "own-b"] {        db.run(            "INSERT INTO cotton_events (id, collection_id, title, starts_at, created_at, updated_at) \             VALUES (?,?,?,?,?,?)",            &[                text(id),                text("collection-own"),                text("A synthetic errand"),                text("2026-09-09T10:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),            ],        )        .expect("an event");    }}// ── Asked of you: one test per key ────────────────────────────────────────/// RULE: Home's Asked of you never counts a thought routing was unsure of, a memory entry, or a document that failed to read — each stays on its own screen, and what Cotton did shows in Done for you.////// On 27 Sep 2026 the owner was told 1,108 things waited, and twenty were questions.#[test]fn thoughts_memories_and_failed_documents_are_not_asked_of_the_owner() {    let (_dir, client) = workspace(|db| {        a_pending_capture(db);        a_memory(db, "mem-1", "alpaca-one", "active", "2026-09-01T00:00:00.000Z");        a_memory(db, "mem-2", "alpaca-two", "archived", "2026-09-02T00:00:00.000Z");        a_failed_document(db);    });    let answer = home_of(&client);    assert!(asked(&answer).is_empty(), "{answer}");    assert_eq!(answer["askedOfYou"]["total"].as_u64(), Some(0));    // Memory has no review state: Home counts no band of it.    assert!(answer.get("unreviewedMemories").is_none(), "{answer}");}/// RULE: The session inbox is gone: an old owner-addressed question on the session bus is history, never asked of the owner, because nothing can answer it any more.#[test]fn an_old_session_question_is_not_asked_of_the_owner() {    let (_dir, client) = workspace(|db| {        an_agents_question(db);        a_session(db, "session-a");        an_open_owner_question(db, "message-a", "session-a", "2026-09-08T09:00:00.000Z");    });    let answer = home_of(&client);    // The comment table is held as retired (TABLE DROP 1): an agent's question there is no row either.    assert_eq!(count_for(&answer, "assistantsAsked"), None);    assert!(answer["askedOfYou"].get("askingSessionId").is_none(), "{answer}");}fn a_locked_document(db: &Driver) {    db.run(        "INSERT INTO cotton_documents (id, workspace_id, original_name, mime, byte_size, sha256, \         storage_path, status, error_code, status_changed_at, created_at, updated_at) \         VALUES (?,?,?,?,1,?,?,'locked','password_required',?,?,?)",        &[            text("document-locked"),            text(fixture::WORKSPACE),            text("locked.pdf"),            text("application/pdf"),            text(&"b".repeat(64)),            text("documents/locked.pdf"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),        ],    )    .expect("a locked document");}/// Only the owner has the password: the one document state that is a question.#[test]fn a_document_locked_by_a_password_is_asked() {    let (_dir, client) = workspace(a_locked_document);    let answer = home_of(&client);    assert_eq!(count_for(&answer, "passwords"), Some(1));}#[test]fn an_unanswered_invitation_still_ahead_moves_invites() {    let (_dir, client) = workspace(|db| an_unanswered_invitation(db, "2026-09-09T10:00:00.000Z"));    let answer = home_of(&client);    assert_eq!(count_for(&answer, "invites"), Some(1));}// RULE: The owner's own events ahead — no organizer, no attendees, no reply — are never invites to answer (Home said "2 invites to answer" over two of them, 11 Oct 2026).#[test]fn the_owners_own_events_are_never_invites() {    let (_dir, client) = workspace(the_owners_own_events);    let answer = home_of(&client);    assert_eq!(count_for(&answer, "invites"), None);}#[test]fn an_invitation_to_a_meeting_that_has_happened_is_no_decision() {    let (_dir, client) = workspace(|db| an_unanswered_invitation(db, "2026-09-01T10:00:00.000Z"));    let answer = home_of(&client);    assert_eq!(count_for(&answer, "invites"), None);}/// `aiAccess` is a CLIENT flag — session-only, never persisted — so no read/// over the replica may ever produce it. The Swift model appends that row/// itself, which stays in band order because `aiAccess` is last.#[test]fn ai_access_is_never_a_row_this_read_produces() {    let (_dir, client) = workspace(|db| {        a_pending_capture(db);        a_failed_document(db);    });    let answer = home_of(&client);    assert_eq!(count_for(&answer, "aiAccess"), None);}#[test]fn a_zero_count_key_is_absent_rather_than_a_zero_row() {    let (_dir, client) = workspace(a_locked_document);    let answer = home_of(&client);    let keys: Vec<String> = asked(&answer).into_iter().map(|(key, _)| key).collect();    assert_eq!(keys, vec!["passwords".to_string()]);}#[test]fn the_total_is_the_sum_of_the_counts_and_never_the_row_count() {    let (_dir, client) = workspace(|db| {        a_locked_document(db);        an_unanswered_invitation(db, "2026-09-09T10:00:00.000Z");    });    let answer = home_of(&client);    // Two ROWS (passwords 1, invites 1) and a total of two: the total is the    // sum of the counts.    assert_eq!(asked(&answer).len(), 2);    assert_eq!(answer["askedOfYou"]["total"].as_u64(), Some(2));}// ── the memory row, the projects band, and the fifteen figures ───────────#[test]fn the_projects_band_is_active_only_and_in_activity_order() {    let (_dir, client) = workspace(|db| {        db.run(            "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, \             created_at, updated_at) VALUES (?,?,?,?,'active',?,?)",            &[                text("project-b"),                text(fixture::WORKSPACE),                text("alpaca-newer"),                text("Alpaca Newer"),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),            ],        )        .expect("a second active project");        // A session bound to the newer project, more recent than anything        // `project-a`'s linked note carries.        db.run(            "INSERT INTO cotton_sessions (id, workspace_id, project_id, tool, external_id, \             machine, started_at, last_active_at, created_at, updated_at) \             VALUES (?,?,?,'claude-code',?,?,?,?,?,?)",            &[                text("session-b"),                text(fixture::WORKSPACE),                text("project-b"),                text("session-b"),                text("A synthetic machine"),                text("2026-09-08T08:00:00.000Z"),                text("2026-09-08T09:30:00.000Z"),                text("2026-09-08T08:00:00.000Z"),                text("2026-09-08T09:30:00.000Z"),            ],        )        .expect("a session on the newer project");    });    let answer = home_of(&client);    let projects = answer["projects"].as_array().expect("an array");    let ids: Vec<&str> = projects        .iter()        .map(|project| project["id"].as_str().expect("an id"))        .collect();    // The archive is not a working context and does not appear at all.    assert_eq!(ids, vec!["project-b", "project-a"]);    assert_eq!(        projects[0]["lastActivity"].as_str(),        Some("2026-09-08T09:30:00.000Z")    );    assert_eq!(projects[0]["slug"].as_str(), Some("alpaca-newer"));    assert_eq!(answer["projectFactsMissing"], Value::Bool(false));}// ── the person's own order of Home ────────────────────────────────────────/// The database's tools as Home and Tools list them: the shell's Bin and the/// kit's tools together, alphabetical by the name each is drawn with — the/// Bin sorts among them ("Artifacts" comes before "Bin"), never first.fn editorial() -> Vec<String> {    let mut out: Vec<String> = std::iter::once(cotton_tools::home_arrangement::SHELL_BIN).chain(cotton_core::kit::ids().iter().copied()).map(str::to_string).collect();    cotton_core::js_text::sort_by_name(&mut out, |key| kit_name(key), String::clone);    out}/// A tile's name: a kit tool's own name (Coding sessions'), else its id with/// a capital (the shell's Bin).fn kit_name(key: &str) -> String {    if let Some(Ok(package)) = cotton_core::kit::package(key) {        return package.package.tool.name;    }    let mut letters = key.chars();    letters.next().map(|first| first.to_uppercase().chain(letters).collect()).unwrap_or_default()}/// These views as the fan orders them: alphabetical by the name each tile is/// drawn with (a tool's list by its tool's name, Everything as "Everything").fn by_name(views: &[&str]) -> Vec<String> {    let mut out: Vec<String> = views.iter().map(|view| (*view).to_string()).collect();    cotton_core::js_text::sort_by_name(        &mut out,        |view| match cotton_core::rules::home_arrangement::view_tool(view) {            Some(key) => kit_name(key),            None if view == "ready/everything" => "Everything".to_string(),            None => view.clone(),        },        String::clone,    );    out}fn view_ids(answer: &Value) -> Vec<String> {    let block = if answer.get("arrangement").is_some() { &answer["arrangement"] } else { answer };    serde_json::from_value(block["viewIds"].clone()).expect("a list of view ids")}fn database_tools(answer: &Value) -> Vec<String> {    serde_json::from_value(answer["arrangement"]["tools"].clone()).expect("a list of tools")}/// Home's tiles as drawn: (view id, empty), in order.fn tiles(answer: &Value) -> Vec<(String, bool)> {    answer["arrangement"]["tiles"]        .as_array()        .expect("tiles")        .iter()        .map(|tile| (tile["id"].as_str().expect("an id").to_string(), tile["empty"].as_bool().expect("empty")))        .collect()}/// One arrangement row, as the write lands it.fn an_arrangement(db: &Driver, project_slugs: &str, tools: &str, view_ids: &str) {    db.run(        "INSERT INTO cotton_home_arrangement (workspace_id, project_slugs, tools, \         view_ids, created_at, updated_at) VALUES (?,?,?,?,?,?)",        &[            text(fixture::WORKSPACE),            text(project_slugs),            text(tools),            text(view_ids),            text(NOW),            text(NOW),        ],    )    .expect("an arrangement row");}/// The fixture's second active project, the one the existing band test adds —/// `alpaca-newer`, with a session newer than anything `project-a` carries.fn a_second_active_project(db: &Driver) {    db.run(        "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, \         created_at, updated_at) VALUES (?,?,?,?,'active',?,?)",        &[            text("project-b"),            text(fixture::WORKSPACE),            text("alpaca-newer"),            text("Alpaca Newer"),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("a second active project");    db.run(        "INSERT INTO cotton_sessions (id, workspace_id, project_id, tool, external_id, \         machine, started_at, last_active_at, created_at, updated_at) \         VALUES (?,?,?,'claude-code',?,?,?,?,?,?)",        &[            text("session-b"),            text(fixture::WORKSPACE),            text("project-b"),            text("session-b"),            text("A synthetic machine"),            text("2026-09-08T08:00:00.000Z"),            text("2026-09-08T09:30:00.000Z"),            text("2026-09-08T08:00:00.000Z"),            text("2026-09-08T09:30:00.000Z"),        ],    )    .expect("a session on the newer project");}#[test]fn with_no_arrangement_row_the_band_is_activity_order_and_the_tools_are_editorial() {    let (_dir, client) = kit_workspace(a_second_active_project);    let answer = home_of(&client);    assert_eq!(        answer["arrangement"]["manual"],        Value::Bool(false),        "nobody has arranged, and the app needs to know that rather than re-derive it"    );    assert_eq!(database_tools(&answer), editorial());    let mut every: Vec<String> = editorial().iter().map(|key| format!("tool/{key}")).collect();    every.push("ready/everything".to_string());    let every: Vec<&str> = every.iter().map(String::as_str).collect();    assert_eq!(view_ids(&answer), by_name(&every), "every tool's list and Everything, alphabetical: nothing is put away");    let slugs: Vec<&str> = answer["projects"]        .as_array()        .expect("an array")        .iter()        .map(|project| project["slug"].as_str().expect("a slug"))        .collect();    assert_eq!(slugs, vec!["alpaca-newer", "alpaca-work"]);}#[test]fn an_arrangement_row_reorders_the_band_by_slug() {    let (_dir, client) = workspace(|db| {        a_second_active_project(db);        an_arrangement(db, r#"["alpaca-work"]"#, "[]", "[]");    });    let answer = home_of(&client);    assert_eq!(answer["arrangement"]["manual"], Value::Bool(true));    let slugs: Vec<&str> = answer["projects"]        .as_array()        .expect("an array")        .iter()        .map(|project| project["slug"].as_str().expect("a slug"))        .collect();    // Activity puts `alpaca-newer` first; the person put `alpaca-work` there.    assert_eq!(slugs, vec!["alpaca-work", "alpaca-newer"]);    // The rest of the row is untouched — arranging reorders, it does not    // rewrite what a project IS.    assert_eq!(        answer["projects"][1]["lastActivity"].as_str(),        Some("2026-09-08T09:30:00.000Z")    );}#[test]fn an_archived_slug_drops_out_and_a_project_born_later_appends_in_activity_order() {    let (_dir, client) = workspace(|db| {        a_second_active_project(db);        // `zeppelin-gone` is not a project in this file at all — an archive,        // said the way a stale stored list says it. `alpaca-newer` was born        // after the drag and is not named.        an_arrangement(db, r#"["zeppelin-gone","alpaca-work"]"#, "[]", "[]");    });    let answer = home_of(&client);    let slugs: Vec<&str> = answer["projects"]        .as_array()        .expect("an array")        .iter()        .map(|project| project["slug"].as_str().expect("a slug"))        .collect();    assert_eq!(slugs, vec!["alpaca-work", "alpaca-newer"]);}/// RULE: a tile the person took off Home stays off — its tool still one of the database's — and a view naming nothing here (a tool no build knows, a group that is gone) is dropped by the read, never answered to the screen.#[test]fn a_tile_off_home_stays_off_and_an_unknown_view_is_dropped_by_the_read() {    let every = serde_json::to_string(&editorial()).expect("the keys");    let (_dir, client) = kit_workspace(|db| {        an_arrangement(            db,            "[]",            &every.replacen('[', r#"["zeppelin","#, 1),            r#"["tool/todos","tool/zeppelin","note/no-such-group","ready/everything"]"#,        );    });    let answer = home_of(&client);    assert_eq!(view_ids(&answer), by_name(&["tool/todos", "ready/everything"]));    let tools = database_tools(&answer);    assert_eq!(tools.len(), editorial().len(), "the database's tools, the ones off Home too");    assert!(tools.iter().any(|key| key == "notebook"));    assert!(!tools.iter().any(|key| key == "zeppelin"), "a key no build knows is dropped by the read");}#[test]fn a_row_this_build_cannot_read_refuses_rather_than_answering_the_default_order() {    // A silent fallback here would answer the editorial order and the next    // Done would overwrite a real arrangement with it.    let (_dir, client) = workspace(|db| {        an_arrangement(db, r#"[1,2]"#, "[]", "[]");    });    let refusal = super::home(&client, &Map::new()).expect_err("a refusal");    assert!(        refusal.contains("project_slugs"),        "the refusal names the column: {refusal}"    );}/// RULE: Home's counts are exactly the reads a tool's tile figure may name (`TOOL_FIGURE_READS`), so a figure a definition names is always answered and a renamed count fails here, never as a silent zero.#[test]fn the_counts_are_every_read_a_tool_figure_names() {    let (_dir, client) = workspace(|_| {});    let answer = home_of(&client);    let counts = answer["counts"].as_object().expect("an object");    let mut names: Vec<&str> = counts.keys().map(String::as_str).collect();    names.sort_unstable();    let mut reads = cotton_core::definitions::TOOL_FIGURE_READS.to_vec();    reads.sort_unstable();    assert_eq!(names, reads);}#[test]fn the_figures_read_the_fixture_s_own_rows() {    let (_dir, client) = workspace(|_| {});    let answer = home_of(&client);    let counts = &answer["counts"];    // Three notes and two journal pages in the fixture; only the notes count.    assert_eq!(counts["notes"].as_u64(), Some(3));    // Three todos, all open.    assert_eq!(counts["openTodos"].as_u64(), Some(3));    // One live person; the archived one is not a figure.    assert_eq!(counts["people"].as_u64(), Some(1));    // One active project, one archived.    assert_eq!(counts["activeProjects"].as_u64(), Some(1));    // Neither journal page is today's, so today's is still blank.    assert_eq!(counts["journalUnwritten"], Value::Bool(true));    // A state, never a count — and false while nothing is ready to read.    assert_eq!(counts["freshEdition"], Value::Bool(false));    // No coding session and no launch in the fixture, so the Code row is    // silent — both halves of its caption are zero.    assert_eq!(counts["runningSessions"].as_u64(), Some(0));    assert_eq!(counts["waitingSessions"].as_u64(), Some(0));}/// One coding session per state the Code queue cuts on, so the Home figure and/// the `/code` sections cannot come to disagree about which session is running/// and which is asking for something.////// ONE OBJECT (v23): every row here is a `cotton_sessions` row, `queued`/// included — there is no launch table to count beside it and so no way to/// count one piece of work twice.#[test]fn the_code_row_counts_what_is_running_and_what_is_blocked_on_the_person() {    let (_dir, client) = workspace(|db| {        // Running: an agent is actually in it.        a_coding_session(db, "ses-run", "ext-run", Some("running"), None, 1, NOW);        a_coding_session(db, "ses-start", "ext-start", Some("starting"), None, 1, NOW);        // Waiting on the person — a permission, a question, a typed answer.        a_coding_session(db, "ses-wait", "ext-wait", Some("waiting"), None, 1, NOW);        // A HOST-OWNED idle session active within the hour is one the person        // has open; the same session yesterday is a tab they forgot.        a_coding_session(db, "ses-idle", "ext-idle", Some("idle"), None, 1, NOW);        a_coding_session(db, "ses-stale", "ext-stale", Some("idle"), None, 1, LONG_AGO);        // An ADOPTED idle session is somebody's own terminal Cotton merely        // noticed — never a badge on Home.        a_coding_session(db, "ses-adopted", "ext-adopted", Some("idle"), None, 0, NOW);        // A session nobody has started has no agent in it yet — and so no        // `external_id` at all, which the row's own CHECK insists on.        a_queued_session(db, "ses-queued");        // And a NULL state is a session logged before the Code tool existed.        a_coding_session(db, "ses-old", "ext-old", None, None, 0, NOW);        // Neither: one finished.        a_coding_session(db, "ses-done", "ext-done", Some("ended"), Some(NOW), 1, NOW);    });    let counts = &home_of(&client)["counts"];    assert_eq!(        counts["runningSessions"].as_u64(),        Some(3),        "starting, running, and the host-owned idle one active within the hour"    );    assert_eq!(counts["waitingSessions"].as_u64(), Some(1));}/// One synthetic session nobody has started: no agent, so no `external_id`.fn a_queued_session(db: &Driver, id: &str) {    db.run(        "INSERT INTO cotton_sessions (id, workspace_id, tool, prompt, state, state_at, \         last_active_at, host_owned, created_at, updated_at) \         VALUES (?,?,?,?,'queued',?,?,1,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text("claude-code"),            text("a synthetic prompt"),            text(NOW),            text(NOW),            text(NOW),            text(NOW),        ],    )    .expect("a queued session row");}/// A day before [`NOW`] — past the hour an idle session stays "open" for.const LONG_AGO: &str = "2026-09-07T10:00:00.000Z";/// One synthetic coding session.fn a_coding_session(    db: &Driver,    id: &str,    external_id: &str,    state: Option<&str>,    ended_at: Option<&str>,    host_owned: i64,    last_active_at: &str,) {    db.run(        "INSERT INTO cotton_sessions (id, workspace_id, tool, external_id, machine, \         started_at, last_active_at, ended_at, state, host_owned, created_at, updated_at) \         VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text("claude-code"),            text(external_id),            text("synthetic-mac"),            text(NOW),            text(last_active_at),            ended_at.map_or(SqlValue::Null, text),            state.map_or(SqlValue::Null, text),            SqlValue::Integer(host_owned),            text(NOW),            text(NOW),        ],    )    .expect("a session row");}#[test]fn the_workspace_and_the_sync_banner_ride_the_same_answer() {    let (_dir, client) = workspace(|_| {});    let answer = home_of(&client);    assert_eq!(answer["workspace"]["id"].as_str(), Some(fixture::WORKSPACE));    assert_eq!(answer["workspace"]["name"].as_str(), Some("Synthetic"));    assert!(answer["workspace"]["cityName"].is_null());    // Exactly `sync_status()`, so the banner and the settings row cannot    // disagree about the same phone.    assert_eq!(answer["sync"], client.sync_status());}/// RULE: Home's city is the Me person's city — the person the workspace names as its owner, while present — never a second copy on the workspace row, so Settings › Your city, the Me card and Home's weather line read one city.#[test]fn homes_city_is_the_me_persons_city() {    let (_dir, client) = workspace(|db| {        db.run(            "INSERT INTO cotton_people (id, workspace_id, full_name, city, created_at, updated_at) \             VALUES ('synthetic-me', ?, 'Synthetic owner', 'Hyderabad', ?, ?)",            &[SqlValue::Text(fixture::WORKSPACE.into()), SqlValue::Text(NOW.into()), SqlValue::Text(NOW.into())],        )        .expect("the owner person");        db.run(            "UPDATE cotton_workspaces SET owner_person_id = 'synthetic-me' WHERE id = ?",            &[SqlValue::Text(fixture::WORKSPACE.into())],        )        .expect("the owner link");    });    assert_eq!(home_of(&client)["workspace"]["cityName"], "Hyderabad");}/// The instant is the controller's seam unless the caller names one — never a/// wall clock inside the read./// RULE: A named now is still parsed and a broken one still refused, even though no memory band reads a clock any more.#[test]fn a_named_now_is_parsed_and_a_broken_one_is_refused() {    let (_dir, client) = workspace(|db| {        a_memory(db, "mem-new", "alpaca-new", "active", "2026-09-02T00:00:00.000Z");    });    let mut args = Map::new();    args.insert("now".to_string(), Value::from("2026-09-01T00:00:00.000Z"));    let earlier = super::home(&client, &args).expect("home answers");    assert_eq!(earlier["unreadableMemories"].as_u64(), Some(0));    // A now that is not an instant is refused rather than silently ignored.    let mut broken = Map::new();    broken.insert("now".to_string(), Value::from("yesterday"));    assert!(super::home(&client, &broken).is_err());    assert_eq!(NOW, "2026-09-08T10:00:00.000Z");}// ── /mood ─────────────────────────────────────────────────────────────────fn mood_of(client: &ClientController) -> Value {    super::mood(client, &Map::new()).expect("the timeline answers")}/// The moments, newest first, and today's date. There is NO strip and no/// per-day average: a mood is a moment since schema v18, and an average of/// named emotions is not a thing. The screen groups by `localDay`, which is/// presentation.#[test]fn the_timeline_is_the_moments_newest_first_with_the_day_the_writer_stamped() {    let (_dir, client) = workspace(|db| {        a_mood(            db,            "mood-a",            "2026-09-07",            "2026-09-07T08:00:00.000Z",            r#"["tired"]"#,        );        a_mood(            db,            "mood-b",            "2026-09-08",            "2026-09-08T08:00:00.000Z",            r#"["hopeful","proud"]"#,        );    });    let answer = mood_of(&client);    assert_eq!(answer["today"].as_str(), Some("2026-09-08"));    assert!(        answer.get("strip").is_none(),        "the strip went with the score it averaged"    );    let moments = answer["moments"].as_array().expect("moments");    assert_eq!(moments.len(), 2);    assert_eq!(moments[0]["id"].as_str(), Some("mood-b"));    assert_eq!(        moments[0]["emotions"],        serde_json::json!(["hopeful", "proud"])    );    assert_eq!(moments[0]["localDay"].as_str(), Some("2026-09-08"));    assert_eq!(moments[0]["emotionsBy"].as_str(), Some("user"));    assert_eq!(moments[1]["id"].as_str(), Some("mood-a"));}/// Several moments on one day are several rows, not one revised reading — a/// person who felt flat at noon and fine by evening said two true things.#[test]fn several_moments_on_one_day_all_travel() {    let (_dir, client) = workspace(|db| {        a_mood(            db,            "mood-a",            "2026-09-08",            "2026-09-08T08:00:00.000Z",            r#"["low"]"#,        );        a_mood(            db,            "mood-b",            "2026-09-08",            "2026-09-08T19:00:00.000Z",            r#"["good"]"#,        );    });    let moments = mood_of(&client)["moments"]        .as_array()        .expect("moments")        .len();    assert_eq!(moments, 2);}// ── /take and /keyboard-take ──────────────────────────────────────────────#[test]fn the_mic_reads_the_corpus_and_the_vocabulary_in_its_own_order() {    let (_dir, client) = workspace(|db| {        a_pending_capture(db);        // Manual first whatever the counts say — the owner typed those, and a        // word the model proposed fifty times must not outvote one of them.        for (id, term, source, uses) in [            ("vocab-auto", "alpaca", "auto", 50),            ("vocab-manual", "vicuna", "manual", 1),        ] {            db.run(                "INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, \                 created_at) VALUES (?,?,?,?,?,?)",                &[                    text(id),                    text(fixture::WORKSPACE),                    text(term),                    text(source),                    SqlValue::Integer(uses),                    text("2026-09-01T00:00:00.000Z"),                ],            )            .expect("a vocabulary term");        }    });    let answer = super::take(&client, &Map::new()).expect("the mic answers");    assert_eq!(answer["corpusCount"].as_u64(), Some(1));    assert_eq!(        answer["biasTerms"].as_array().unwrap()[..2],        serde_json::json!(["vicuna", "alpaca"]).as_array().unwrap()[..]    );    // The HIGHLIGHTING list is a different list: every term, in the    // vocabulary's own order, which is not the ranked one.    assert_eq!(        answer["vocabularyTerms"].as_array().unwrap().iter().filter(|term| ["alpaca", "vicuna"].contains(&term.as_str().unwrap())).cloned().collect::<Vec<_>>(),        serde_json::json!(["alpaca", "vicuna"]).as_array().unwrap().clone()    );}/// The two lists are not one list. Both come off one query and go to/// different places: the highlighting list underlines against EVERY term,/// unbounded, while the bias list feeds the recogniser its ranked hundred./// Answering only the second would silently stop the phone underlining a/// word it should.#[test]fn the_highlighting_list_is_every_term_where_the_bias_list_stops_at_a_hundred() {    let (_dir, client) = workspace(|db| {        for n in 0..120 {            db.run(                "INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, \                 created_at) VALUES (?,?,?,'auto',?,?)",                &[                    text(&format!("vocab-{n:03}")),                    text(fixture::WORKSPACE),                    text(&format!("synthetic{n:03}")),                    SqlValue::Integer(i64::from(120 - n)),                    text("2026-09-01T00:00:00.000Z"),                ],            )            .expect("a vocabulary term");        }    });    let answer = super::take(&client, &Map::new()).expect("the mic answers");    assert_eq!(answer["biasTerms"].as_array().map(Vec::len), Some(100));    let terms = answer["vocabularyTerms"].as_array().unwrap();    for n in 0..120 {        assert!(terms.contains(&serde_json::json!(format!("synthetic{n:03}"))));    }}// RULE: The words dictation listens for are the person's, and the open database's names come next: `/take` read inside a shared database answers the personal database's hand list first, so a word typed into Voice words is heard in every database, then that database's own names ahead of the rest (Me brief, piece 3).#[test]fn the_mic_in_a_shared_database_hears_the_person_s_own_words() {    const GARDEN: &str = "33333333-3333-4333-8333-333333333333";    let (dir, client) = workspace(|db| {        db.run(            "INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, \             created_at) VALUES ('vocab-mine', ?, 'quokka', 'manual', 1, ?)",            &[text(fixture::WORKSPACE), text("2026-09-01T00:00:00.000Z")],        )        .expect("a vocabulary term");    });    let layout = Layout::new(dir.path());    let record = layout.connection_json();    let mut connection: Value =        serde_json::from_slice(&std::fs::read(&record).expect("the record")).expect("json");    connection["places"] = serde_json::json!([        { "id": GARDEN, "name": "Garden", "available": true, "unavailableSince": null, "pending": true },        { "id": "44444444-4444-4444-8444-444444444444", "name": "Arriving", "available": true, "unavailableSince": null },    ]);    std::fs::write(&record, serde_json::to_vec_pretty(&connection).expect("json"))        .expect("the record");    let path = layout.replica(GARDEN);    std::fs::create_dir_all(path.parent().expect("a parent")).expect("the replica folder");    let garden = cotton_store::test_template::create_workspace_for_test(        &path,        &cotton_store::meta::Meta {            workspace_id: GARDEN.to_string(),            owner_id: fixture::OWNER.to_string(),            device_id: fixture::DEVICE.to_string(),            last_server_seq: 0,            last_hlc: None,        },    )    .expect("a synthetic database");    garden        .run(            "INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) \             VALUES (?,'Garden',?,?)",            &[text(GARDEN), text(fixture::OWNER), text(NOW)],        )        .expect("the workspace row");    // Garden as this build creates it and its people filled it: the shell, the kit.    fixture::created_and_filled(&garden);    garden.run(        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('garden-person', ?, 'Quince Wren', ?, ?)",        &[text(GARDEN), text(NOW), text(NOW)],    ).expect("a name from the shared database");    drop(garden);    let _garden = client.name_database(Some(GARDEN)).expect("Garden is held");    let answer = super::take(&client, &Map::new()).expect("the mic answers in Garden");    let personal_and_shared: Vec<_> = answer["biasTerms"].as_array().unwrap().iter()        .filter(|term| ["quokka", "Garden", "Quince Wren", "Alpaca Tester"].contains(&term.as_str().unwrap()))        .cloned().collect();    assert_eq!(personal_and_shared, serde_json::json!(["quokka", "Garden", "Quince Wren", "Alpaca Tester"]).as_array().unwrap().clone());    for term in ["quokka", "Garden", "Quince Wren", "Alpaca Tester"] {        assert!(answer["vocabularyTerms"].as_array().unwrap().contains(&serde_json::json!(term)));    }    drop(_garden);    connection["places"] = serde_json::json!([]);    std::fs::write(&record, serde_json::to_vec(&connection).unwrap()).unwrap();    let after_leave = super::take(&client, &Map::new()).expect("the mic drops words from a database no longer held");    assert!(!after_leave["vocabularyTerms"].as_array().unwrap().contains(&serde_json::json!("Quince Wren")));}// ── the day boundary: whose calendar the reads band by ─────────────────────fn mood_at(client: &ClientController, now: &str) -> Value {    let mut args = Map::new();    args.insert("now".to_string(), Value::from(now));    super::mood(client, &args).expect("the timeline answers")}/// The DEVICE's zone decides the day, not the workspace's and never UTC. At/// 19:30 UTC a phone in Asia/Kolkata is already an hour into tomorrow, and the/// writer (`record_mood {timezone: …}`) stamps a moment recorded then with/// tomorrow's date. A reader banding in UTC would file that row under the wrong/// header — the moment the person had just recorded would sit under yesterday.#[test]fn the_day_is_the_device_s_own_and_never_utc() {    let (_dir, client) = workspace_in(Some("Asia/Kolkata"), |db| {        a_mood(            db,            "mood-a",            "2026-09-09",            "2026-09-08T19:30:00.000Z",            r#"["calm"]"#,        );    });    let answer = mood_at(&client, "2026-09-08T19:30:00.000Z");    assert_eq!(answer["today"].as_str(), Some("2026-09-09"));    let moments = answer["moments"].as_array().expect("moments");    assert_eq!(moments.len(), 1);    assert_eq!(moments[0]["localDay"].as_str(), Some("2026-09-09"));}/// And a phone that named no zone REFUSES rather than falling to UTC. A/// timeline silently grouped in the wrong zone says nothing about being wrong;/// this is `record_mood`'s `writer_zone` rule, on the reader's side.#[test]fn a_phone_that_named_no_zone_refuses_rather_than_guessing_one() {    let (_dir, client) = workspace_in(None, |_| {});    assert!(super::home(&client, &Map::new()).is_err());    assert!(super::mood(&client, &Map::new()).is_err());}// ── the figures, against the app's own filters ────────────────────────────/// A note an assistant manages is not one of the owner's notes. `listNotes`/// hides them unless a surface asks for them by name, and Home does not — a/// figure the owner cannot account for is worse than no figure.#[test]fn a_managed_note_is_not_one_of_the_owner_s_notes() {    let (_dir, client) = workspace(|db| {        db.run(            "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, managed_by, \             external_id, created_at, updated_at) VALUES (?,?,'note',?,?,?,?,?,?)",            &[                text("note-managed"),                text(fixture::WORKSPACE),                text("A synthetic managed note"),                text("Kept in step by an assistant."),                text("A synthetic assistant"),                text("external-managed-1"),                text("2026-09-06T00:00:00.000Z"),                text("2026-09-06T00:00:00.000Z"),            ],        )        .expect("a managed note");    });    // Still the fixture's three, not four.    assert_eq!(home_of(&client)["counts"]["notes"].as_u64(), Some(3));}/// A PROJECT's journal page is not the owner's page. Since v21 a journal page/// belongs to a context, and without the filter an assistant's project entry/// would light his streak and be offered as "today's page" to write into.#[test]fn a_project_s_journal_page_does_not_write_the_owner_s_day() {    let (_dir, client) = workspace(|db| {        db.run(            "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, journal_date, \             project_id, created_at, updated_at) VALUES (?,?,'journal',?,?,?,?,?,?)",            &[                text("journal-project"),                text(fixture::WORKSPACE),                text("A synthetic project day"),                text("Written into a project rather than the owner's stream."),                text("2026-09-08"),                text("project-a"),                text("2026-09-08T00:00:00.000Z"),                text("2026-09-08T00:00:00.000Z"),            ],        )        .expect("a project journal page");    });    assert_eq!(        home_of(&client)["counts"]["journalUnwritten"],        Value::Bool(true)    );}/// One inbound live message past the cursor is the badge. `unread_count`'s own/// predicate, said in SQL over the whole workspace at once, which is what the/// TypeScript does and why.fn a_thread(db: &Driver, id: &str, archived: i64, cleared_before: Option<&str>) {    db.run(        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, archived, read_seq, \         cleared_before, created_at, updated_at) VALUES (?,?,'group',?,?,0,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text("A synthetic group"),            SqlValue::Integer(archived),            cleared_before.map_or(SqlValue::Null, text),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("a thread");}#[allow(clippy::too_many_arguments)]fn an_inbound_message(    db: &Driver,    id: &str,    thread_id: &str,    seq: i64,    sent_at: &str,    hidden: bool,) {    db.run(        "INSERT INTO cotton_msg_messages (id, workspace_id, thread_id, direction, channel, \         origin, seq, sent_at, hidden_at, body, created_at) \         VALUES (?,?,?,'in','cotton','live',?,?,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(thread_id),            SqlValue::Integer(seq),            text(sent_at),            if hidden {                text("2026-09-07T00:00:00.000Z")            } else {                SqlValue::Null            },            text("A synthetic line about alpacas."),            text(sent_at),        ],    )    .expect("an inbound message");}/// The three cuts the per-thread loop did not have, each one a badge the/// person had already cleared: an ARCHIVED thread's backlog, a HIDDEN row, and/// everything before a `cleared_before` cut.#[test]fn a_badge_the_person_already_cleared_is_not_counted_again() {    let (_dir, client) = workspace(|db| {        a_thread(db, "thread-live", 0, None);        an_inbound_message(db, "msg-live", "thread-live", 1, "2026-09-08T08:00:00.000Z", false);        an_inbound_message(db, "msg-hidden", "thread-live", 2, "2026-09-08T08:05:00.000Z", true);        a_thread(db, "thread-archived", 1, None);        an_inbound_message(            db,            "msg-archived",            "thread-archived",            1,            "2026-09-08T08:00:00.000Z",            false,        );        a_thread(db, "thread-cleared", 0, Some("2026-09-08T12:00:00.000Z"));        an_inbound_message(            db,            "msg-cleared",            "thread-cleared",            1,            "2026-09-08T08:00:00.000Z",            false,        );    });    // Only `msg-live` survives all three.    assert_eq!(        home_of(&client)["counts"]["unreadMessages"].as_u64(),        Some(1)    );}/// RULE: Home's unread-messages count is asked of the live threads, each thread's rows read from its cursor on through (thread_id, seq) — it never scans the messages, so it costs what is unread and not the history.#[test]fn the_unread_count_reads_past_each_threads_cursor_and_never_scans_the_messages() {    let (_dir, client) = workspace(|db| {        a_thread(db, "thread-live", 0, None);        // A long history already read, and two rows past the cursor.        for seq in 1..=60 {            an_inbound_message(db, &format!("msg-{seq}"), "thread-live", seq, "2026-09-08T08:00:00.000Z", false);        }        db.run("UPDATE cotton_msg_threads SET read_seq = 58 WHERE id = 'thread-live'", &[])            .expect("the cursor");        let plan: Vec<String> = db            .all(&format!("EXPLAIN QUERY PLAN {}", super::UNREAD_MESSAGES), &[text(fixture::WORKSPACE)])            .expect("a plan")            .iter()            .map(|row| row.text("detail").unwrap_or_default().to_string())            .collect();        assert!(            !plan.iter().any(|step| step.starts_with("SCAN") && step.contains("cotton_msg_messages"))                && plan.iter().any(|step| step.contains("(thread_id=? AND seq>?)")),            "the messages are scanned, or not read by (thread_id, seq): {plan:#?}"        );    });    assert_eq!(        home_of(&client)["counts"]["unreadMessages"].as_u64(),        Some(2)    );}// ── the memory queue: a row this build cannot read ────────────────────────/// A row whose status, visibility or origin this build has no words for is a/// file ahead of the binary — the ordinary condition of an install that has/// not updated yet. It is SKIPPED and COUNTED, never fatal: one such row used/// to take the whole of Home down with it, for a file that is otherwise fine.#[test]fn one_unreadable_memory_row_is_skipped_and_counted_rather_than_fatal() {    let (_dir, client) = workspace(|db| {        a_memory(db, "mem-a", "alpaca-a", "active", "2026-09-01T00:00:00.000Z");        // The CHECK is the one a later schema would have widened, so the test        // stands where that install stands: the row is in the file and this        // build has no word for its visibility.        db.run("PRAGMA ignore_check_constraints = ON", &[])            .expect("the checks step aside");        db.run(            "INSERT INTO cotton_memories (id, workspace_id, slug, title, body, status, \             visibility, origin_kind, created_at, updated_at) \             VALUES (?,?,?,?,?,'active','circle','user',?,?)",            &[                text("mem-future"),                text(fixture::WORKSPACE),                text("alpaca-future"),                text("A synthetic sentence from a later schema"),                text("Written by a build that knows one more visibility."),                text("2026-09-02T00:00:00.000Z"),                text("2026-09-02T00:00:00.000Z"),            ],        )        .expect("a row from a later schema");        db.run("PRAGMA ignore_check_constraints = OFF", &[])            .expect("the checks come back");    });    let home = home_of(&client);    assert_eq!(home["unreadableMemories"].as_u64(), Some(1));}// ── the row that opens a session, and the projects band's derived half ────/// A project whose only recent movement is a CONVERSATION with a linked person/// still moves. Until the derived half existed, a person linked to a project/// contributed nothing but their name — so the one thing a project is actually/// made of, talking to people, was the one thing that never moved it up.#[test]fn a_conversation_with_a_linked_person_moves_their_project() {    let (_dir, client) = workspace(|db| {        db.run(            "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, \             record_id, applied_by, created_at, updated_at, pinned, position) \             VALUES (?,?,?,'person',?,'user',?,?,0,1.0)",            &[                text("link-person"),                text(fixture::WORKSPACE),                text("project-a"),                text("person-a"),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),            ],        )        .expect("a person's project link");        db.run(            "INSERT INTO cotton_msg_contacts (id, workspace_id, person_id, display_name, \             created_at, updated_at) VALUES (?,?,?,?,?,?)",            &[                text("contact-a"),                text(fixture::WORKSPACE),                text("person-a"),                text("A synthetic contact"),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),            ],        )        .expect("a contact");        db.run(            "INSERT INTO cotton_msg_threads (id, workspace_id, kind, contact_id, archived, \             read_seq, created_at, updated_at) VALUES (?,?,'dm',?,0,0,?,?)",            &[                text("thread-dm"),                text(fixture::WORKSPACE),                text("contact-a"),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-07T00:00:00.000Z"),            ],        )        .expect("a dm thread");    });    let answer = home_of(&client);    let projects = answer["projects"].as_array().expect("an array");    // The fixture's own link on `note-a` is older; the conversation is what    // this project last did.    assert_eq!(projects[0]["slug"].as_str(), Some("alpaca-work"));    assert_eq!(        projects[0]["lastActivity"].as_str(),        Some("2026-09-07T00:00:00.000Z")    );}// ── the timeline's own window ─────────────────────────────────────────────/// The timeline asks `list_moods` for its whole ceiling. The tool's unasked/// page is a hundred rows over `at DESC`, so a busy fortnight would lose its/// OLDEST in-window rows and the run would simply stop early, with nothing/// saying the days below it exist.#[test]fn a_busy_fortnight_does_not_lose_its_oldest_days_to_the_tool_s_page() {    let (_dir, client) = workspace(|db| {        // The oldest in-window day first, so `at DESC` would cut exactly these.        for n in 0..4 {            a_mood(                db,                &format!("mood-old-{n}"),                "2026-08-26",                &format!("2026-08-26T0{n}:00:00.000Z"),                r#"["low"]"#,            );        }        for n in 0..100 {            a_mood(                db,                &format!("mood-today-{n}"),                "2026-09-08",                &format!("2026-09-08T09:00:{:02}.000Z", n % 60),                r#"["great"]"#,            );        }    });    let moments = mood_of(&client)["moments"]        .as_array()        .expect("moments")        .clone();    assert_eq!(moments.len(), 104);    assert_eq!(        moments[103]["localDay"].as_str(),        Some("2026-08-26"),        "the oldest in-window day is still there"    );}/// The bias feed's tie-break folds case, as `localeCompare` does — a byte/// order files "Ravi" above "aadhaar" for a capital letter, and at the/// hundred-term cap that decides MEMBERSHIP, not just order.#[test]fn the_bias_feed_s_tiebreak_does_not_let_a_capital_letter_decide_it() {    let (_dir, client) = workspace(|db| {        for (id, term) in [("vocab-r", "Ravindra"), ("vocab-a", "aadhaar")] {            db.run(                "INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, \                 created_at) VALUES (?,?,?,'auto',1,?)",                &[                    text(id),                    text(fixture::WORKSPACE),                    text(term),                    text("2026-09-01T00:00:00.000Z"),                ],            )            .expect("a vocabulary term");        }    });    let answer = super::take(&client, &Map::new()).expect("the mic answers");    assert_eq!(&answer["biasTerms"].as_array().unwrap()[..2], serde_json::json!(["aadhaar", "Ravindra"]).as_array().unwrap());}// ── 4k: Home's "Working on" row ───────────────────────────────────────────//// The figure and the task under it are `crate::phone::activity::working_on`'s —// the SAME function `/activity` draws its own header from — so what these cases// are about is that Home CARRIES it, in the shape the Swift decoder is written// for, and that the two screens cannot come to disagree about the same queue./// One assistant run. `finished_at` and `error` follow the state because the/// table's paired CHECKs refuse any other combination.fn seed_run(db: &Driver, id: &str, state: &str, task: &str, queued_at: &str) {    let finished = if state == "done" || state == "failed" {        text("2026-09-08T09:00:00.000Z")    } else {        SqlValue::Null    };    let error = if state == "failed" {        text("the model would not answer this one")    } else {        SqlValue::Null    };    db.run(        "INSERT INTO cotton_assistant_runs \           (id, workspace_id, source_kind, source_id, class, state, task, receipt, queued_at, \            finished_at, error) \         VALUES (?,?,'thought',?,'quick',?,?,?,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(&format!("source-{id}")),            text(state),            text(task),            text("Working on it · about ten minutes"),            text(queued_at),            finished,            error,        ],    )    .expect("a run");}#[test]fn nothing_in_flight_draws_a_zero_and_two_nulls_rather_than_no_row_at_all() {    // Never ABSENT: every other figure in this read is present-or-null and the    // Swift decoder is written for that. `count: 0` is what makes the row    // disappear on the screen; a missing key would be a decode failure.    let (_dir, client) = workspace(|_db| {});    assert_eq!(        home_of(&client)["workingOn"],        serde_json::json!({ "count": 0, "oldestTask": Value::Null, "oldestQueuedAt": Value::Null }),    );}#[test]fn the_row_names_the_oldest_run_in_flight_even_when_it_is_already_running() {    // The rule stated as a test: OLDEST BY `queued_at`, over `queued` AND    // `running` together — which is the order the worker actually serves the    // queue in. A `running` row queued earlier than a `queued` one therefore    // wins, and taking the oldest `queued` row alone would name the wrong one.    let (_dir, client) = workspace(|db| {        seed_run(db, "run-r", "running", "the oldest thing in flight", "2026-09-06T09:00:00.000Z");        seed_run(db, "run-q", "queued", "the newer one, still waiting", "2026-09-07T09:00:00.000Z");    });    assert_eq!(        home_of(&client)["workingOn"],        serde_json::json!({            "count": 2,            "oldestTask": "the oldest thing in flight",            "oldestQueuedAt": "2026-09-06T09:00:00.000Z",        }),    );}#[test]fn a_run_that_has_finished_is_in_flight_no_longer_whichever_way_it_ended() {    let (_dir, client) = workspace(|db| {        seed_run(db, "run-d", "done", "answered", "2026-09-01T09:00:00.000Z");        seed_run(db, "run-f", "failed", "gave up", "2026-09-02T09:00:00.000Z");        seed_run(db, "run-q", "queued", "the only one waiting", "2026-09-07T09:00:00.000Z");    });    let row = home_of(&client)["workingOn"].clone();    assert_eq!(row["count"], serde_json::json!(1));    assert_eq!(row["oldestTask"], serde_json::json!("the only one waiting"));}#[test]fn home_and_activity_answer_the_same_object_because_they_call_the_same_function() {    // Not "the same numbers" — the same VALUE, so a change to one is a change    // to both by construction rather than by two suites happening to agree.    let (_dir, client) = workspace(|db| {        seed_run(db, "run-q", "queued", "the one waiting", "2026-09-07T09:00:00.000Z");    });    let home = home_of(&client)["workingOn"].clone();    let activity = client        .with_writer(|replica| crate::phone::activity::activity(replica, &Map::new()))        .expect("activity answers")["working"]        .clone();    assert_eq!(home, activity);    assert_eq!(home["count"], serde_json::json!(1));}// ── Done for you ──────────────────────────────────────────────────────────fn a_filed_capture(db: &Driver, id: &str, routed_kind: Option<&str>, at: &str) {    db.run(        "INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, route_status, \         routed_kind, routed_id, created_at, updated_at) VALUES (?,?,?,?,'routed',?,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text("Buy alpaca feed on Friday."),            text(at),            routed_kind.map_or(SqlValue::Null, text),            routed_kind.map_or(SqlValue::Null, |_| text("todo-a")),            text(at),            text(at),        ],    )    .expect("a filed capture");}fn an_agents_memory(db: &Driver, id: &str, created_at: &str) {    db.run(        "INSERT INTO cotton_memories (id, workspace_id, slug, title, body, status, visibility, \         origin_kind, origin_label, created_at, updated_at) \         VALUES (?,?,?,?,'','active','private','agent','claude.ai',?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(id),            text("Alpacas are fed on Fridays."),            text(created_at),            text(created_at),        ],    )    .expect("an agent's memory");}/// What Cotton did by itself, newest first, each with its one action — and/// only what it did: a thought that stayed a thought and the owner's own/// memory entry are not on it.#[test]fn done_for_you_lists_filings_remembered_entries_and_unread_documents_newest_first() {    let (_dir, client) = workspace(|db| {        a_filed_capture(db, "capture-filed", Some("todo"), "2026-09-08T08:00:00.000Z");        a_filed_capture(db, "capture-stayed", None, "2026-09-08T08:30:00.000Z");        an_agents_memory(db, "memory-agent", "2026-09-07T09:00:00.000Z");        a_memory(db, "memory-owner", "owner-own", "active", "2026-09-08T09:30:00.000Z");        a_failed_document(db);    });    let answer = home_of(&client);    let rows = answer["doneForYou"].as_array().expect("doneForYou is a list");    let seen: Vec<(&str, &str, &str, &str)> = rows        .iter()        .map(|row| {            (                row["kind"].as_str().unwrap(),                row["id"].as_str().unwrap(),                row["label"].as_str().unwrap(),                row["action"].as_str().unwrap(),            )        })        .collect();    assert_eq!(        seen,        [            ("couldNotRead", "document-failed", "Could not read", "change"),            ("filed", "capture-filed", "Filed as a todo", "undo"),            ("remembered", "memory-agent", "Remembered", "undo"),        ],        "{answer}"    );    assert_eq!(rows[1]["text"], "Buy alpaca feed on Friday.");    assert_eq!(rows[1]["path"], "/thoughts/thought/capture-filed");    assert_eq!(rows[0]["text"], "synthetic.pdf");}fn a_filled_person(db: &Driver, id: &str, name: &str, city: Option<&str>, zone: &str, filled_at: &str) {    db.run(        "INSERT INTO cotton_people (id, workspace_id, full_name, city, timezone, city_filled_at, \         created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",        &[            text(id),            text(fixture::WORKSPACE),            text(name),            city.map_or(SqlValue::Null, text),            text(zone),            text(filled_at),            text(filled_at),            text(filled_at),        ],    )    .expect("a person whose city Cotton filled");}/// RULE: Done for you lists each pass of the city fill as ONE undoable row, naming only the people whose city is still the one their zone named — a city the owner changed or cleared since is his, not Cotton's.#[test]fn done_for_you_lists_a_city_fill_by_its_pass_and_only_the_cities_that_still_stand() {    const PASS: &str = "2026-09-08T07:00:00.000Z";    const LONE: &str = "2026-09-07T07:00:00.000Z";    let (_dir, client) = workspace(|db| {        a_filled_person(db, "person-oslo", "Maren Example", Some("Oslo"), "Europe/Oslo", PASS);        a_filled_person(db, "person-london", "Cassius Example", Some("London"), "Europe/London", PASS);        a_filled_person(db, "person-bath", "Wren Example", Some("Bath"), "Europe/London", PASS);        a_filled_person(db, "person-cleared", "Pia Example", None, "Europe/Berlin", PASS);        a_filled_person(db, "person-tokyo", "Tomas Example", Some("Tokyo"), "Asia/Tokyo", LONE);    });    let answer = home_of(&client);    let rows = answer["doneForYou"].as_array().expect("doneForYou is a list");    assert_eq!(rows.len(), 2, "{answer}");    assert_eq!(rows[0]["kind"], "cityFilled");    assert_eq!(rows[0]["id"], PASS);    assert_eq!(rows[0]["action"], "undo");    assert_eq!(rows[0]["label"], "Filled in 2 cities from their time zones");    assert_eq!(rows[0]["text"], "Cassius Example — London, Maren Example — Oslo");    assert_eq!(rows[0]["path"], "/people");    assert_eq!(rows[1]["id"], LONE);    assert_eq!(rows[1]["label"], "Filled in a city from the time zone");    assert_eq!(rows[1]["path"], "/people/person/person-tokyo");}fn a_decided_sender(db: &Driver, address: &str, by: &str, verdict: &str, at: &str) {    db.run(        "INSERT INTO cotton_email_senders (id, workspace_id, address, kind, created_at, updated_at, \         decided_by, verdict, reason, decided_at) VALUES (?,?,?,?,?,?,?,?,?,?)",        &[            text(&format!("sender-{address}")),            text(fixture::WORKSPACE),            text(address),            text(if verdict == "junk" { "junk" } else { "service" }),            text(at),            text(at),            text(by),            text(verdict),            text("junk: an invented newsletter"),            text(at),        ],    )    .expect("a decided sender");}/// RULE: Done for you shows the junk classifier as ONE row a day — how many senders it filed into Junk that day and still stands behind, opening Mail; a sender the owner kept since, or one it called a service, is not counted.#[test]fn done_for_you_lists_a_day_of_the_junk_classifier_as_one_row() {    let (_dir, client) = workspace(|db| {        a_decided_sender(db, "letters@one.example.invalid", "assistant", "junk", "2026-09-08T06:00:00.000Z");        a_decided_sender(db, "offers@two.example.invalid", "assistant", "junk", "2026-09-08T07:00:00.000Z");        a_decided_sender(db, "deals@three.example.invalid", "assistant", "junk", "2026-09-08T08:00:00.000Z");        a_decided_sender(db, "kept@four.example.invalid", "owner", "junk", "2026-09-08T08:30:00.000Z");        a_decided_sender(db, "tool@five.example.invalid", "assistant", "service", "2026-09-08T08:40:00.000Z");        a_decided_sender(db, "digest@six.example.invalid", "assistant", "junk", "2026-09-07T08:00:00.000Z");    });    let answer = home_of(&client);    let rows = answer["doneForYou"].as_array().expect("doneForYou is a list");    assert_eq!(rows.len(), 2, "{answer}");    assert_eq!(rows[0]["kind"], "junkFiled");    assert_eq!(rows[0]["id"], "2026-09-08");    assert_eq!(rows[0]["action"], "change");    assert_eq!(rows[0]["label"], "Filed 3 senders into Junk");    assert_eq!(rows[0]["text"], "deals@three.example.invalid, offers@two.example.invalid and 1 more");    assert_eq!(rows[0]["path"], "/email");    assert_eq!(rows[1]["label"], "Filed a sender into Junk");    assert_eq!(rows[1]["text"], "digest@six.example.invalid");}#[test]fn done_for_you_is_an_empty_list_on_a_quiet_file() {    let (_dir, client) = workspace(|_| {});    let answer = home_of(&client);    assert_eq!(answer["doneForYou"], serde_json::json!([]));}// RULE (owner's ruling, 12 Oct 2026; owner, 17 Oct 2026): a tile with nothing to show is drawn faint IN ITS ALPHABETICAL PLACE — never moved after the full ones — and gains its colour there on its first record; what it holds is asked of the tables its tool names, over a real file.#[test]fn an_empty_tile_draws_faint_in_its_place_and_gains_colour_on_its_first_record() {    let (_dir, client) = kit_workspace(|db| {        db.run("DELETE FROM cotton_notes", &[]).expect("no notes and no journal pages");        an_arrangement(            db,            "[]",            r#"["todos","notebook"]"#,            r#"["tool/todos","tool/notebook"]"#,        );    });    let ours = |tiles: Vec<(String, bool)>| -> Vec<(String, bool)> {        tiles.into_iter().filter(|(id, _)| ["tool/notebook", "tool/todos"].contains(&id.as_str())).collect()    };    let before = tiles(&home_of(&client));    let drawn: Vec<&str> = before.iter().map(|(id, _)| id.as_str()).collect();    assert_eq!(drawn, by_name(&drawn), "alphabetical, the empty tiles in their places: {before:?}");    let order = by_name(&["tool/notebook", "tool/todos"]);    let expected: Vec<(String, bool)> = order.iter().map(|id| (id.clone(), id == "tool/notebook")).collect();    assert_eq!(ours(before.clone()), expected, "the notebook holds nothing yet");    client        .with_writer(|file| {            file.driver                .run(                    "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \                     VALUES ('note-first', ?, 'note', 'A synthetic note', 'Synthetic.', ?, ?)",                    &[text(fixture::WORKSPACE), text(NOW), text(NOW)],                )                .map_err(|error| error.to_string())?;            cotton_tools::test_fixtures::reconcile(file.driver, "cotton_notes");            Ok(())        })        .unwrap();    let after = tiles(&home_of(&client));    let expected: Vec<(String, bool)> = order.iter().map(|id| (id.clone(), false)).collect();    assert_eq!(ours(after.clone()), expected, "the note's first record gave its tile colour, where it stood");    let ids = |tiles: &[(String, bool)]| tiles.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>();    assert_eq!(ids(&after), ids(&before), "a first record moves nothing");}/// RULE: every kit tool's records are asked of tables the file really has — `holds_records` runs for each kit tool against a real file, so a renamed table fails here, never as a tile that is faint forever.#[test]fn every_tool_records_query_runs_against_a_real_file() {    let (_dir, client) = kit_workspace(|_| {});    client        .with_file(|file| {            for key in cotton_core::kit::ids() {                cotton_tools::home_arrangement::holds_records(file.driver, file.workspace_id, key)                    .map_err(|error| format!("{key}: {error}"))?;            }            Ok(())        })        .unwrap();}/// RULE: Home and keep-fetch stay under 50 ms on a generated huge household; a glance must not walk the person's history or the media catalogue.#[test]#[ignore = "million-row read guard; run explicitly with --release --ignored"]fn glances_on_a_generated_huge_household() {    let (_dir, client) = workspace(|_| {});    client.with_writer(|f| {        let db = f.driver;        // Match an opened writer before bulk imports; the measured read must        // never prepare derivation or silently omit an unprepared forecast.        cotton_tools::derive::ensure_current(db).map_err(|e| e.to_string())?;        db.run("INSERT OR IGNORE INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) VALUES ('cal-proof', ?, 'calendar', 'Synthetic', 1, '2026-01-01T00:00:00Z')", &[text(fixture::WORKSPACE)]).unwrap();        fixture::this_devices_row(db);        let plan = cotton_tools::synthetic::Plan::named("huge").unwrap();        // Bulk history for a read guard: exercising the normal import writers        // here measures their per-record derived work, not the reads. The        // shipped generator's huge cardinalities are retained for Home's        // tables, with a million-message archive alongside them.        for (sql, count) in [            ("INSERT INTO cotton_people (id,workspace_id,full_name,created_at,updated_at) SELECT 'huge-person-'||i,?1,'Synthetic person','2026-01-01','2026-01-01' FROM n", plan.people),            ("INSERT INTO cotton_locations (id,workspace_id,name,created_at,updated_at) SELECT 'huge-place-'||i,?1,'Synthetic place','2026-01-01','2026-01-01' FROM n", plan.locations),            ("INSERT INTO cotton_memory_projects (id,workspace_id,slug,name,created_at,updated_at) SELECT 'huge-project-'||i,?1,'huge-project-'||i,'Synthetic project','2026-01-01','2026-01-01' FROM n", plan.projects),            ("INSERT INTO cotton_memories (id,workspace_id,slug,title,body,origin_kind,created_at,updated_at) SELECT 'huge-memory-'||i,?1,'huge-memory-'||i,'Synthetic memory',printf('%02000d',i),'user','2026-01-01','2026-01-01' FROM n", plan.memories),            ("INSERT INTO cotton_money_accounts (id,workspace_id,kind,subtype,name,currency,created_at,updated_at) SELECT 'huge-account-'||i,?1,'asset','bank','Synthetic bank','INR','2026-01-01','2026-01-01' FROM n", plan.accounts),            ("INSERT INTO cotton_money_transactions (id,workspace_id,account_id,occurred_on,for_period,description,amount_minor,direction,currency,status,created_at,updated_at) SELECT 'huge-money-'||i,?1,'huge-account-'||(1+(i-1)%8),date('2023-10-01','+'||(i%1096)||' days'),strftime('%Y-%m','2023-10-01','+'||(i%1096)||' days'),'Synthetic payment',100,CASE WHEN i%2=0 THEN 'in' ELSE 'out' END,'INR',CASE WHEN i%20=0 THEN 'expected' ELSE 'actual' END,'2026-01-01','2026-01-01' FROM n", plan.transactions),            ("INSERT INTO cotton_email_threads (id,workspace_id,external_key,subject,email_count,created_at,updated_at) SELECT 'huge-mail-thread-'||i,?1,'huge-mail-thread-'||i,'Synthetic correspondence',3,'2026-01-01','2026-01-01' FROM n", plan.emails.div_ceil(3)),            ("INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,body,created_at) SELECT 'huge-mail-'||i,?1,'huge-mail-thread-'||(1+(i-1)/3),'huge-mail-'||i,'synthetic@example.invalid','2026-01-01',printf('%02000d',i),'2026-01-01' FROM n", plan.emails),            ("INSERT INTO cotton_todos (id,workspace_id,title,status,created_at,updated_at) SELECT 'huge-todo-'||i,?1,'Synthetic task',CASE WHEN i%4=0 THEN 'open' ELSE 'done' END,'2026-01-01','2026-01-01' FROM n", plan.todos),            ("INSERT INTO cotton_notes (id,workspace_id,title,body,kind,created_at,updated_at) SELECT 'huge-note-'||i,?1,'Synthetic note',printf('%02000d',i),'note','2026-01-01','2026-01-01' FROM n", plan.notes),            ("INSERT INTO cotton_events (id,collection_id,title,starts_at,ends_at,created_at,updated_at) SELECT 'huge-event-'||i,'cal-proof','Synthetic event',strftime('%Y-%m-%dT%H:%M:%fZ','2023-10-01','+'||(i%1096)||' days'),strftime('%Y-%m-%dT%H:%M:%fZ','2023-10-01','+'||(i%1096)||' days','+1 hour'),'2026-01-01','2026-01-01' FROM n", plan.events),            ("INSERT INTO cotton_msg_threads (id,workspace_id,kind,title,read_seq,last_message_at,created_at,updated_at) SELECT 'huge-chat-'||i,?1,'group','Synthetic chat',10000,'2026-10-01T00:00:00Z','2026-01-01','2026-01-01' FROM n", plan.message_threads),            ("INSERT INTO cotton_msg_messages (id,workspace_id,thread_id,direction,channel,origin,seq,sent_at,body,created_at) SELECT 'huge-message-'||i,?1,'huge-chat-'||(1+(i-1)%2000),'in','cotton','imported',i,'2026-01-01T00:00:00Z','Synthetic line','2026-01-01' FROM n", plan.messages*4),            ("INSERT INTO cotton_photos (id,workspace_id,key,sha256,content_type,size_bytes,taken_at,created_at,updated_at) SELECT 'photo:'||printf('%064x',i),?1,?1||'/photos/'||printf('%064x',i)||'.jpg',printf('%064x',i),'image/jpeg',4000000,'2026-01-01','2026-01-01','2026-01-01' FROM n", plan.photos),            ("INSERT OR IGNORE INTO cotton_notes (id,workspace_id,title,body,kind,journal_date,created_at,updated_at) SELECT 'huge-journal-'||i,?1,'Synthetic journal',printf('%02000d',i),'journal',date('2023-10-01','+'||i||' days'),'2026-01-01','2026-01-01' FROM n", plan.journal_days),        ] {            let sql = format!("WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<?2) {sql}");            db.run(&sql, &[text(fixture::WORKSPACE), SqlValue::Integer(count as i64)]).unwrap();        }        // Keep physical cached values as an older writer may have left them;        // the recurrence reader must derive its own bounded occurrences.        db.run("UPDATE cotton_money_transactions SET due_date=occurred_on WHERE workspace_id=? AND status='expected'",            &[text(fixture::WORKSPACE)]).unwrap();        db.run("INSERT INTO _computed (table_id,record_id,key,value)            SELECT 'ahead',id,'balance_after',                (SELECT COALESCE(SUM(CASE WHEN direction='in' THEN amount_minor ELSE -amount_minor END),0)                 FROM cotton_money_transactions WHERE workspace_id=?1 AND status='actual')                + SUM(CASE WHEN direction='in' THEN amount_minor ELSE -amount_minor END)                  OVER (ORDER BY due_date,id ROWS UNBOUNDED PRECEDING)            FROM cotton_money_transactions WHERE workspace_id=?1 AND status='expected'",            &[text(fixture::WORKSPACE)]).unwrap();        // The recurrence reader starts from the evaluator's stored opening.        // Bulk synthetic inserts bypass that writer, so supply its opening        // and currency as well as the per-record values above. A missing        // opening must not turn the measured balance into a silent figure.        db.run("INSERT OR REPLACE INTO _computed (table_id,record_id,key,value)            SELECT 'ahead','@opening','balance_after',                COALESCE(SUM(CASE WHEN direction='in' THEN amount_minor ELSE -amount_minor END),0)            FROM cotton_money_transactions WHERE workspace_id=? AND status='actual'", &[text(fixture::WORKSPACE)]).unwrap();        db.exec("INSERT OR REPLACE INTO _computed (table_id,record_id,key,value)            VALUES ('ahead','@opening','balance_after@currency','INR')").unwrap();        Ok(())    }).unwrap();    if std::env::var_os("COTTON_READ_PROOF").is_some() {        // A review copy is generated here, never read from a person's files.        let root = std::path::PathBuf::from(std::env::var_os("HOME").unwrap())            .join("cotton-captures/readsperf").join(format!("household-{}", std::process::id()));        let layout = cotton_client::layout::Layout::new(&root);        let target = layout.replica(fixture::WORKSPACE);        std::fs::create_dir_all(target.parent().unwrap()).unwrap();        client.with_writer(|file| file.driver.checkpoint_truncate().map_err(|e|e.to_string())).unwrap();        std::fs::copy(client.layout().replica(fixture::WORKSPACE), target).unwrap();        std::fs::copy(client.layout().connection_json(), layout.connection_json()).unwrap();        println!("generated read proof: {}", root.display());    }    client.set_self_device_id(Some(fixture::SELF_DEVICE_ID.into()));    let began = std::time::Instant::now();    let keep_fetch = super::read_for("read.keepFetch").unwrap();    crate::phone::answer_read(&client, keep_fetch, &Map::new()).unwrap();    let took = began.elapsed();    println!("keep-fetch: {took:?}");    assert!(took < std::time::Duration::from_millis(50));    let inside_before = crate::shell::client::on_short_lane(crate::shell::client::ShortRead::Home, || {        client.with_file(|file| {            file.driver.watch_statements();            Ok(file.driver.time_inside())        })    }).unwrap();    let home = super::read_for("read.home").unwrap();    let began = std::time::Instant::now();    let answer = crate::phone::answer_read(&client, home, &Map::new());    let took = began.elapsed();    crate::shell::client::on_short_lane(crate::shell::client::ShortRead::Home, || {        client.with_file(|file| {            println!("Home inside SQLite: {:?}", file.driver.time_inside().saturating_sub(inside_before));            for (took, sql) in file.driver.times_by_statement().into_iter().take(10) {                println!("{took:?} SQL: {sql}");            }            for (steps, sql) in file.driver.steps_by_statement().into_iter().take(15) {                println!("{steps} steps: {sql}");            }            Ok(())        })    }).unwrap();    let answer = answer.unwrap();    let counts = answer["counts"].as_object().expect("Home answers its figures");    println!("Home: {took:?}; {} counts", counts.len());    let ahead = cotton_core::definitions::builtin_table_definitions().iter()        .find(|table| table.id == "ahead").unwrap();    let lowest = ahead.tool.as_ref().unwrap().figures.iter()        .find(|figure| figure.summary.as_ref().is_some_and(|summary|            summary.op == cotton_core::definitions::SummaryOp::Min)).unwrap();    assert!(counts.get(&lowest.read).and_then(Value::as_str).is_some(),        "Home must answer the nonzero future balance, not skip its evaluator: {counts:?}");    assert!(took < std::time::Duration::from_millis(50), "Home took {took:?}");}/// RULE: Home reads today's journal by day by its index; a glance never decodes the note bodies it does not show.#[test]fn home_uses_the_journal_day_index() {    let (_dir, client) = workspace(|_| {});    client.with_file(|f| {        for (sql, params, index) in [            (super::HOME_JOURNAL, vec![text(f.workspace_id), text("2026-09-08")], "uq_cotton_notes_journal_day"),        ] {            let plan: Vec<String> = f.driver.all(&format!("EXPLAIN QUERY PLAN {sql}"), &params).map_err(|e|e.to_string())?                .iter().map(|row|row.text("detail").unwrap_or_default().into()).collect();            assert!(plan.iter().any(|line|line.contains(index)), "{plan:#?}");        }        Ok(())    }).unwrap();}/// RULE: Home seeks its filtered counts and calendar slices even on fresh copies without planner statistics; a glance must not visit note bodies, closed todos or historical events it does not show.#[test]fn home_uses_filtered_counts_and_calendar_seeks_without_statistics() {    let (_dir, client) = workspace(|_| {});    client.with_file(|f| {        for (sql, params, indexes) in [            (super::HOME_NOTES, vec![text(f.workspace_id)], vec!["idx_cotton_notes_home"]),            (super::HOME_TODOS, vec![text(f.workspace_id)], vec!["idx_cotton_todos_open"]),            (super::home_events_sql(), vec![text("2026-09-08"), text("2026-09-15")], vec!["idx_cotton_events_range", "idx_cotton_events_invites"]),        ] {            let plan: Vec<String> = f.driver.all(&format!("EXPLAIN QUERY PLAN {sql}"), &params).map_err(|e| e.to_string())?                .iter().map(|row| row.text("detail").unwrap_or_default().into()).collect();            for index in indexes {                assert!(plan.iter().any(|line| line.contains("SEARCH") && line.contains(index)), "{plan:#?}");            }        }        Ok(())    }).unwrap();}