Cotton code
1192 lines · 72.7 KB · RustRaw
//! Cotton Notes on a phone that started its own database and never signed//! in: every `notes.*` method answers here, old-shaped rows read with no//! migration, a note written the way an assistant writes it over MCP reads//! right here and the reverse. Every note is invented.use serde_json::{json, Map, Value};use super::*;use crate::handle::{CottonHandle, OpenConfig, OpenMode};use crate::methods::dispatch;fn notes_manifest() -> Value {    json!({        "genesis": "personal",        "flavour": "notes",        "name": "Cotton Notes",        "databases": "single",        "database": "personal",        "business": { "server": { "real": "https://cottondb.com", "dev": "https://dev.example.invalid" } },        "fan": { "home": false, "tools": false, "opens": "notebook" },        "kit": "notes",        "ground": "blank"    })}fn phone(dir: &tempfile::TempDir) -> CottonHandle {    let handle = CottonHandle::open(OpenConfig {        mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().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(notes_manifest()),    })    .expect("an open core");    dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone");    handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}fn rows(answer: &Value) -> Vec<Value> {    answer["rows"].as_array().cloned().unwrap_or_default()}fn ids(answer: &Value) -> Vec<String> {    rows(answer).iter().map(|row| row["id"].as_str().unwrap().to_string()).collect()}fn cards(handle: &CottonHandle) -> Vec<Value> {    ask(handle, "notes.fan", json!({}))["cards"].as_array().cloned().unwrap()}fn card<'a>(cards: &'a [Value], id: &str) -> &'a Value {    cards.iter().find(|card| card["id"] == id).unwrap_or_else(|| panic!("no card {id} in {cards:?}"))}/// A note written as a phone writes it: made, then its text saved.fn write(handle: &CottonHandle, text: &str) -> String {    let made = ask(handle, "notes.new", json!({}));    let id = made["id"].as_str().unwrap().to_string();    ask(handle, "notes.edit", json!({ "id": id, "text": text }));    id}/// The note's row as the store holds it (what an assistant reads over MCP).fn stored(handle: &CottonHandle, id: &str) -> Map<String, Value> {    let query = cotton_tools::mcp::read_db::Query::on("cotton_notes").columns(&["id", "title", "body", "archived_at", "trashed_at"]).eq("id", id.to_string());    let found = super::with_read(handle, "test", |ctx| Ok(json!(cotton_tools::mcp::handlers::common::rows(ctx, &query).unwrap()))).unwrap();    found.as_array().and_then(|rows| rows.first()).and_then(Value::as_object).cloned().unwrap_or_default()}/// An old note's row, as the old deck and the Mac wrote them: a title kept/// apart, a plain body, no `updated_at`, its pins and project columns.fn old_note(handle: &CottonHandle, title: Option<&str>, body: &str) -> String {    let id = format!("{:032x}", rand_id());    super::with_write(handle, "test", |ctx| {        let mut row = Map::new();        row.insert("kind".into(), json!("note"));        row.insert("title".into(), json!(title));        row.insert("body".into(), json!(body));        row.insert("pinned".into(), json!(true));        row.insert("author_kind".into(), json!("user"));        cotton_tools::mcp::handlers::common::insert_row(ctx, "cotton_notes", &id, row).unwrap();        ctx.commit().unwrap();        Ok(Value::Null)    })    .unwrap();    id}fn rand_id() -> u128 {    use std::sync::atomic::{AtomicU64, Ordering};    static NEXT: AtomicU64 = AtomicU64::new(1);    0xA11CE_0000_0000_0000_0000_0000_0000u128 + NEXT.fetch_add(1, Ordering::SeqCst) as u128}/// A synthetic picture kept as a photo record; answers its id.fn photo(handle: &CottonHandle, dir: &std::path::Path, n: usize) -> String {    let path = dir.join(format!("picture-{n}.jpg"));    std::fs::write(&path, format!("synthetic picture {n}")).unwrap();    super::keep_picture(handle, &path.to_string_lossy(), "image/jpeg", Some("picture.jpg")).expect("the picture is kept")}fn attach(handle: &CottonHandle, note: &str, photo: &str, position: f64) {    super::with_write(handle, "test", |ctx| {        let mut row = Map::new();        row.insert("note_id".into(), json!(note));        row.insert("record_kind".into(), json!("photo"));        row.insert("record_id".into(), json!(photo));        row.insert("position".into(), json!(position));        let id = format!("{:032x}", rand_id());        cotton_tools::mcp::handlers::common::insert_row(ctx, cotton_tools::mcp::handlers::records_1::notes::ATTACHMENTS, &id, row).unwrap();        ctx.commit().unwrap();        Ok(Value::Null)    })    .unwrap();}/// RULE (owner, 19 Nov 2026): a note is one Markdown text; its first line, a/// heading, is its title; the list is newest edit first, each row its title,/// its preview (two lines under a title, three without) and its date; the/// title column is kept in step for every other reader.#[test]fn a_note_is_written_listed_and_kept_in_step() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let empty = ask(&handle, "notes.list", json!({}));    assert_eq!(empty["count"], 0);    assert_eq!(empty["empty"], "No notes yet. Tap the round button to write one.");    let first = write(&handle, "# Groceries\n\n- milk\n- [ ] eggs\n- bread");    let second = write(&handle, "Call the plumber about the tap");    let listed = ask(&handle, "notes.list", json!({}));    assert_eq!(ids(&listed), vec![second.clone(), first.clone()], "newest edit first");    let groceries = &rows(&listed)[1];    assert_eq!(groceries["title"], "Groceries");    assert_eq!(groceries["preview"], "milk\neggs");    assert_eq!(groceries["preview_lines"], 2);    assert!(!groceries["date"].as_str().unwrap().is_empty());    // RULE (owner, 21 Nov 2026): a note with no title is titled in the list by its first line, as a titled note is.    assert_eq!(rows(&listed)[0]["title"], "Call the plumber about the tap");    assert_eq!(rows(&listed)[0]["preview"], "");    assert_eq!(rows(&listed)[0]["preview_lines"], 2);    assert_eq!(listed["count_words"], "2 notes");    // An edit brings a note to the top; the column stays in step.    ask(&handle, "notes.edit", json!({ "id": first, "replace": { "start": 2, "end": 11, "with": "Shopping" } }));    let listed = ask(&handle, "notes.list", json!({}));    assert_eq!(ids(&listed)[0], first);    let row = stored(&handle, &first);    assert_eq!(row["title"], "Shopping");    assert!(row["body"].as_str().unwrap().starts_with("# Shopping\n"));    let opened = ask(&handle, "notes.open", json!({ "id": first, "cursor": 0 }));    assert_eq!(opened["title"], "Shopping");    assert!(opened["blocks"].as_array().unwrap().iter().any(|b| b["kind"] == "check"));    assert!(opened["spans"].as_array().unwrap().iter().any(|s| s["style"] == "title"));    // A compose tapped and left leaves nothing behind.    let blank = ask(&handle, "notes.new", json!({}))["id"].as_str().unwrap().to_string();    assert_eq!(ask(&handle, "notes.leave", json!({ "id": blank }))["left"], "removed");    assert_eq!(ask(&handle, "notes.list", json!({}))["count"], 2);    assert_eq!(ask(&handle, "notes.leave", json!({ "id": first }))["left"], "kept");    // RULE (owner, 21 Nov 2026): the first line titles an untitled note in the list, the rest previews.    let lines = write(&handle, "Pick up the parcel\nfrom the post office\nbefore six");    let listed = ask(&handle, "notes.list", json!({}));    let row = rows(&listed).into_iter().find(|r| r["id"] == json!(lines)).expect("the row");    assert_eq!((row["title"].as_str(), row["preview"].as_str()), (Some("Pick up the parcel"), Some("from the post office\nbefore six")), "the first line titles it, the rest previews");    assert!(stored(&handle, &lines).get("title").and_then(Value::as_str).unwrap_or_default().is_empty(), "the note itself still has no title");}/// RULE (owner, 19 Nov 2026): a hashtag files its note into the group of/// that name; `#a/b` nests under `a`; removing the last hashtag for a group/// takes the note out, and a group only hashtags made, left empty, goes. A/// list made by hand is never touched.#[test]fn hashtags_file_notes_and_their_groups_come_and_go() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let a = write(&handle, "Seeds to order #home/garden and #work");    let b = write(&handle, "Standup at ten #Work");    let c = write(&handle, "Nothing tagged here");    // A list made by hand of note c stays as it is through all of this.    super::with_write(&handle, "test", |ctx| {        let args = json!({ "table": "note", "name": "Errands", "records": [c] }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::tables::groups::create_group(ctx, &args).unwrap())    })    .unwrap();    let hand_made = || {        super::with_read(&handle, "test", |ctx| {            let live = cotton_tools::mcp::handlers::tables::groups::live_groups(ctx.read.driver(), Some(ctx.workspace_id)).unwrap();            Ok(json!(live.iter().filter(|(_, d)| cotton_tools::mcp::handlers::tables::groups::name_of(d) == "Errands").map(|(_, d)| cotton_tools::mcp::handlers::tables::groups::members_of(d)).collect::<Vec<_>>()))        })        .unwrap()    };    let fan = cards(&handle);    let labels: Vec<&str> = fan.iter().map(|card| card["label"].as_str().unwrap()).collect();    assert_eq!(labels[..4], ["Notes", "Untagged", "Archive", "Bin"]);    assert_eq!(card(&fan, "notes:all")["count"], 3);    assert_eq!(card(&fan, "notes:untagged")["count"], 1);    // Most used first; the nested tag folds under its parent.    let tags: Vec<(&str, u64)> = fan[4..].iter().map(|card| (card["tag"].as_str().unwrap(), card["depth"].as_u64().unwrap())).collect();    assert_eq!(tags, vec![("work", 0), ("home", 0), ("home/garden", 1)]);    assert_eq!(card(&fan, "notes:tag:work")["count"], 2);    assert_eq!(card(&fan, "notes:tag:home/garden")["parent"], "home");    assert_eq!(card(&fan, "notes:tag:home/garden")["label"], "garden");    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "home" }))), vec![a.clone()]);    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "untagged" }))), vec![c.clone()]);    // The last #work goes from b: b leaves the group; the group stays for a.    let edited = ask(&handle, "notes.edit", json!({ "id": b, "text": "Standup at ten" }));    assert_eq!(edited["unfiled"], json!(["work"]));    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "work" }))), vec![a.clone()]);    // a drops its tags: both its groups go.    ask(&handle, "notes.edit", json!({ "id": a, "text": "Seeds to order" }));    let fan = cards(&handle);    assert_eq!(fan.len(), 4, "{fan:?}");    let groups = super::with_read(&handle, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.len()))).unwrap();    assert_eq!(groups, 0);    assert_eq!(hand_made(), json!([[c]]), "a list made by hand is left as it is");    // The bar's Tag adds the hashtag on a line of its own and files it.    let tagged = ask(&handle, "notes.tag", json!({ "id": c, "tag": "two words" }));    assert!(tagged["text"].as_str().unwrap().ends_with("\n\n#two words#"));    assert_eq!(tagged["filed"], json!(["two words"]));    assert_eq!(ask(&handle, "notes.tags", json!({}))["tags"][0]["tag"], "two words");    // The tag picker takes it off again: its line goes, and it is unfiled.    let untagged = ask(&handle, "notes.untag", json!({ "id": c, "tag": "two words" }));    assert!(!untagged["text"].as_str().unwrap().contains('#'), "{untagged}");    assert_eq!(untagged["unfiled"], json!(["two words"]));}/// RULE (owner, 19 Nov 2026): old notes read correctly with no migration: a/// stored title over a plain body is the note's title, the old deck's columns/// change nothing, attached pictures draw after the text in their old order,/// and the first edit writes them into the body, none lost or doubled.#[test]fn old_shaped_notes_read_with_no_migration() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let plain = old_note(&handle, Some("Packing"), "socks\ncharger");    let titled_twice = old_note(&handle, Some("Ideas"), "Ideas\nfirst one");    let untitled = old_note(&handle, None, "just words");    let pictured = old_note(&handle, Some("Trip"), "the view");    let one = photo(&handle, dir.path(), 1);    let two = photo(&handle, dir.path(), 2);    attach(&handle, &pictured, &two, 2.0);    attach(&handle, &pictured, &one, 1.0);    let listed = ask(&handle, "notes.list", json!({}));    let titled: Vec<(String, Value)> = rows(&listed).iter().map(|r| (r["id"].as_str().unwrap().to_string(), r["title"].clone())).collect();    assert!(titled.contains(&(plain.clone(), json!("Packing"))));    assert!(titled.contains(&(titled_twice.clone(), json!("Ideas"))));    assert!(titled.contains(&(untitled.clone(), json!("just words"))), "an untitled note is titled in the list by its first line");    let packing = rows(&listed).into_iter().find(|r| r["id"] == plain).unwrap();    assert_eq!(packing["preview"], "socks\ncharger");    let ideas = ask(&handle, "notes.open", json!({ "id": titled_twice }));    assert_eq!(ideas["text"], "# Ideas\nfirst one");    // Nothing was written by reading.    assert_eq!(stored(&handle, &plain)["body"], "socks\ncharger");    let opened = ask(&handle, "notes.open", json!({ "id": pictured }));    let text = opened["text"].as_str().unwrap().to_string();    assert_eq!(text, format!("# Trip\n\nthe view\n\n![]({one})\n\n![]({two})\n"));    assert!(opened["pictures"][&one]["key"].is_string(), "{}", opened["pictures"]);    // The first edit writes them in; opened again, each is there once.    ask(&handle, "notes.edit", json!({ "id": pictured, "text": text.replace("the view", "the view from the top") }));    assert_eq!(stored(&handle, &pictured)["body"], format!("# Trip\n\nthe view from the top\n\n![]({one})\n\n![]({two})\n"));    let again = ask(&handle, "notes.open", json!({ "id": pictured }))["text"].as_str().unwrap().to_string();    assert_eq!(again.matches(&one).count(), 1);    assert_eq!(again.matches(&two).count(), 1);    assert_eq!(stored(&handle, &pictured)["title"], "Trip");}/// RULE (owner, 19 Nov 2026): a note written or edited the way an assistant/// does over MCP (`create_note` / `update_note`: title and body apart) shows/// right in Notes — title, preview, hashtags filing it, pictures, tables —/// and a note written in Notes reads right to an assistant.#[test]fn notes_and_mcp_read_each_other() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let picture = photo(&handle, dir.path(), 7);    let body = format!("Plan for the week #plans/week\n\n| Day | Swim |\n| --- | --- |\n| Mon | yes |\n\n![]({picture})");    let made = super::with_write(&handle, "mcp", |ctx| {        let args = json!({ "title": "Week", "body": body }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::records_1::notes::create_note(ctx, &args).unwrap())    })    .unwrap();    let id = made["id"].as_str().unwrap().to_string();    let listed = ask(&handle, "notes.list", json!({}));    let row = rows(&listed).into_iter().find(|r| r["id"] == id).unwrap();    assert_eq!(row["title"], "Week");    assert_eq!(row["preview"], "Plan for the week plans/week\nDay · Swim");    assert_eq!(row["picture"], picture);    assert_eq!(row["tags"], json!(["plans/week"]));    // Filed by the list's look, though Notes never saw the write.    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "plans" }))), vec![id.clone()]);    let opened = ask(&handle, "notes.open", json!({ "id": id }));    assert_eq!(opened["tables"][0]["rows"][1][0]["text"], "Mon");    assert!(opened["pictures"][&picture]["key"].is_string());    // An assistant's edit drops the hashtag: Notes takes it out of the group.    super::with_write(&handle, "mcp", |ctx| {        let args = json!({ "id": id, "body": "Plan for the week" }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::records_1::notes::update_note(ctx, &args).unwrap())    })    .unwrap();    assert_eq!(cards(&handle).len(), 4);    // The reverse: what Notes writes, an assistant reads as title and body.    let mine = write(&handle, "# From the phone\n\nwords #here");    let row = stored(&handle, &mine);    assert_eq!(row["title"], "From the phone");    assert_eq!(row["body"], "# From the phone\n\nwords #here");    let hit = super::with_write(&handle, "mcp", |ctx| {        let args = json!({ "query": "phone", "kinds": ["note"] }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::records_2::search::search_records(ctx, &args).unwrap())    })    .unwrap();    assert!(hit["records"].as_array().unwrap().iter().any(|r| r["id"] == mine), "{hit}");}/// RULE: Archive and Bin are the store's own; a binned note is filed under/// no tag, comes back filed, and goes for good from the bin.#[test]fn archive_bin_restore_and_remove() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let a = write(&handle, "keep me #x");    let b = write(&handle, "bin me #x");    let c = write(&handle, "bin me too");    assert_eq!(ask(&handle, "notes.archive", json!({ "id": a }))["archived"], true);    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "archive" }))), vec![a.clone()]);    assert_eq!(ask(&handle, "notes.bin", json!({ "id": b }))["binned"], true);    ask(&handle, "notes.bin", json!({ "id": c }));    let fan = cards(&handle);    assert_eq!(card(&fan, "notes:all")["count"], 0);    assert_eq!(card(&fan, "notes:archive")["count"], 1);    assert_eq!(card(&fan, "notes:bin")["count"], 2);    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "x" }))), Vec::<String>::new());    ask(&handle, "notes.restore", json!({ "id": b }));    ask(&handle, "notes.unarchive", json!({ "id": a }));    let tagged = ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "x" })));    assert_eq!(tagged.len(), 2);    assert!(ask(&handle, "notes.empty_bin", json!({}))["ask"].is_object());    assert_eq!(ask(&handle, "notes.empty_bin", json!({ "confirmed": true }))["removed"], 1);    assert!(stored(&handle, &c).is_empty());    ask(&handle, "notes.bin", json!({ "id": b }));    ask(&handle, "notes.remove", json!({ "id": b, "confirmed": true }));    assert_eq!(ask(&handle, "notes.list", json!({ "view": "bin" }))["count"], 0);    assert_eq!(ask(&handle, "notes.list", json!({}))["count"], 1);}#[test]fn search_finds_words_in_this_copy() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let a = write(&handle, "# Recipes\nlemon cake");    write(&handle, "bus times");    let old = old_note(&handle, Some("Lemon trees"), "water weekly");    let found = ids(&ask(&handle, "notes.list", json!({ "search": "lemon" })));    assert!(found.contains(&a) && found.contains(&old) && found.len() == 2, "{found:?}");    let none = ask(&handle, "notes.list", json!({ "search": "zebra" }));    assert_eq!(none["empty"], "No notes say “zebra”.");}#[test]fn buttons_and_styling_answer_without_a_write() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let pressed = ask(&handle, "notes.format", json!({ "text": "- milk", "cursor": 6, "action": { "action": "return" } }));    assert_eq!(pressed["text"], "- milk\n- ");    assert_eq!(pressed["selection"], json!({ "start": 9, "end": 9 }));    assert_eq!(pressed["replace"], json!({ "start": 6, "end": 6, "with": "\n- " }));    let bold = ask(&handle, "notes.format", json!({ "text": "a b", "selection": { "start": 2, "end": 3 }, "action": { "action": "bold" } }));    assert_eq!(bold["text"], "a **b**");    assert!(dispatch(&handle, "notes.format", &json!({ "text": "a", "action": { "action": "explode" } })).is_err());    let styled = ask(&handle, "notes.style", json!({ "text": "# T\n**b**", "cursor": 0 }));    assert_eq!(styled["title"], "T");    assert_eq!(ask(&handle, "notes.list", json!({}))["count"], 0);}#[test]fn a_picture_goes_in_where_the_cursor_is() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let id = write(&handle, "before\nafter");    let path = dir.path().join("pasted.png");    std::fs::write(&path, "synthetic pasted picture").unwrap();    let answer = ask(&handle, "notes.picture", json!({ "id": id, "path": path.to_string_lossy(), "mime": "image/png", "cursor": 3 }));    let src = answer["src"].as_str().unwrap();    assert!(src.starts_with("photo:"));    assert_eq!(answer["text"], format!("before\n\n![]({src})\nafter"));    assert_eq!(stored(&handle, &id)["body"], answer["text"]);    // The same bytes again are the same photo.    let again = ask(&handle, "notes.picture", json!({ "id": id, "path": path.to_string_lossy(), "mime": "image/png", "cursor": 0 }));    assert_eq!(again["src"], src);}#[test]fn themes_and_settings_are_data_and_sync_as_a_row() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let themes = ask(&handle, "notes.themes", json!({}));    let names: Vec<&str> = themes["themes"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();    assert_eq!(names, ["Linen", "Slate", "Print", "Dusk"]);    assert_eq!(themes["formatting"][0]["label"], "Heading");    assert!(themes["formatting"].as_array().unwrap().iter().any(|b| b["action"]["action"] == "table"));    let first = ask(&handle, "notes.settings", json!({}));    assert_eq!((first["light_theme"].as_str(), first["dark_theme"].as_str(), first["font"].as_str()), (Some("linen"), Some("slate"), Some("sans")));    assert_eq!(first["light"]["ground"], "#F8F6F1");    let set = ask(&handle, "notes.settings", json!({ "dark_theme": "print", "font": "mono", "font_size": 20, "line_width": 64 }));    assert_eq!((set["dark_theme"].as_str(), set["font"].as_str(), set["font_size"].as_f64(), set["line_width"].as_f64()), (Some("print"), Some("typewriter"), Some(20.0), Some(64.0)), "Mono, before Look, reads as the typewriter");    assert_eq!(set["light_theme"], "linen");    let kept = ask(&handle, "notes.settings", json!({ "light_theme": "dusk" }));    assert_eq!((kept["light_theme"].as_str(), kept["dark_theme"].as_str()), (Some("dusk"), Some("print")));    assert!(dispatch(&handle, "notes.settings", &json!({ "font_size": 99 })).is_err());    assert!(dispatch(&handle, "notes.settings", &json!({ "light_theme": "neon" })).is_err());}// RULE (owner, 22 Nov 2026): Words writes in blue until the person chooses another ink; the ink is kept in the notes// row and synced; every paper in notes.themes and the chosen look in notes.settings come in that ink; deleting stays red.#[test]fn the_ink_is_blue_until_chosen_and_every_paper_wears_it() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let first = ask(&handle, "notes.settings", json!({}));    assert_eq!(first["ink"], "blue", "a fresh copy, or one kept before inks, writes in blue");    assert_eq!(first["light"]["accent"], "#2B4A8F");    assert_eq!(first["light"]["danger"], "#CF4A3C");    assert_eq!(first["light"]["link"], first["light"]["text"]);    let themes = ask(&handle, "notes.themes", json!({}));    assert_eq!(themes["ink"], "blue");    let inks: Vec<&str> = themes["inks"].as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap()).collect();    assert_eq!(inks, ["Blue", "Red", "Green", "Black"]);    assert_eq!(themes["words"]["ink"], "Ink");    assert!(themes["themes"].as_array().unwrap().iter().all(|t| t["light"]["accent"] != t["light"]["danger"] || t["id"] == "print"));    let red = ask(&handle, "notes.settings", json!({ "ink": "red" }));    assert_eq!((red["ink"].as_str(), red["light"]["accent"].as_str(), red["dark"]["accent"].as_str()), (Some("red"), Some("#CF4A3C"), Some("#E26C5C")));    let themes = ask(&handle, "notes.themes", json!({}));    let slate = themes["themes"].as_array().unwrap().iter().find(|t| t["id"] == "slate").unwrap();    assert_eq!(slate["light"]["accent"], "#C8503F", "red is each paper's own red, as before");    let kept = settings_row(&handle, SETTINGS_ROW).unwrap();    assert_eq!(kept.get("ink").and_then(Value::as_str), Some("red"), "the ink syncs in the notes row");    assert!(dispatch(&handle, "notes.settings", &json!({ "ink": "purple" })).is_err());    assert_eq!(ask(&handle, "notes.settings", json!({ "ink": "blue" }))["light"]["accent"], "#2B4A8F");}// RULE (launch-ios, 22 Nov 2026): a settings row the object has stamped can be written again. Its `chosen_at` is a// full timestamp in a date column, so writing it back was refused and every change after the first sync failed.#[test]fn a_synced_settings_row_takes_a_second_change() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let stamped = json!({ "table": "notes", "face": "linen", "ink": "red", "chosen_at": "2026-11-22T17:26:00.855Z", "id": "x", "updated_at": "2026-11-22T17:26:00.855Z" });    let refused = crate::phone::records::call(&handle.client(), "records.create", &json!({ "table": "face_settings", "data": stamped.clone() }));    assert!(refused.is_err(), "the object's stamp, written back, is refused: the cause");    let row = rewritable(stamped.as_object().unwrap().clone());    assert!(!row.contains_key("chosen_at") && !row.contains_key("id") && !row.contains_key("updated_at"));    assert_eq!(row.get("ink").and_then(Value::as_str), Some("red"), "the person's choices are kept");    crate::phone::records::call(&handle.client(), "records.create", &json!({ "table": "face_settings", "data": Value::Object(row) })).expect("written again");    assert_eq!(ask(&handle, "notes.settings", json!({ "ink": "blue" }))["ink"], "blue");    assert_eq!(ask(&handle, "notes.settings", json!({ "ink": "green" }))["ink"], "green");}#[test]fn the_panel_has_quote_and_code_block_and_shortcuts_are_data() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let themes = ask(&handle, "notes.themes", json!({}));    let label = |action: &str| themes["formatting"].as_array().unwrap().iter().find(|b| b["action"]["action"] == action).map(|b| b["label"].clone());    assert_eq!(label("quote"), Some(json!("Quote")));    assert_eq!(label("code_block"), Some(json!("Code block")));    let shortcuts = themes["shortcuts"].as_array().unwrap();    let bold = shortcuts.iter().find(|s| s["action"]["action"] == "bold").unwrap();    assert_eq!((bold["keys"].clone(), bold["label"].clone()), (json!(["primary", "b"]), json!("Bold")));    let new = shortcuts.iter().find(|s| s["command"] == "new").unwrap();    assert_eq!((new["keys"].clone(), new["label"].clone()), (json!(["primary", "n"]), json!("New note")));    assert_eq!(themes["scale"]["heading"].as_array().map(Vec::len), Some(6));    for word in ["back", "more", "share", "settings", "close", "shortcuts", "return", "tick", "sample"] {        assert!(themes["words"][word].as_str().is_some_and(|w| !w.is_empty()), "{word}");    }}#[test]fn a_notes_info_card_counts_and_dates_it() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let id = write(&handle, "# Plan\n\nthree small words #work");    let info = ask(&handle, "notes.info", json!({ "id": id, "zone": "Asia/Kolkata" }));    assert_eq!(info["title"], "About this note");    let facts: Vec<(String, String)> = info["facts"].as_array().unwrap().iter().map(|f| (f["key"].as_str().unwrap().to_string(), f["value"].as_str().unwrap().to_string())).collect();    let keys: Vec<&str> = facts.iter().map(|(k, _)| k.as_str()).collect();    assert_eq!(keys, ["words", "characters", "paragraphs", "read_time", "created", "edited", "tags"]);    assert_eq!(info["words"], derive::derive("# Plan\n\nthree small words #work").words);    assert_eq!(info["characters"], "# Plan\n\nthree small words #work".chars().filter(|c| *c != '\n').count());    assert_eq!((facts[2].1.as_str(), facts[3].1.as_str()), ("2", "1 minute"));    assert!(facts[4].1.contains(", ") && facts[4].1.contains(':'), "{}", facts[4].1);    assert_eq!(facts[6].1, "#work");    assert_eq!(grouped(1234567), "1,234,567");    assert_eq!(grouped(999), "999");}fn textpack(path: &std::path::Path) {    use std::io::Write;    let file = std::fs::File::create(path).unwrap();    let mut zip = zip::ZipWriter::new(file);    let options: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default();    zip.start_file("text.md", options).unwrap();    zip.write_all(b"# Packed\n\nfrom a pack #imported/pack\n\n![](assets/p.png)").unwrap();    zip.start_file("assets/p.png", options).unwrap();    zip.write_all(b"synthetic packed picture").unwrap();    zip.start_file("info.json", options).unwrap();    zip.write_all(b"{}").unwrap();    zip.finish().unwrap();}/// RULE (owner, 19 Nov 2026): Bring notes in takes Markdown files, a folder/// of them, TextBundles and TextPacks with their pictures; hashtags file/// them; run twice it makes no duplicate; it says how many notes, pictures/// and tags came in and what it could not read.#[test]fn notes_come_in_once_with_their_pictures_and_tags() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let library = dir.path().join("Library");    std::fs::create_dir_all(library.join("images")).unwrap();    std::fs::write(library.join("Groceries.md"), "milk #shop\n\n![a cat](images/cat%20one.png)").unwrap();    std::fs::write(library.join("images/cat one.png"), "synthetic cat").unwrap();    std::fs::write(library.join("Plain.txt"), "\u{feff}Plain\r\nwords\r\n").unwrap();    std::fs::write(library.join("broken.md"), [0xffu8, 0xfe, b'a']).unwrap();    std::fs::write(library.join("song.mp3"), "not a note").unwrap();    let bundle = library.join("Trip.textbundle");    std::fs::create_dir_all(bundle.join("assets")).unwrap();    std::fs::write(bundle.join("text.md"), "Seen from the hill #travel\n\n![](assets/hill.jpg)").unwrap();    std::fs::write(bundle.join("assets/hill.jpg"), "synthetic hill").unwrap();    std::fs::write(bundle.join("info.json"), "{}").unwrap();    let pack = dir.path().join("Packed.textpack");    textpack(&pack);    let first = ask(&handle, "notes.import", json!({ "files": [{ "path": library.to_string_lossy() }, { "path": pack.to_string_lossy(), "name": "Packed.textpack" }] }));    assert_eq!(first["notes"], 5, "{first}");    assert_eq!(first["pictures"], 3, "{first}");    assert_eq!(first["tags"], 3, "{first}");    assert_eq!(first["unread"], json!(["Library/song.mp3"]), "{first}");    assert_eq!(first["said"], "5 notes, 3 pictures and 3 tags came in. Could not read: Library/song.mp3.");    let listed = ask(&handle, "notes.list", json!({}));    let titles: Vec<String> = rows(&listed).iter().map(|r| r["title"].as_str().unwrap_or("-").to_string()).collect();    for want in ["Groceries", "Plain", "Trip", "Packed", "broken"] {        assert!(titles.contains(&want.to_string()), "{want} in {titles:?}");    }    let trip = rows(&listed).into_iter().find(|r| r["title"] == "Trip").unwrap();    let text = ask(&handle, "notes.open", json!({ "id": trip["id"] }))["text"].as_str().unwrap().to_string();    assert!(text.starts_with("# Trip\n\nSeen from the hill #travel\n\n![](photo:"), "{text}");    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "imported" }))).len(), 1);    // Again (or after being cut short): nothing new.    let second = ask(&handle, "notes.import", json!({ "files": [{ "path": library.to_string_lossy() }, { "path": pack.to_string_lossy(), "name": "Packed.textpack" }] }));    assert_eq!((second["notes"].as_u64(), second["already"].as_u64()), (Some(0), Some(5)), "{second}");    assert_eq!(ask(&handle, "notes.list", json!({}))["count"], 5);}#[test]fn every_notes_method_is_a_method_of_this_build() {    for method in super::METHODS {        assert!(crate::methods::ALL_METHODS.contains(&method), "{method}");        assert!(crate::methods::CLIENT_METHODS.contains(&method), "{method}");    }}/// RULE (owner, 19 Nov 2026): the shared fan's notebook tile is Notes,/// Untagged, Archive, Bin and the tags.#[test]fn the_shared_fan_rings_the_notes_cards() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    write(&handle, "a note #fan");    let fan = ask(&handle, "shell.fan", json!({}));    let tile = fan["tiles"].as_array().unwrap().iter().find(|tile| tile["kind"] == "tool").expect("the notebook's tile");    // The Account card stands left of the first view, as in every app.    let views: Vec<&str> = tile["views"].as_array().unwrap().iter().map(|v| v["id"].as_str().unwrap()).filter(|id| *id != "account").collect();    assert!(views.starts_with(&["notes:all", "notes:untagged", "notes:archive", "notes:bin"]), "{views:?}");    assert!(views.contains(&"notes:tag:fan"), "{views:?}");}/// RULE (owner, 20 Nov 2026): the formatting keyboard is laid out as the/// reference's: the bar's undo, redo, tag, hide keyboard at the left and note/// link, format at the right; a grid of 4 rows by 6, the left column grey; copy/// and paste under it. Every key carries its words; Today writes the date.#[test]fn the_formatting_keyboard_is_the_owners_grid() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let themes = ask(&handle, "notes.themes", json!({}));    let kb = &themes["keyboard"];    let keys = |side: &str| kb["bar"][side].as_array().unwrap().iter().map(|k| k["key"].as_str().unwrap().to_string()).collect::<Vec<_>>();    assert_eq!(keys("left"), ["undo", "redo", "tag", "hide_keyboard"]);    assert_eq!(keys("right"), ["note_link", "format"]);    let grid = kb["grid"].as_array().unwrap();    assert_eq!(grid.len(), 4);    let names: Vec<Vec<&str>> = grid.iter().map(|row| row.as_array().unwrap().iter().map(|c| c["key"].as_str().unwrap()).collect()).collect();    assert_eq!(names, [        ["move_up", "picture", "quote", "table", "today", "fold"],        ["move_down", "heading_1", "bold", "italic", "underline", "strike"],        ["outdent", "bullet", "highlight", "code", "link", "delete"],        ["indent", "check", "divider", "numbered", "space", "return"],    ]);    for row in grid {        assert_eq!(row[0]["grey"], true, "the left column is grey");        for c in row.as_array().unwrap() {            assert!(!c["label"].as_str().unwrap().is_empty(), "{c}");            for h in c["hold"].as_array().into_iter().flatten() {                assert!(!h["label"].as_str().unwrap().is_empty(), "{h}");            }        }    }    assert_eq!(grid[1][1]["hold"].as_array().unwrap().len(), 2, "H1 holds H2 and H3");    assert_eq!((kb["foot"]["left"]["key"].as_str(), kb["foot"]["right"]["key"].as_str()), (Some("copy"), Some("paste")));    assert!(!kb["letters"].as_str().unwrap().is_empty());    assert!(!kb["letters_face"].as_str().unwrap().is_empty());    // Today writes the date at the cursor, in the core's words, the year in it.    let year = chrono::Utc::now().format("%Y").to_string();    let today = ask(&handle, "notes.format", json!({ "text": "On ", "selection": { "start": 3, "end": 3 }, "action": { "action": "today" }, "zone": "UTC" }));    let text = today["text"].as_str().unwrap();    assert!(text.starts_with("On ") && text.ends_with(&year), "{text}");    assert_eq!(today["selection"]["start"].as_u64(), Some(text.encode_utf16().count() as u64));}/// RULE (notes-empty, 21 Nov 2026: the owner's iPhone and Android drew none of 5,069 notes, about 4,500 of them archived, and said "That note is no longer here" at launch on every page): an archived note whose hashtag no `#` group holds yet (an import, an old app, another phone) is filed into its tag like any other note, and the list, the side page and a new note answer: an archived note is a note that is here.#[test]fn an_archived_note_with_an_unfiled_hashtag_never_stops_the_list() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let kept = old_note(&handle, Some("Seeds"), "Seeds to sow #garden");    let archived = old_note(&handle, Some("Old plan"), "Last spring's plan #garden");    super::with_write(&handle, "test", |ctx| {        let mut patch = Map::new();        patch.insert("archived_at".into(), json!("2025-04-01T09:00:00.000Z"));        cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_notes", &archived, patch).unwrap();        ctx.commit().unwrap();        Ok(Value::Null)    })    .unwrap();    let listed = ask(&handle, "notes.list", json!({ "view": "all" }));    assert_eq!(ids(&listed), vec![kept.clone()], "the live note lists");    ask(&handle, "notes.side", json!({}));    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "archive" }))), vec![archived.clone()]);    let garden = ask(&handle, "notes.list", json!({ "view": "tag", "tag": "garden" }));    assert_eq!(ids(&garden), vec![kept.clone()], "an archived note stays out of its tag's list");    let made = write(&handle, "test note");    let listed = ask(&handle, "notes.list", json!({ "view": "all" }));    let row = rows(&listed).into_iter().find(|row| row["id"] == json!(made)).expect("a new note shows");    assert_eq!((row["title"].as_str(), row["empty"].as_bool()), (Some("test note"), Some(false)), "its row carries its words, its first line as the title: {row}");    assert!(stored(&handle, &made).get("title").and_then(Value::as_str).unwrap_or_default().is_empty(), "a first line that is no heading is no stored title; the row reads the body");}/// RULE (notes-empty, 21 Nov 2026): filing never stops a list. A note whose tag cannot be filed (here a list keeping a where already holds the name `#garden`, so no `#garden` group can be made) is left as it stands, and the list, the side page and every other note's filing go on.#[test]fn a_note_that_cannot_be_filed_never_stops_the_list() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    super::with_write(&handle, "test", |ctx| {        let args = json!({ "table": "note", "name": "#garden", "where": { "pinned": true } });        cotton_tools::mcp::handlers::tables::groups::create_group(ctx, args.as_object().unwrap()).unwrap();        Ok(Value::Null)    })    .unwrap();    let garden = old_note(&handle, Some("Seeds"), "Seeds to sow #garden");    let home = old_note(&handle, Some("Paint"), "Paint the door #home");    let listed = ask(&handle, "notes.list", json!({ "view": "all" }));    let mut shown = ids(&listed);    shown.sort();    let mut both = vec![garden.clone(), home.clone()];    both.sort();    assert_eq!(shown, both, "both notes list");    ask(&handle, "notes.side", json!({}));    assert_eq!(ids(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "home" }))), vec![home], "the note that could be filed was");}/// RULE (notes-empty, 21 Nov 2026: an account of 5,000 notes pulled to a phone and filed one note at a time ran the first list for minutes, every change re-reading every member of its group): a copy's notes are filed in ONE change per group, however many notes it gains.#[test]fn many_unfiled_notes_are_filed_in_one_change_per_group() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    for n in 0..120 {        old_note(&handle, Some(&format!("Bed {n}")), &format!("Sow row {n} #garden"));    }    for n in 0..60 {        old_note(&handle, Some(&format!("Room {n}")), &format!("Paint wall {n} #home"));    }    let group_writes = |handle: &CottonHandle| -> i64 {        handle.client().with_file(|file| file.driver.get("SELECT COUNT(*) AS n FROM _writes WHERE tbl = 'cotton_groups'", &[]).map_err(|e| e.to_string()).map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))).unwrap()    };    let before = group_writes(&handle);    assert_eq!(rows(&ask(&handle, "notes.list", json!({ "view": "all" }))).len(), 180);    assert!(group_writes(&handle) - before <= 2, "two groups made, one change each: {} writes", group_writes(&handle) - before);    assert_eq!(rows(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "garden" }))).len(), 120);    assert_eq!(rows(&ask(&handle, "notes.list", json!({ "view": "tag", "tag": "home" }))).len(), 60);}/// One row of `table` written as given (an invented row of the kit's tables: an/// assistant's note, a web page, a memory entry, a project, a project link).fn invented(handle: &CottonHandle, table: &str, id: &str, data: Value) {    let row: Map<String, Value> = data.as_object().cloned().expect("an object");    super::with_write(handle, "test", |ctx| {        let mut row = row.clone();        // A document's file key, made in this database's own prefix as the phone makes it.        if row.get("storage_path").and_then(Value::as_str) == Some("@file") {            row.insert("storage_path".into(), json!(cotton_core::media::keys::document_original_key(ctx.file.id(), id, "html")));        }        cotton_tools::mcp::handlers::common::insert_row(ctx, table, id, row).unwrap();        ctx.commit().unwrap();        Ok(Value::Null)    })    .unwrap();}/// RULE (owner, 21 Nov 2026): the person's own list is their own. Notes, Todo,/// Today and Untagged hold what the person wrote; what an assistant wrote (its/// notes and the web pages it made) is under "From your assistant", newest/// first and searchable, a page carrying the media key the reader opens; a/// search for `@assistant` still finds the assistant's notes in Notes; the side/// page counts each place so.#[test]fn an_assistants_writing_stands_apart_from_the_persons_own() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let mine = write(&handle, "# Shopping\n\nmilk");    // Before any assistant has written or kept anything (a new person, signed out): no section for it at all (the    // launch walk, 22 Nov 2026: "Your assistant" stood empty on a fresh install, "Nothing from your assistant yet.").    assert_eq!(ask(&handle, "notes.side", json!({}))["assistant"], Value::Null, "nothing of an assistant yet");    let note = |title: &str, at: &str| json!({ "kind": "note", "title": title, "body": format!("# {title}\n\nInvented words"), "author_kind": "agent", "author_label": "Claude", "created_at": at, "updated_at": at });    invented(&handle, "cotton_notes", "a-old", note("Invented plan", "2026-11-01T09:00:00.000Z"));    invented(&handle, "cotton_notes", "a-new", note("Invented summary", "2026-11-20T09:00:00.000Z"));    let page = |title: &str, at: &str, bytes: i64| json!({ "title": title, "original_name": "page.html", "mime": "text/html", "byte_size": bytes, "sha256": format!("{bytes:0>64}"), "storage_path": "@file", "status": "ready", "created_at": at, "updated_at": at });    invented(&handle, "cotton_documents", "p-mid", page("Invented chart", "2026-11-10T09:00:00.000Z", 2048));    invented(&handle, "cotton_documents", "p-big", page("Invented atlas", "2026-11-05T09:00:00.000Z", 64 * 1024 * 1024));    invented(&handle, "cotton_documents", "d-pdf", json!({ "title": "Invented statement", "original_name": "s.pdf", "mime": "application/pdf", "byte_size": 10, "sha256": "f".repeat(64), "storage_path": "@file", "status": "ready" }));    let all = ask(&handle, "notes.list", json!({ "view": "all" }));    assert_eq!(ids(&all), vec![mine.clone()], "Notes holds the person's own");    assert_eq!(all["assistant"], json!({ "label": "From your assistant", "count": 4, "list": { "view": "assistant" } }), "one tap to the assistant's");    let asked = ask(&handle, "notes.list", json!({ "view": "all", "search": "@assistant" }));    assert_eq!(ids(&asked), vec!["a-new".to_string(), "a-old".to_string()], "@assistant still finds them");    let theirs = ask(&handle, "notes.list", json!({ "view": "assistant" }));    assert_eq!(ids(&theirs), vec!["a-new", "p-mid", "p-big", "a-old"], "notes and pages, newest first");    assert_eq!(theirs["heading"], "From your assistant");    let row = |id: &str| rows(&theirs).into_iter().find(|r| r["id"] == id).unwrap();    assert_eq!((row("p-mid")["kind"].as_str(), row("p-mid")["page"]["refused"].is_null()), (Some("page"), true));    assert!(row("p-mid")["page"]["key"].as_str().is_some_and(|key| key.contains("p-mid")), "the reader's media key: {}", row("p-mid"));    assert_eq!(row("p-big")["page"]["refused"], "This page is too big to open here.");    assert_eq!(row("a-new")["kind"], "note");    let found = ask(&handle, "notes.list", json!({ "view": "assistant", "search": "chart" }));    assert_eq!(ids(&found), vec!["p-mid"], "a search finds a page by its title");    let side = ask(&handle, "notes.side", json!({}));    assert_eq!(side["places"][0]["count"], 1, "Notes counts the person's own: {side}");    assert_eq!(side["assistant"]["items"][0]["id"], "assistant");    assert_eq!(side["assistant"]["items"][0]["count"], 4, "two notes and two pages, never the statement");    assert_eq!(side["assistant"]["items"][0]["list"], json!({ "view": "assistant" }));    assert_eq!((side["assistant"]["items"][1]["id"].as_str(), side["assistant"]["items"][1]["opens"].as_str()), (Some("memory"), Some("memory")));}/// RULE (owner, 21 Nov 2026): Words reads the assistant's memory, read-only:/// the live entries about the person first (linked to no project, oldest/// first), then each project's in its own order (pinned first, then position),/// each one sentence with when it changed; archived and replaced entries are/// not there.#[test]fn the_memory_reads_by_group_in_its_own_order() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let entry = |slug: &str, title: &str, status: &str, at: &str| json!({ "slug": slug, "title": title, "body": "", "status": status, "visibility": "private", "origin_kind": "agent", "origin_label": "Claude", "created_at": at, "updated_at": at });    invented(&handle, "cotton_memories", "m-me-2", entry("me-later", "I like invented mornings.", "active", "2026-11-03T09:00:00.000Z"));    invented(&handle, "cotton_memories", "m-me-1", entry("me-first", "Call me Ravi.", "active", "2026-11-01T09:00:00.000Z"));    invented(&handle, "cotton_memories", "m-gone", json!({ "slug": "me-gone", "title": "An archived invented line.", "body": "", "status": "archived", "archived_at": "2026-11-02T10:00:00.000Z", "visibility": "private", "origin_kind": "user", "created_at": "2026-11-02T09:00:00.000Z" }));    invented(&handle, "cotton_memories", "m-p-a", entry("drusket-a", "Drusket ships on Fridays.", "active", "2026-11-04T09:00:00.000Z"));    invented(&handle, "cotton_memories", "m-p-b", entry("drusket-b", "Drusket is one file.", "active", "2026-11-05T09:00:00.000Z"));    invented(&handle, "cotton_memories", "m-p-c", entry("drusket-c", "Drusket never sleeps.", "active", "2026-11-06T09:00:00.000Z"));    invented(&handle, "cotton_memory_projects", "pr-1", json!({ "slug": "drusket", "name": "Drusket", "repos": [], "status": "active", "created_at": "2026-10-01T09:00:00.000Z" }));    let link = |memory: &str, pinned: bool, position: f64| json!({ "project_id": "pr-1", "record_kind": "memory", "record_id": memory, "pinned": pinned, "position": position, "applied_by": "agent" });    invented(&handle, "cotton_project_links", "l-a", link("m-p-a", false, 2.0));    invented(&handle, "cotton_project_links", "l-b", link("m-p-b", false, 1.0));    invented(&handle, "cotton_project_links", "l-c", link("m-p-c", true, 9.0));    let memory = ask(&handle, "notes.memory", json!({}));    let groups = memory["groups"].as_array().expect("groups");    let said = |group: &Value| -> Vec<String> { group["entries"].as_array().unwrap().iter().map(|e| e["sentence"].as_str().unwrap().to_string()).collect() };    assert_eq!(groups[0]["label"], "About you");    assert_eq!(said(&groups[0]), ["Call me Ravi.", "I like invented mornings."], "oldest first, the archived one gone");    assert_eq!((groups[1]["label"].as_str(), groups[1]["project"].as_str()), (Some("Drusket"), Some("drusket")));    assert_eq!(said(&groups[1]), ["Drusket never sleeps.", "Drusket is one file.", "Drusket ships on Fridays."], "pinned first, then position");    assert_eq!(groups[1]["entries"][0]["pinned"], true);    assert!(groups[0]["entries"][0]["changed"].as_str().unwrap().starts_with("Changed "), "{memory}");    assert_eq!((memory["count"].as_u64(), memory["count_words"].as_str()), (Some(5), Some("5 entries")));    assert_eq!(ask(&handle, "notes.side", json!({}))["assistant"]["items"][1]["count"], 5);}/// A phone of this flavour (Cotton Dev, or the real Cotton) with its own database.fn phone_as(dir: &tempfile::TempDir, flavor: cotton_core::flavor::Flavor) -> CottonHandle {    let handle = CottonHandle::open(OpenConfig {        mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().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,        manifest: Some(notes_manifest()),    })    .expect("an open core");    dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone");    handle}/// Invented writing, as Words Dev's look asks for it (`notes-assistant-seed.json`'s shape).fn invented_writing() -> Value {    json!({        "notes": [            { "title": "Invented plan", "body": "# Invented plan\n\nInvented words", "at": "2026-11-01T09:00:00.000Z" },            { "title": "Invented summary", "body": "# Invented summary\n\nInvented words", "at": "2026-11-20T09:00:00.000Z" }        ],        "pages": [ { "title": "Invented chart", "at": "2026-11-10T09:00:00.000Z", "bytes": 2048 } ],        "about_you": [ { "slug": "me-invented", "title": "Call me Ravi.", "at": "2026-11-01T09:00:00.000Z" } ],        "projects": [ { "slug": "drusket", "name": "Drusket", "at": "2026-10-01T09:00:00.000Z", "entries": [            { "slug": "drusket-a", "title": "Drusket ships on Fridays.", "at": "2026-11-04T09:00:00.000Z" },            { "slug": "drusket-b", "title": "Drusket never sleeps.", "at": "2026-11-05T09:00:00.000Z", "pinned": true }        ] } ]    })}/// RULE (Cotton Dev only): invented assistant writing lands as an assistant's/// writes land, so Words Dev's look draws Your assistant from the core's own/// answers: the notes and the page under From your assistant (the person's/// Notes untouched), the page a reader can open, the memory in its groups./// Asked twice it writes the same rows. The real Cotton refuses it by name.#[test]fn invented_assistant_writing_lands_in_cotton_dev_only() {    let dir = tempfile::tempdir().unwrap();    let real = phone_as(&dir, cotton_core::flavor::Flavor::Real);    let refused = dispatch(&real, "developer.inventAssistantWriting", &invented_writing()).expect_err("the real Cotton refuses it");    assert_eq!(refused.code, "not_dev");    drop(real);    let dir = tempfile::tempdir().unwrap();    let dev = phone_as(&dir, cotton_core::flavor::Flavor::Dev);    let mine = write(&dev, "# Shopping\n\nmilk");    for _ in 0..2 {        ask(&dev, "developer.inventAssistantWriting", invented_writing());    }    assert_eq!(ids(&ask(&dev, "notes.list", json!({ "view": "all" }))), vec![mine], "Notes holds the person's own");    let theirs = ask(&dev, "notes.list", json!({ "view": "assistant" }));    assert_eq!(ids(&theirs), vec!["dev-assistant-note-1", "dev-assistant-page-0", "dev-assistant-note-0"], "notes and the page, newest first, once");    let page = rows(&theirs).into_iter().find(|row| row["kind"] == "page").expect("a page");    assert!(page["page"]["key"].as_str().is_some() && page["page"]["refused"].is_null(), "the reader opens it: {page}");    let memory = ask(&dev, "notes.memory", json!({}));    let groups = memory["groups"].as_array().expect("groups");    assert_eq!((groups[0]["label"].as_str(), groups[0]["count"].as_u64()), (Some("About you"), Some(1)));    assert_eq!(groups[1]["label"], "Drusket");    assert_eq!(groups[1]["entries"][0]["sentence"], "Drusket never sleeps.", "pinned first");    let side = ask(&dev, "notes.side", json!({}));    assert_eq!((side["assistant"]["items"][0]["count"].as_u64(), side["assistant"]["items"][1]["count"].as_u64()), (Some(3), Some(3)));}/// The assistant's rewrite landing in this copy while the writer stands open on the older body (a pull folds it in, as on the owner's iPhone, 21 Nov 2026).fn rewritten_under_the_writer(handle: &CottonHandle, id: &str, body: &str) {    super::with_write(handle, "mcp", |ctx| {        let args = json!({ "id": id, "body": body }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::records_1::notes::update_note(ctx, &args).unwrap())    })    .unwrap();}/// RULE (owner's lost edit, 21 Nov 2026): a writer opened at 17:50 saved its whole text over the bodies the assistant wrote at 19:05 and 20:05, and nothing said so. A save whose writer opened an older body than the copy holds is merged over what it opened: lines only one side changed are taken from it, lines both changed are both kept (the writer's first), the answer says so, and typing on keeps every line of both.#[test]fn a_save_from_a_writer_opened_on_an_older_body_keeps_the_newer_text() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let id = write(&handle, "# Trip\nPack the bag\nBook the train\nCall Asha\n");    let opened = ask(&handle, "notes.open", json!({ "id": id }));    assert_eq!(opened["text"], "# Trip\nPack the bag\nBook the train\nCall Asha\n");    // 19:05 and 20:05: the assistant rewrites lines of the body; the writer still shows 17:50.    rewritten_under_the_writer(&handle, &id, "# Trip\nPack the bag\nBook the 7:10 train, seat 42\nCall Asha\n");    rewritten_under_the_writer(&handle, &id, "# Trip\nPack the bag\nBook the 7:10 train, seat 42\nCall Asha\nTake the charger\n");    // The owner types at the top of what his writer shows, and it saves whole.    let saved = ask(&handle, "notes.edit", json!({ "id": id, "text": "# Trip to Goa\nPack the bag\nBook the train\nCall Asha\n" }));    let both = "# Trip to Goa\nPack the bag\nBook the 7:10 train, seat 42\nCall Asha\nTake the charger\n";    assert_eq!(saved["text"], both, "{saved}");    assert_eq!(saved["merged"], true);    assert_eq!(saved["both_kept"], false);    assert_eq!(saved["said"], "This note changed on another device while you were writing. Your changes are added to it.", "the person is told");    assert_eq!(stored(&handle, &id)["body"].as_str().map(|b| b.contains("seat 42") && b.contains("charger") && b.contains("Goa")), Some(true), "{:?}", stored(&handle, &id));    // He types on; his writer still holds his own text, not the answer's: nothing of the assistant's goes.    let typed = ask(&handle, "notes.edit", json!({ "id": id, "text": "# Trip to Goa\nPack the bag\nBook the train\nCall Asha\nAsk about the dog\n" }));    let text = typed["text"].as_str().unwrap();    for line in ["Trip to Goa", "seat 42", "Take the charger", "Ask about the dog"] {        assert!(text.contains(line), "{line} kept: {text}");    }    // The same line changed on both sides: both are kept.    let id = write(&handle, "Pack the bag\n");    ask(&handle, "notes.open", json!({ "id": id }));    rewritten_under_the_writer(&handle, &id, "Pack the big bag and the tent\n");    let saved = ask(&handle, "notes.edit", json!({ "id": id, "text": "Pack the small bag\n" }));    assert_eq!(saved["text"], "Pack the small bag\nPack the big bag and the tent\n");    assert_eq!(saved["both_kept"], true);    assert_eq!(saved["said"], "This note changed on another device while you were writing. Where you both changed a line, both are kept.");    // A writer whose note did not move saves as before, and says nothing of a merge.    let id = write(&handle, "Pack the bag\n");    ask(&handle, "notes.open", json!({ "id": id }));    let plain = ask(&handle, "notes.edit", json!({ "id": id, "text": "Pack the bag only\n" }));    assert_eq!(plain["text"], "Pack the bag only\n");    assert!(plain.get("merged").is_none());    assert!(plain.get("said").is_none(), "an unmoved note's save says nothing");}/// RULE (STALE, 21 Nov 2026): an open writer reloads when a pull moved its note by saving its text with the `base` it loaded. Unchanged,/// it gets the newer body and nothing is written or said; typed on, the typing is merged into the newer body and the person is told;/// once it took the newer body, its next save from it is a plain save.#[test]fn an_open_writer_reloads_through_a_save_of_what_it_loaded() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let old = "Weekend in Hampi\n\n- [ ] Book the bus\n- [ ] Guesthouse near the river";    let newer = "Weekend in Hampi\n\nLeave Friday after work.\n\n- [ ] Book the bus\n- [ ] Guesthouse near the river\n- [ ] Sunrise at Matanga Hill";    let id = write(&handle, old);    ask(&handle, "notes.open", json!({ "id": id }));    rewritten_under_the_writer(&handle, &id, newer);    let reloaded = ask(&handle, "notes.edit", json!({ "id": id, "text": old, "base": old }));    assert_eq!(reloaded["text"], newer, "the newer body is the answer");    assert!(reloaded.get("merged").is_none() && reloaded.get("said").is_none(), "nothing to tell: {reloaded}");    assert_eq!(stored(&handle, &id)["body"], newer, "nothing written over it");    // Took it, and ticks a box: a plain save.    let ticked = newer.replace("[ ] Book", "[x] Book");    let saved = ask(&handle, "notes.edit", json!({ "id": id, "text": ticked, "base": newer }));    assert_eq!(saved["text"], ticked.as_str());    assert!(saved.get("merged").is_none(), "{saved}");    // The note moves again while the person ticks another box: merged, told.    let again = format!("{ticked}\n- [ ] Ask Kiran about the boulders");    rewritten_under_the_writer(&handle, &id, &again);    let both = ticked.replace("[ ] Guesthouse", "[x] Guesthouse");    let saved = ask(&handle, "notes.edit", json!({ "id": id, "text": both, "base": ticked }));    assert_eq!(saved["text"], format!("{both}\n- [ ] Ask Kiran about the boulders").as_str());    assert_eq!(saved["merged"], true);    assert_eq!(saved["said"], "This note changed on another device while you were writing. Your changes are added to it.");}/// RULE (owner's lost edit, 21 Nov 2026): an edit keeps the body it was written over as its base; when the object refused the post as/// moved and the pull kept the newer body (`cotton_client::seal::EDIT_BASE`), the pass's end merges the edit over it as a new edit, and/// the newer body is the base of what follows.#[test]fn an_edit_the_object_refused_as_moved_is_merged_over_the_newer_body() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let id = write(&handle, "Pack the bag\nBook the train\n");    let base_row = |handle: &CottonHandle| -> Option<(String, Option<String>)> {        handle.client().with_file(|file| Ok(file.driver.get("SELECT base, theirs FROM _edit_base WHERE row_id = ?", &[rusqlite::types::Value::Text(id.clone())]).unwrap().map(|row| (row.text("base").unwrap().to_string(), row.text("theirs").map(str::to_string))))).unwrap()    };    // Offline, the owner adds to the first line; the body it was written over is kept as the base.    let mine = "Pack the bag and the charger\nBook the train\n";    ask(&handle, "notes.open", json!({ "id": id }));    ask(&handle, "notes.edit", json!({ "id": id, "text": mine }));    let (base, theirs) = base_row(&handle).expect("a base kept");    assert!(base.is_empty() || base == "Pack the bag\nBook the train\n", "the first edit's base: {base:?}");    assert_eq!(theirs, None);    // The pass: refused as moved, the pull keeps the assistant's newer body.    let newer = "Pack the bag\nBook the 7:10 train, seat 42\n";    handle.client().with_writer(|file| Ok(file.driver.run("UPDATE _edit_base SET base = 'Pack the bag\nBook the train\n', moved = 1, theirs = ?", &[rusqlite::types::Value::Text(newer.into())]).unwrap())).unwrap();    assert_eq!(super::merge_waiting(&handle.client()).unwrap(), 1);    let body = stored(&handle, &id)["body"].as_str().unwrap().to_string();    assert_eq!(body, "Pack the bag and the charger\nBook the 7:10 train, seat 42\n", "both sides' words");    assert_eq!(base_row(&handle).map(|(base, theirs)| (base, theirs)).filter(|(_, theirs)| theirs.is_none()).map(|(base, _)| base).unwrap_or_else(|| newer.to_string()), newer, "the newer body is the base now (or the base went with nothing left to send)");    assert_eq!(super::merge_waiting(&handle.client()).unwrap(), 0, "merged once");}/// RULE (coordinator, 21 Nov 2026): the same-name `#` groups the old 409 loop made are merged into the oldest of each name: a dry run counts them and writes nothing; applied, the oldest gains the members it lacked, every later one goes into the Bin, each note is filed by one group, and a second run finds none. A group a person named by hand is never touched.#[test]fn same_name_tag_groups_are_merged_into_the_oldest() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let a = write(&handle, "Standup #work");    let b = write(&handle, "Plan #work and #home");    let c = write(&handle, "Garden #home");    // The loop's groups: the same names again (any case), each with some of the notes.    // A phone now refuses a name held already, so they are made under names of their own and given the loop's name in the store, as a pull brought them.    for (n, (name, members)) in [("#work", vec![b.clone()]), ("#Work", vec![a.clone(), c.clone()]), ("#home", vec![c.clone()]), ("Errands", vec![a.clone()]), ("Errands", vec![b.clone()])].into_iter().enumerate() {        super::with_write(&handle, "test", |ctx| {            let args = json!({ "table": "note", "name": format!("loop {n}"), "records": members }).as_object().cloned().unwrap();            cotton_tools::mcp::handlers::tables::groups::create_group(ctx, &args).unwrap();            let rename = format!("UPDATE cotton_groups SET name = '{name}' WHERE name = 'loop {n}'");            ctx.read.driver().exec(&rename).unwrap();            crate::fixture::receipted(ctx.read.driver(), &rename);            Ok(json!(null))        })        .unwrap();    }    let groups = |handle: &CottonHandle| super::with_read(handle, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.into_iter().map(|g| (g.tag, g.members)).collect::<Vec<_>>()))).unwrap();    let counted = ask(&handle, "notes.merge_tags", json!({}));    assert_eq!((counted["tags"].as_u64(), counted["groups"].as_u64(), counted["moved"].as_u64(), counted["applied"].as_bool()), (Some(2), Some(3), Some(1), Some(false)), "{counted}");    assert_eq!(groups(&handle).as_array().unwrap().len(), 5, "a dry run writes nothing");    let merged = ask(&handle, "notes.merge_tags", json!({ "apply": true }));    assert_eq!(merged["groups"], 3, "{merged}");    let left: Vec<(String, Vec<String>)> = serde_json::from_value(groups(&handle)).unwrap();    assert_eq!(left.len(), 2, "one group a tag: {left:?}");    let members = |tag: &str| -> BTreeSet<String> { left.iter().find(|(t, _)| t.eq_ignore_ascii_case(tag)).map(|(_, m)| m.iter().cloned().collect()).unwrap_or_default() };    assert_eq!(members("work"), [a.clone(), b.clone(), c.clone()].into_iter().collect(), "the oldest gains what the later held");    assert_eq!(members("home"), [b.clone(), c.clone()].into_iter().collect());    assert_eq!(ask(&handle, "notes.merge_tags", json!({}))["groups"], 0, "nothing left to merge");    // The hand-made groups (no `#`) stand, both.    let errands = super::with_read(&handle, "test", |ctx| Ok(json!(cotton_tools::mcp::handlers::tables::groups::live_groups(ctx.read.driver(), Some(ctx.workspace_id)).unwrap().into_iter().filter(|(_, d)| cotton_tools::mcp::handlers::tables::groups::name_of(d) == "Errands").count()))).unwrap();    assert_eq!(errands, 2);}/// A note brought in from HTML holds an anchor (`href="#fn-6f1a2b3c"`), which an older rule filed as a tag named like an/// id. The side page shows the tags a person wrote, and the next list takes the note out of the anchor's group, which goes.#[test]fn an_anchor_filed_as_a_tag_by_an_older_rule_leaves_the_side_page() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let note = write(&handle, "Monsoon reading<sup><a href=\"#fn-6f1a2b3c\">1</a></sup> #garden");    super::with_write(&handle, "test", |ctx| {        let args = json!({ "table": "note", "name": "#fn-6f1a2b3c", "records": [note] }).as_object().cloned().unwrap();        Ok(cotton_tools::mcp::handlers::tables::groups::create_group(ctx, &args).unwrap())    })    .unwrap();    ask(&handle, "notes.list", json!({ "view": "all" }));    let side = ask(&handle, "notes.side", json!({}));    let names: Vec<&str> = side["tags"]["tree"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();    assert_eq!(names, vec!["garden"], "{side}");    let groups = super::with_read(&handle, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.into_iter().map(|g| g.tag).collect::<Vec<_>>()))).unwrap();    assert_eq!(groups, json!(["garden"]));}/// Colour codes an older rule filed as tags (the owner's side page: dozens like 1B2638 and 3A171C) leave the side page/// on the next list: each note leaves the colour's group and the emptied group goes.#[test]fn colour_codes_filed_as_tags_by_an_older_rule_leave_the_side_page() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let a = write(&handle, "Night palette #1B2638 and #3A171C, accent #E5C07Bff #design");    let b = write(&handle, "Same blue #1B2638 for the header");    for (name, members) in [("#1B2638", vec![a.clone(), b.clone()]), ("#3A171C", vec![a.clone()]), ("#E5C07Bff", vec![a.clone()])] {        super::with_write(&handle, "test", |ctx| {            let args = json!({ "table": "note", "name": name, "records": members }).as_object().cloned().unwrap();            Ok(cotton_tools::mcp::handlers::tables::groups::create_group(ctx, &args).unwrap())        })        .unwrap();    }    ask(&handle, "notes.list", json!({ "view": "all" }));    let side = ask(&handle, "notes.side", json!({}));    let names: Vec<&str> = side["tags"]["tree"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();    assert_eq!(names, vec!["design"], "{side}");    let groups = super::with_read(&handle, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.into_iter().map(|g| g.tag).collect::<Vec<_>>()))).unwrap();    assert_eq!(groups, json!(["design"]));}/// RULE (the launch walk, 22 Nov 2026): reading the list or the side page writes nothing when nothing needs filing or/// merging. Each list merged same-name tag groups as a write even with none to merge; the write said rows changed, the/// phone asked the list again on that, and Words asked `notes.list` and `shell.home` sixty times a second from launch.#[test]fn a_list_with_nothing_to_file_says_nothing_changed() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    write(&handle, "Weekend in Hampi #travel/2026\n\n- [ ] Book the bus");    write(&handle, "Garden #home");    assert!(super::files_now(&handle), "this copy files (the walk's phone did)");    // The first list files what is new; from then on nothing is left to file.    ask(&handle, "notes.list", json!({ "view": "all" }));    ask(&handle, "notes.side", json!({}));    let heard = handle.events().buffered_events().len();    for _ in 0..3 {        ask(&handle, "notes.list", json!({ "view": "all" }));        ask(&handle, "notes.side", json!({}));    }    let data: Vec<Value> = handle.events().buffered_events().into_iter().skip(heard).filter(|event| event["kind"] == "data").collect();    assert!(data.is_empty(), "reading wrote: {data:?}");}/// RULE (the launch walk, 22 Nov 2026; coordinator): a write that moved no table and no row sends no `data` event,/// since every phone screen reads again on one and a screen that reads through a write would loop on its own event./// A write that moves a row still says so.#[test]fn a_write_that_moves_nothing_sends_no_data_event() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    write(&handle, "Garden #home");    ask(&handle, "notes.list", json!({ "view": "all" }));    let data_since = |heard: usize| handle.events().buffered_events().into_iter().skip(heard).filter(|event| event["kind"] == "data").collect::<Vec<Value>>();    // Nothing to merge: a write that mints nothing.    let heard = handle.events().buffered_events().len();    let merged = ask(&handle, "notes.merge_tags", json!({ "apply": true }));    assert_eq!(merged["groups"], 0, "{merged}");    assert!(data_since(heard).is_empty(), "a write that moved nothing said rows moved: {:?}", data_since(heard));    let heard = handle.events().buffered_events().len();    write(&handle, "Reading list");    let moved = data_since(heard);    assert!(!moved.is_empty() && moved.iter().all(|event| event["payload"]["tables"].as_array().is_some_and(|tables| !tables.is_empty())), "{moved:?}");}/// RULE: the list names its search's clear mark in words (the launch walk, 22 Nov 2026: TalkBack read it as "close").#[test]fn the_list_names_its_search_clear_mark() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    write(&handle, "Weekend in Hampi");    let list = ask(&handle, "notes.list", json!({ "view": "all", "query": "Hampi" }));    assert_eq!(list["search_clear"], json!("Clear the search"), "{list}");}/// RULE (the owner's Words, 22 Nov 2026): his drawer listed 1B1A18, E9D9B7, F3EADA, FFFFFF, 211B12, 509, 1132-era,/// 1310-polish and test, of 0 or 1 notes, though he never tagged on purpose: colour codes and issue numbers an/// assistant's notes cite, filed as tags by older rules, and groups whose notes had gone. On the next list, with no/// note edited, each note leaves every group its text no longer tags, every `#` group no note holds goes into the Bin,/// the drawer lists only the tag a note holds (#test here), and no note's text changes.#[test]fn colour_codes_and_numbers_filed_as_tags_heal_on_the_next_list() {    let dir = tempfile::tempdir().unwrap();    let handle = phone(&dir);    let texts = [        "Palette for the reader: ground #1B1A18, paper #E9D9B7 and #F3EADA, ink #FFFFFF.",        "Fixes #509 and #1310-polish; see #1132-era. A #test of the import.",        "The brown was #211B12 before.",    ];    let notes: Vec<String> = texts.iter().map(|text| write(&handle, text)).collect();    let gone = write(&handle, "Old note #211B12");    // The groups older rules filed, as a pull brings them: named so in the store.    let filed: [(&str, Vec<String>); 9] = [        ("#1B1A18", vec![notes[0].clone()]), ("#E9D9B7", vec![notes[0].clone()]), ("#F3EADA", vec![notes[0].clone()]), ("#FFFFFF", vec![notes[0].clone()]),        ("#509", vec![notes[1].clone()]), ("#1132-era", vec![notes[1].clone()]), ("#1310-polish", vec![gone.clone()]), ("#211B12", vec![gone.clone()]), ("#test", vec![notes[1].clone()]),    ];    for (n, (name, members)) in filed.iter().enumerate() {        super::with_write(&handle, "test", |ctx| {            let args = json!({ "table": "note", "name": format!("old {n}"), "records": members }).as_object().cloned().unwrap();            cotton_tools::mcp::handlers::tables::groups::create_group(ctx, &args).unwrap();            let rename = format!("UPDATE cotton_groups SET name = '{name}' WHERE name = 'old {n}'");            ctx.read.driver().exec(&rename).unwrap();            crate::fixture::receipted(ctx.read.driver(), &rename);            Ok(json!(null))        })        .unwrap();    }    // The old note went into the Bin elsewhere, its groups left as they stood (a pull brings it so).    super::with_write(&handle, "test", |ctx| {        let bin = format!("UPDATE cotton_notes SET trashed_at = '2026-11-01T00:00:00.000Z' WHERE id = '{gone}'");        ctx.read.driver().exec(&bin).unwrap();        crate::fixture::receipted(ctx.read.driver(), &bin);        Ok(json!(null))    })    .unwrap();    let before: Vec<String> = notes.iter().map(|id| ask(&handle, "notes.open", json!({ "id": id }))["text"].as_str().unwrap_or_default().to_string()).collect();    ask(&handle, "notes.list", json!({ "view": "all" }));    let side = ask(&handle, "notes.side", json!({}));    let names: Vec<&str> = side["tags"]["tree"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();    assert_eq!(names, vec!["test"], "{side}");    let listed = ask(&handle, "notes.tags", json!({}));    let tags: Vec<&str> = listed["tags"].as_array().unwrap().iter().map(|t| t["tag"].as_str().unwrap()).collect();    assert_eq!(tags, vec!["test"], "{listed}");    let groups = super::with_read(&handle, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.into_iter().map(|g| g.tag).collect::<Vec<_>>()))).unwrap();    assert_eq!(groups, json!(["test"]), "every group no note holds went into the Bin");    let after: Vec<String> = notes.iter().map(|id| ask(&handle, "notes.open", json!({ "id": id }))["text"].as_str().unwrap_or_default().to_string()).collect();    assert_eq!(after, before, "no note's text changes");    // A second list writes nothing more.    ask(&handle, "notes.list", json!({ "view": "all" }));    assert_eq!(super::with_read(&handle, "test", |ctx| Ok(json!(super::tag_groups(ctx)?.len()))).unwrap(), json!(1));}