//! `shell.list` over synthetic databases: the scrolling list's page answered //! whole — its sections, rows, acts, menu, links, groups, empty words — //! paged by cursor. use super::*; use crate::handle::CottonHandle; const TODAY: &str = "2026-11-05"; thread_local! { /// A test's ask for the whole-row cut, never the narrow one. static WIDE: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// The last mark and each phase's time. type Phases = (Option, Vec<(&'static str, std::time::Duration)>); thread_local! { /// The bench's phases of one ask. static PHASES: std::cell::RefCell = const { std::cell::RefCell::new((None, Vec::new())) }; } thread_local! { /// The store steps at the last mark, and each phase's steps. static PHASE_STEPS: std::cell::RefCell<(u64, Vec<(&'static str, u64)>)> = const { std::cell::RefCell::new((0, Vec::new())) }; } /// Each phase's store steps since the last take. pub(super) fn phase_steps_take() -> Vec<(&'static str, u64)> { PHASE_STEPS.with(|steps| { let mut steps = steps.borrow_mut(); steps.0 = cotton_store::Driver::thread_steps(); std::mem::take(&mut steps.1) }) } /// The time since the last mark, added to `name`'s. pub(super) fn phase(name: &'static str) { PHASE_STEPS.with(|steps| { let mut steps = steps.borrow_mut(); let now = cotton_store::Driver::thread_steps(); let took = now - steps.0; steps.0 = now; match steps.1.iter_mut().find(|(held, _)| *held == name) { Some((_, held)) => *held += took, None => steps.1.push((name, took)), } }); PHASES.with(|phases| { let mut phases = phases.borrow_mut(); let now = std::time::Instant::now(); let took = phases.0.map(|at| now - at).unwrap_or_default(); phases.0 = Some(now); match phases.1.iter_mut().find(|(held, _)| *held == name) { Some((_, time)) => *time += took, None => phases.1.push((name, took)), } }); } /// The phases timed since the last take, from now. pub(super) fn phases_begin() { PHASES.with(|phases| *phases.borrow_mut() = (Some(std::time::Instant::now()), Vec::new())); } pub(super) fn phases_take() -> Vec<(&'static str, std::time::Duration)> { PHASES.with(|phases| std::mem::take(&mut phases.borrow_mut().1)) } thread_local! { /// How many kept cuts this thread patched. static PATCHED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// A kept cut patched on this thread. pub(super) fn patching() { PATCHED.with(|patched| patched.set(patched.get() + 1)); } /// How many kept cuts this thread has patched. fn patched() -> u64 { PATCHED.with(std::cell::Cell::get) } /// Whether this test thread reads a whole cut over whole light rows. pub(super) fn wide() -> bool { WIDE.with(std::cell::Cell::get) } /// A list's answer with the clock it was read at taken out (an archive act /// writes the moment it is pressed): two reads compared row for row. pub(super) fn unclocked(mut answer: Value) -> Value { fn walk(value: &mut Value) { match value { Value::Object(map) => { if let Some(Value::Object(write)) = map.get_mut("write") { for (_, held) in write.iter_mut() { if held.as_str().is_some_and(|text| text.len() == 24 && text.ends_with('Z')) { *held = json!("@now"); } } } map.values_mut().for_each(walk); } Value::Array(items) => items.iter_mut().for_each(walk), _ => {} } } walk(&mut answer); answer } /// `body` with the whole cut read wide (every light column), not narrow. fn read_wide(body: impl FnOnce() -> T) -> T { WIDE.with(|wide| wide.set(true)); let answer = body(); WIDE.with(|wide| wide.set(false)); answer } /// A fresh phone opened as Cotton. fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let manifest: Value = serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("a manifest"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::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(manifest), }) .expect("an open core"); crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); (dir, handle) } fn make(handle: &CottonHandle, table: &str, data: Value) -> String { let made = crate::methods::dispatch(handle, "records.create", &json!({"table": table, "data": data, "timezone": "Asia/Kolkata"})) .unwrap_or_else(|error| panic!("a {table} is made: {error:?}")); made["id"].as_str().or_else(|| made["record"]["id"].as_str()).unwrap_or_else(|| panic!("a made id: {made}")).to_string() } fn list(handle: &CottonHandle, request: Value) -> Value { let mut request = request; request["timezone"] = json!("Asia/Kolkata"); request["today"] = json!(TODAY); crate::methods::dispatch(handle, "shell.list", &request).unwrap_or_else(|error| panic!("the list reads: {error:?}")) } /// A section as the test reads it: id, heading, whether it folds, its count, its titles. type Drawn = (String, String, bool, Option, Vec); fn section<'a>(answer: &'a Value, id: &str) -> &'a Value { answer["sections"].as_array().unwrap().iter().find(|section| section["id"] == id).unwrap_or_else(|| panic!("no section {id}: {}", ids(answer))) } fn ids(answer: &Value) -> String { answer["sections"].as_array().unwrap().iter().map(|section| section["id"].as_str().unwrap_or_default().to_string()).collect::>().join(", ") } fn titles(section: &Value) -> Vec { section["rows"].as_array().unwrap().iter().map(|row| row["slip"]["title"].as_str().unwrap_or_default().to_string()).collect() } // RULE (boundary review, 5 Nov 2026): the Todos list is the core's day plan — Today open, each day ahead under its heading, Late, No date and Done shut with their whole counts. #[test] fn todos_read_as_their_day_plan() { assert!(crate::methods::read_only("shell.list")); let (_dir, handle) = phone(); make(&handle, "todo", json!({"title": "Invented today", "due_at": "2026-11-05T12:00:00+05:30"})); make(&handle, "todo", json!({"title": "Invented late", "due_at": "2026-11-01T12:00:00+05:30"})); make(&handle, "todo", json!({"title": "Invented tomorrow", "due_at": "2026-11-06T12:00:00+05:30"})); make(&handle, "todo", json!({"title": "Invented undated"})); make(&handle, "todo", json!({"title": "Invented done", "due_at": "2026-11-05T09:00:00+05:30", "status": "done"})); let answer = list(&handle, json!({"table": "todo"})); let drawn: Vec = answer["sections"].as_array().unwrap().iter().map(|section| ( section["id"].as_str().unwrap().to_string(), section["heading"].as_str().unwrap_or_default().to_string(), section["folds"].as_bool().unwrap(), section["count"].as_str().map(str::to_string), titles(section), )).collect(); let shut = |id: &str, heading: &str| (id.to_string(), heading.to_string(), true, Some("1".to_string()), Vec::::new()); assert_eq!(drawn, [ ("today".to_string(), "Today".to_string(), false, None, vec!["Invented today".to_string()]), shut("late", "Late"), ("day:2026-11-06".to_string(), "Tomorrow".to_string(), false, None, vec!["Invented tomorrow".to_string()]), shut("undated", "No date"), shut("done", "Done"), ], "{answer}"); // Today's month leaf: the day and the month's short name in the dates set's words. let november = cotton_core::rules::shell_lines::resolve("dates", "months.nov", &[], &[]).unwrap(); assert_eq!(section(&answer, "today")["leaf"], json!({"day": 5, "month": november})); assert!(section(&answer, "late").get("leaf").is_none(), "only Today carries a leaf"); // A row: its slip's words, its check, its acts by id (`shell.opened`'s rule), its tap. let row = §ion(&answer, "today")["rows"][0]; assert_eq!((row["toggled"].clone(), row["toggle"].clone()), (json!(false), json!({"status": "done"}))); assert!(row["slip"]["foot"].is_string(), "the core's foot: {row}"); assert!(row["slip"]["record"]["data"].is_object(), "the record the slip face still takes"); let opened = crate::methods::dispatch(&handle, "shell.opened", &json!({"table": "todo", "id": row["id"]})).unwrap(); let held: Vec<&Value> = opened["acts"].as_array().unwrap().iter().map(|act| &act["id"]).collect(); assert_eq!(row["acts"].as_array().unwrap().iter().collect::>(), held, "the list's acts are shell.opened's"); for id in row["acts"].as_array().unwrap() { assert!(answer["acts"][id.as_str().unwrap()]["label"].is_string(), "{id} is named once"); } assert!(answer["acts"][row["tap"].as_str().unwrap()]["kind"] == "open"); // Where it opens: its definition's route filled, and the kind of screen. assert_eq!(row["opens"]["path"], json!(format!("/todos/todo/{}", row["id"].as_str().unwrap())), "{row}"); assert_eq!(row["opens"]["screen"], "outside"); assert_eq!(row["opens"], opened["opens"], "the list row opens where the held card does"); assert_eq!(answer["title"], "Todos"); assert_eq!(answer["count"], 5); assert_eq!(answer["next"], Value::Null); assert_eq!(answer["plus"]["does"], "blank"); // A shut section opened: asked alone, open, its rows. let late = list(&handle, json!({"table": "todo", "section": "late"})); assert_eq!(late["sections"].as_array().unwrap().len(), 1, "{late}"); assert_eq!((titles(section(&late, "late")), section(&late, "late")["open"].clone()), (vec!["Invented late".to_string()], json!(true))); let done = list(&handle, json!({"table": "todo", "section": "done"})); assert_eq!(titles(section(&done, "done")), ["Invented done"], "{done}"); assert_eq!(section(&done, "done")["rows"][0]["stamp"], "done"); } fn group(handle: &CottonHandle, table: &str, name: &str, members: &[&str]) -> String { let mut asked = json!({"table": table, "name": name}); if !members.is_empty() { asked["records"] = json!(members); } let made = crate::methods::dispatch(handle, "groups.create", &asked) .unwrap_or_else(|error| panic!("{name} is made: {error:?}")); made["group"]["id"].as_str().unwrap_or_else(|| panic!("a made group: {made}")).to_string() } fn every_title(answer: &Value) -> Vec { answer["sections"].as_array().unwrap().iter().flat_map(titles).collect() } fn menu_ids(answer: &Value) -> Vec { answer["menu"].as_array().unwrap().iter().map(|item| item["id"].as_str().unwrap_or_default().to_string()).collect() } // RULE (owner, 2 Nov 2026; R9): the Calendar opens on what is coming, each day under its heading, a weekly event under each day it happens; the past is one "Earlier · n" link, read newest first. /// RULE: a tile of slips shows today and the open work a list keeps shut, /// never the finished, each record carrying its one slip answer. #[test] fn a_tile_shows_open_work_and_leaves_out_the_finished() { let (_dir, handle) = phone(); make(&handle, "todo", json!({"title": "Invented today", "due_at": "2026-11-05T12:00:00+05:30"})); make(&handle, "todo", json!({"title": "Invented late", "due_at": "2026-11-01T12:00:00+05:30"})); make(&handle, "todo", json!({"title": "Invented undated"})); make(&handle, "todo", json!({"title": "Invented done", "due_at": "2026-11-05T09:00:00+05:30", "status": "done"})); let answer = list(&handle, json!({"table": "todo", "tile": true})); let names: Vec<&str> = answer["records"].as_array().unwrap().iter().map(|record| record["data"]["@said"]["slip"]["name"].as_str().unwrap()).collect(); assert!(names.contains(&"Invented today") && names.contains(&"Invented late") && names.contains(&"Invented undated"), "{names:?}"); assert!(!names.contains(&"Invented done"), "{names:?}"); } #[test] fn calendar_reads_coming_and_earlier_with_a_repeating_event() { let (_dir, handle) = phone(); make(&handle, "event", json!({"title": "Invented launch", "starts_at": "2026-11-07T18:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented dentist", "starts_at": "2026-11-09T10:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented old lunch", "starts_at": "2026-10-01T13:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented older lunch", "starts_at": "2026-09-01T13:00:00+05:30"})); make(&handle, "event", json!({"title": "Invented swim", "starts_at": "2026-10-29T07:00:00+05:30", "rrule": "FREQ=WEEKLY"})); let answer = list(&handle, json!({"table": "event"})); let swim_days: Vec = answer["sections"].as_array().unwrap().iter() .filter(|section| titles(section).contains(&"Invented swim".to_string())).map(|section| section["id"].as_str().unwrap().to_string()).collect(); assert_eq!(&swim_days[..2], ["day:2026-11-05", "day:2026-11-12"], "the swim stands under each day it happens: {}", ids(&answer)); assert_eq!(section(&answer, "day:2026-11-05")["heading"], "Today"); assert_eq!(titles(section(&answer, "day:2026-11-07")), ["Invented launch"]); assert_eq!(titles(section(&answer, "day:2026-11-09")), ["Invented dentist"]); assert!(!every_title(&answer).contains(&"Invented old lunch".to_string()), "the past is behind its link"); let earlier = answer["links"].as_array().unwrap().iter().find(|link| link["id"] == "earlier").unwrap_or_else(|| panic!("an Earlier link: {}", answer["links"])); assert_eq!((earlier["label"].clone(), earlier["count"].clone()), (json!("Earlier"), json!(2)), "{earlier}"); let past = list(&handle, earlier["opens"].clone()); assert_eq!(every_title(&past), ["Invented old lunch", "Invented older lunch"], "newest first: {}", ids(&past)); assert!(past["links"].as_array().unwrap().iter().all(|link| link["id"] != "earlier")); } // RULE (phase 5, the owner's rule): People is one run in A–Z order, case and accents folded, the rail landing on each letter's first person; a name that starts with no letter files under #. #[test] fn people_read_a_to_z_with_their_index() { let (_dir, handle) = phone(); for name in ["Bela Invented", "élodie Invented", "anil Invented", "Anand Invented", "9 Invented"] { make(&handle, "person", json!({"full_name": name, "language": "en"})); } let answer = list(&handle, json!({"table": "person"})); assert_eq!(every_title(&answer), ["Anand Invented", "anil Invented", "Bela Invented", "élodie Invented", "9 Invented"], "{answer}"); let index: Vec<(String, u64)> = answer["index"].as_array().unwrap().iter().map(|entry| (entry["letter"].as_str().unwrap().to_string(), entry["at"].as_u64().unwrap())).collect(); assert_eq!(index, [("A".to_string(), 0), ("B".to_string(), 2), ("E".to_string(), 3), ("#".to_string(), 4)]); assert_eq!(answer["title"], "People"); assert!(menu_ids(&answer).contains(&"select".to_string()), "People gathers groups, so Select: {}", answer["menu"]); } // RULE (S8): a pick ticks rows, the held ones marked; it offers no act, no menu, no groups. #[test] fn a_pick_marks_the_held_rows() { let (_dir, handle) = phone(); let asha = make(&handle, "person", json!({"full_name": "Asha Invented", "language": "en"})); make(&handle, "person", json!({"full_name": "Bela Invented", "language": "en"})); let answer = list(&handle, json!({"table": "person", "pick": {"column": "id", "held": [asha]}})); let rows: Vec<&Value> = answer["sections"].as_array().unwrap().iter().flat_map(|section| section["rows"].as_array().unwrap()).collect(); assert_eq!(rows.len(), 2); for row in &rows { assert_eq!(row["tap"], "pick"); assert_eq!(row["held"], json!(row["id"] == asha.as_str()), "{row}"); assert_eq!(row["acts"], json!([])); } assert_eq!(answer["menu"], json!([])); assert_eq!(answer["groups"], Value::Null); } // RULE (S7): a table that archives counts what is put away as "Archived · n"; the archived list holds them, each with Bring back. #[test] fn archived_is_counted_and_listed_with_bring_back() { let (_dir, handle) = phone(); make(&handle, "person", json!({"full_name": "Asha Invented", "language": "en"})); let bela = make(&handle, "person", json!({"full_name": "Bela Invented", "language": "en"})); crate::methods::dispatch(&handle, "records.command", &json!({"table": "person", "id": bela, "command": "archive"})).expect("Bela is archived"); let answer = list(&handle, json!({"table": "person"})); assert_eq!(every_title(&answer), ["Asha Invented"], "{answer}"); let archived = answer["links"].as_array().unwrap().iter().find(|link| link["id"] == "archived").unwrap_or_else(|| panic!("an Archived link: {}", answer["links"])); assert_eq!((archived["label"].clone(), archived["count"].clone()), (json!("Archived"), json!(1))); let put_away = list(&handle, archived["opens"].clone()); assert_eq!(every_title(&put_away), ["Bela Invented"], "{put_away}"); let row = &put_away["sections"][0]["rows"][0]; assert!(row["acts"].as_array().unwrap().contains(&json!("bring_back")), "{row}"); assert_eq!(put_away["acts"]["bring_back"]["label"], "Bring back"); assert!(put_away["links"].as_array().unwrap().iter().all(|link| link["id"] != "archived")); assert_eq!(put_away["groups"], Value::Null, "the archived draw no stacks"); } // RULE (S6, 6 Oct): a long list pages fifty at a time with no gap and no repeat, and the core says when it ends. #[test] fn two_thousand_rows_page_with_no_gap_or_repeat() { let (_dir, handle) = phone(); // One book made as the phone makes one, and 1,999 more as its row, in one act (Money's spends were the rows until // TABLE DROP 1): 2,000 writes one by one say nothing about paging. let first = make(&handle, "book", json!({"title": "Invented book 0000", "author": "Invented Author", "status": "reading", "added_on": "2026-11-01"})); bench::cloned(&handle, "cotton_book", &first, 1999, &[("id", "printf('00000000-0000-4000-8000-%012d', i + 1)"), ("title", "printf('Invented book %04d', i + 1)")]); let mut seen = std::collections::HashSet::new(); let mut cursor = Value::Null; let mut pages = 0; let mut timings = Vec::new(); loop { let began = std::time::Instant::now(); let answer = list(&handle, json!({"table": "book", "cursor": cursor})); timings.push(began.elapsed()); assert_eq!(answer["count"], 2000); for section in answer["sections"].as_array().unwrap() { for row in section["rows"].as_array().unwrap() { assert!(seen.insert(row["id"].as_str().unwrap().to_string()), "a repeat at page {pages}"); } } pages += 1; cursor = answer["next"].clone(); if cursor.is_null() { break; } } assert_eq!(seen.len(), 2000, "no gap"); assert_eq!(pages, 40); eprintln!("shell.list on 2,000 rows: first page {:?}, page 20 {:?}, last {:?}", timings[0], timings[20], timings[39]); } // RULE (notewords, 16 Oct 2026; walker 298): an empty list says its table's words over its picture; a search that matches nothing says so, however its links count. #[test] fn an_empty_list_and_a_search_say_their_words() { let (_dir, handle) = phone(); let empty = list(&handle, json!({"table": "person"})); assert_eq!(empty["sections"], json!([])); assert!(empty["empty"]["title"].as_str().is_some_and(|title| !title.is_empty()), "{}", empty["empty"]); assert_eq!(empty["count"], 0); make(&handle, "person", json!({"full_name": "Asha Invented", "language": "en"})); let found = list(&handle, json!({"table": "person", "query": "Asha"})); assert_eq!(every_title(&found), ["Asha Invented"]); assert_eq!((found["index"].clone(), found["empty"].clone()), (Value::Null, Value::Null), "a search draws no rail"); let none = list(&handle, json!({"table": "person", "query": "Zebedee"})); assert_eq!(none["sections"], json!([])); assert!(none["empty"]["title"].as_str().is_some_and(|title| !title.is_empty()), "{}", none["empty"]); assert_ne!(none["empty"], empty["empty"], "a search's words are its own"); } // RULE (shell-list-reader, 7 Nov 2026): a table a shell's own source still answers hands its rows; the core sections, indexes and pages them as its own read, with nothing archived and no plan. #[test] fn handed_rows_are_read_as_the_cores_own() { let (_dir, handle) = phone(); let rows: Vec = ["Bela Invented", "anil Invented", "9 Invented"].iter().enumerate() .map(|(at, name)| json!({"id": format!("p{at}"), "data": {"full_name": name}})).collect(); let answer = list(&handle, json!({"table": "person", "rows": rows})); assert_eq!(every_title(&answer), ["anil Invented", "Bela Invented", "9 Invented"], "{answer}"); assert_eq!(answer["count"], 3); assert!(answer["links"].as_array().unwrap().iter().all(|link| link["id"] != "archived"), "nothing handed is archived"); let letters: Vec<&str> = answer["index"].as_array().unwrap().iter().map(|entry| entry["letter"].as_str().unwrap()).collect(); assert_eq!(letters, ["A", "B", "#"]); let many: Vec = (0..120).map(|at| json!({"id": format!("t{at:03}"), "data": {"title": format!("Invented book {at:03}"), "status": "reading"}})).collect(); let mut seen = std::collections::HashSet::new(); let mut cursor = Value::Null; let mut pages = 0; loop { let page = list(&handle, json!({"table": "book", "rows": many, "cursor": cursor, "limit": 50})); assert_eq!(page["count"], 120, "{page}"); for row in page["sections"].as_array().unwrap().iter().flat_map(|section| section["rows"].as_array().unwrap()) { assert!(seen.insert(row["id"].as_str().unwrap().to_string()), "a repeat"); } pages += 1; cursor = page["next"].clone(); if cursor.is_null() { break; } } assert_eq!((seen.len(), pages), (120, 3), "every handed row once, fifty a page"); let refused = crate::methods::dispatch(&handle, "shell.list", &json!({"table": "person", "rows": [{"name": "no id"}]})); assert!(refused.is_err(), "a row with no id is refused by name"); } // RULE (shell-list-reader): the archived list of a source's table hands its archived rows, and they are listed. #[test] fn handed_archived_rows_are_listed() { let (_dir, handle) = phone(); let rows = json!([{"id": "p0", "data": {"full_name": "Kept Invented"}}]); let answer = list(&handle, json!({"table": "person", "rows": rows, "archived": true})); assert_eq!(every_title(&answer), ["Kept Invented"], "{answer}"); } fn press_ids(row: &Value) -> Vec { row["press"].as_array().unwrap_or_else(|| panic!("a press: {row}")).iter().map(|act| act["id"].as_str().unwrap().to_string()).collect() } // RULE (shell-list-rest, 7 Nov 2026; the press-menu double): a slip's long press is the card's own acts, named once — a person offers one Archive, and an archived person none, but Bring back; an act that opens a step stays on the card's fan. #[test] fn a_press_offers_one_archive_and_none_once_archived() { let (_dir, handle) = phone(); let asha = make(&handle, "person", json!({"full_name": "Asha Invented", "language": "en"})); let bela = make(&handle, "person", json!({"full_name": "Bela Invented", "language": "en"})); let answer = list(&handle, json!({"table": "person"})); let row = answer["sections"].as_array().unwrap().iter().flat_map(|section| section["rows"].as_array().unwrap()).find(|row| row["id"] == asha.as_str()).unwrap(); let press = press_ids(row); assert_eq!(press.iter().filter(|id| id.contains("archive")).count(), 1, "one Archive: {press:?}"); let archive = row["press"].as_array().unwrap().iter().find(|act| act["id"] == "archive").unwrap(); assert_eq!((archive["label"].clone(), archive["kind"].clone()), (json!("Archive"), json!("command")), "{archive}"); assert!(row["press"].as_array().unwrap().iter().all(|act| act.get("step").is_none()), "no act that opens a step: {}", row["press"]); crate::methods::dispatch(&handle, "records.command", &json!({"table": "person", "id": bela, "command": "archive"})).expect("Bela is archived"); let put_away = list(&handle, json!({"table": "person", "archived": true})); let row = &put_away["sections"][0]["rows"][0]; assert_eq!(row["id"], bela.as_str()); assert_eq!(press_ids(row), ["bring_back"], "an archived person offers no Archive: {row}"); } // RULE (shell-list-rest, 7 Nov 2026): Select's Delete asks in the core's words — how many, of what — and its receipt over them all is the core's too; what could not go is said after. #[test] fn select_delete_asks_in_the_cores_words() { let (_dir, handle) = phone(); let one = make(&handle, "todo", json!({"title": "Invented one"})); let two = make(&handle, "todo", json!({"title": "Invented two"})); let asked = |picked: Value, failed: Option| { let mut request = json!({"table": "todo", "deleting": picked}); if let Some(failed) = failed { request["failed"] = failed; } list(&handle, request)["deleting"].clone() }; let both = asked(json!([one, two]), None); assert_eq!(both["ids"], json!([one, two]), "{both}"); assert_eq!(both["asks"], true); assert_eq!(both["question"]["title"], "Delete 2 todos?", "{both}"); assert_eq!(both["question"]["confirm"], "Delete"); assert_eq!(both["done"], "Deleted 2 todos"); assert_eq!(both["outcome"], "2 deleted"); let alone = asked(json!([one]), None); assert_eq!(alone["question"]["title"], "Delete this todo?", "{alone}"); let refused = asked(json!([one]), Some(json!([two]))); assert_eq!(refused["outcome"], "1 of 2 could not be deleted \u{2014} still selected, so you can try again.", "{refused}"); } // RULE (shell-list-rest, 7 Nov 2026): a group's page writes through the list's own acts — Add and Remove its picks, Rename refused in the list's words when empty or taken, Remove list asked in the list's words. #[test] fn a_group_page_writes_through_its_list_acts() { let (_dir, handle) = phone(); // Books' lists (Owed's groups were the example until TABLE DROP 1). let book = |what: &str| make(&handle, "book", json!({"title": what, "author": "Invented Author", "status": "reading", "added_on": "2026-11-01"})); let dinner = book("Invented dinner"); let taxi = book("Invented taxi"); let trip = group(&handle, "book", "Invented trip", &[&dinner]); group(&handle, "book", "Invented fair", &[]); let page = list(&handle, json!({"table": "book", "where": {"group": trip}, "title": "Invented trip"})); let menu = menu_ids(&page); assert_eq!(&menu[..3], ["select", "list_add", "list_take_out"], "Select, then its picks: {menu:?}"); let item = |id: &str| page["menu"].as_array().unwrap().iter().find(|item| item["id"] == id).unwrap_or_else(|| panic!("no {id}: {menu:?}")).clone(); assert!(item("list_add")["label"].as_str().is_some_and(|label| label.starts_with("Add ")) && item("list_add")["picks"] == json!("add"), "{}", item("list_add")); let remove = item("list_remove"); assert_eq!(remove["question"]["title"], "Delete Invented trip?", "{remove}"); assert!(remove["question"]["confirm"].as_str().is_some_and(|confirm| confirm.starts_with("Delete ")), "{remove}"); let act = |act: &str, extra: Value| { let mut request = item(act)["act"].clone(); request["act"] = request["id"].clone(); for (key, value) in extra.as_object().unwrap() { request[key] = value.clone(); } crate::methods::dispatch(&handle, "tools.act", &request) }; let rename = |words: &str| { let mut request = item("list_rename")["act"].clone(); request["act"] = request["id"].clone(); request["words"] = json!(words); crate::methods::dispatch(&handle, "tools.act", &request) }; let added = act("list_add", json!({"records": [taxi]})).expect("the taxi is put in"); assert!(added["change"]["id"].is_string() && added["undo"] == added["change"]["id"], "the change whole: {added}"); let members = |page: &Value| -> Vec { page["sections"].as_array().unwrap().iter().flat_map(|section| section["rows"].as_array().unwrap()).map(|row| row["id"].as_str().unwrap().to_string()).collect() }; let mut held = members(&list(&handle, json!({"table": "book", "where": {"group": trip}}))); held.sort(); let mut both = vec![dinner.clone(), taxi.clone()]; both.sort(); assert_eq!(held, both); act("list_take_out", json!({"records": [dinner]})).expect("the dinner is taken out"); assert_eq!(members(&list(&handle, json!({"table": "book", "where": {"group": trip}}))), std::slice::from_ref(&taxi)); let empty = rename(" ").expect_err("an empty name is refused"); assert_eq!(empty.message, "Give the list a name."); let taken = rename("invented FAIR").expect_err("a taken name is refused"); assert_eq!(taken.message, "There is already a list called invented FAIR."); rename("Invented holiday").expect("renamed"); } // RULE (shell-list-perf, 7 Nov 2026): a whole list's cut and its frame are kept between asks only while the file has not moved on: any write is read on the next ask, nothing waits for a timer. #[test] fn a_kept_cut_reads_again_after_a_write() { let (_dir, handle) = phone(); let anand = make(&handle, "person", json!({"full_name": "Anand Invented", "language": "en"})); make(&handle, "person", json!({"full_name": "Bela Invented", "language": "en"})); let first = list(&handle, json!({"table": "person"})); assert_eq!(first, list(&handle, json!({"table": "person"})), "asked again unmoved, the same answer"); make(&handle, "person", json!({"full_name": "Asha Invented", "language": "en"})); let after = list(&handle, json!({"table": "person"})); assert_eq!(every_title(&after), ["Anand Invented", "Asha Invented", "Bela Invented"], "a made row is cut in: {after}"); assert_eq!(after["count"], 3); crate::methods::dispatch(&handle, "records.command", &json!({"table": "person", "id": anand, "command": "archive"})).expect("archived"); let archived = list(&handle, json!({"table": "person"})); assert_eq!(every_title(&archived), ["Asha Invented", "Bela Invented"], "an archived row leaves the cut: {archived}"); let link = archived["links"].as_array().unwrap().iter().find(|link| link["id"] == "archived").unwrap_or_else(|| panic!("the Archived link counts it: {}", archived["links"])); assert_eq!(link["count"], 1, "the kept frame moved too: {link}"); } // RULE (shell-list-narrow, 8 Nov 2026): a whole list's cut reads only the ids and the columns it cuts by; its pages are the pages the whole-row cut answered, row for row, heads and all. #[test] fn a_narrow_cut_pages_as_the_whole_row_cut() { let (_dir, handle) = phone(); let people: Vec = ["Ana", "Ben", "Cal"].iter().map(|name| make(&handle, "person", json!({"full_name": format!("{name} Invented"), "language": "en"}))).collect(); let gone = make(&handle, "person", json!({"full_name": "Gone Invented", "language": "en"})); let statuses = ["want_to_read", "reading", "finished", "stopped"]; for at in 0..45 { make(&handle, "book", json!({"title": format!("Invented {at:02}"), "added_on": format!("2026-10-{:02}", 1 + at % 28), "author": format!("Invented Author {}", at % 3), "status": statuses[at % 4]})); } crate::methods::dispatch(&handle, "records.delete", &json!({"table": "person", "id": gone})).expect("a person gone"); for name in ["Asha", "Bela", "Zed", "9 Lives"] { make(&handle, "person", json!({"full_name": format!("{name} Invented"), "language": "en"})); } for at in 0..5 { make(&handle, "note", json!({"title": format!("Invented note {at}"), "body": "Invented"})); } for table in ["book", "person", "note"] { for cursor in [0, PAGE, 2 * PAGE] { let narrow = unclocked(list(&handle, json!({"table": table, "cursor": cursor}))); let wide = unclocked(read_wide(|| list(&handle, json!({"table": table, "cursor": cursor})))); assert_eq!(narrow, wide, "{table} at {cursor}: the narrow cut's page is the whole-row cut's"); } } } /// A small synthetic book whose every id and moment is fixed: 240 books by /// 12 authors in the four statuses, 60 people, 40 notes. Two phones made alike answer alike. fn golden_book() -> (tempfile::TempDir, CottonHandle) { let (dir, handle) = phone(); // The words a row wears ("3 days ago", "late") are read against the // device's clock, so the golden pins it to TODAY's morning: the same // answer on any day the test runs. handle.client().pin_clock(chrono::DateTime::parse_from_rfc3339(&format!("{TODAY}T10:00:00Z")).expect("a literal instant").with_timezone(&chrono::Utc)); let person = make(&handle, "person", json!({"full_name": "Template Person", "language": "en"})); bench::cloned(&handle, "cotton_people", &person, 60, &[ ("id", "printf('gold-person-%03d', i)"), ("full_name", "char(65 + (i * 7) % 26) || printf('nvented Person %03d', i)"), ("created_at", "@moment"), ("updated_at", "@moment"), ]); // Books, 240 of them (Money's spends were the golden's rows until TABLE DROP 1). let book = make(&handle, "book", json!({"title": "Template book", "author": "Template Author", "status": "reading", "added_on": TODAY})); bench::cloned(&handle, "cotton_book", &book, 240, &[ ("id", "printf('gold-book-%04d', i)"), ("added_on", "n.day"), ("title", "printf('Invented book %04d', i)"), ("author", "printf('Invented Author %02d', i % 12)"), ("status", "CASE i % 4 WHEN 0 THEN 'reading' WHEN 1 THEN 'want_to_read' WHEN 2 THEN 'finished' ELSE 'stopped' END"), ("created_at", "@moment"), ("updated_at", "@moment"), ]); let note = make(&handle, "note", json!({"title": "Template note", "body": "Invented"})); bench::cloned(&handle, "cotton_notes", ¬e, 40, &[ ("id", "printf('gold-note-%03d', i)"), ("title", "printf('Invented note %03d', i)"), ("updated_at", "@moment"), ("created_at", "@moment"), ]); handle.client().write_rows("golden.templates", &mut |ctx| { for (table, id) in [("cotton_people", &person), ("cotton_book", &book), ("cotton_notes", ¬e)] { ctx.db().exec(&format!("DELETE FROM {table} WHERE id = '{id}'")).map_err(|e| e.to_string())?; } cotton_store::derived::mark_stale(ctx.db()).map_err(|e| e.to_string())?; cotton_tools::derive::rebuild(ctx.db()).map_err(|e| e.to_string())?; Ok(Value::Null) }).expect("the templates go and the book is worked out"); (dir, handle) } /// The asks the golden answers hold: Books' first, a middle and its last /// page, searched and narrowed; People's index; Notes' months. fn golden_asks() -> Vec<(&'static str, Value)> { vec![ ("books first", json!({"table": "book"})), ("books middle", json!({"table": "book", "cursor": 100})), ("books last", json!({"table": "book", "cursor": 200})), ("books searched", json!({"table": "book", "query": "book 01"})), ("books narrowed", json!({"table": "book", "where": {"status": "reading"}})), ("books narrowed page 2", json!({"table": "book", "where": {"status": "reading"}, "cursor": 50})), ("people first", json!({"table": "person"})), ("people middle", json!({"table": "person", "cursor": 25, "limit": 20})), ("notes first", json!({"table": "note"})), ("notes last", json!({"table": "note", "cursor": 30, "limit": 20})), // Asked again with nothing changed: the kept answer, the first's. ("books first again", json!({"table": "book"})), ] } /// Every golden ask's answer, as it stands, serialised at the FFI edge. fn golden_answers() -> Value { let (_dir, handle) = golden_book(); Value::Object(golden_asks().into_iter().map(|(name, ask)| (name.to_string(), unclocked(list(&handle, ask)))).collect()) } /// The answers are the golden's byte for byte: what shell.list said before /// its rows were dressed after the cut. `SHELL_LIST_GOLDEN=write` writes them. #[test] fn answers_are_the_golden() { let path = cotton_store::manifest_dir().join("tests/fixtures/shell_list_golden.json"); let answers = serde_json::to_string_pretty(&golden_answers()).expect("serialised"); if std::env::var("SHELL_LIST_GOLDEN").as_deref() == Ok("write") { std::fs::write(&path, &answers).expect("the golden written"); return; } let golden = std::fs::read_to_string(&path).expect("the golden is there"); if golden != answers { let (golden, answers): (Value, Value) = (serde_json::from_str(&golden).expect("golden"), serde_json::from_str(&answers).expect("answers")); for (name, said) in answers.as_object().unwrap() { assert_eq!(said, &golden[name], "{name} is the golden's"); } panic!("the answers differ from the golden only in their bytes"); } } /// shell.deck's pages over the golden book, each serialised at the FFI edge. fn deck_golden_asks() -> Vec<(&'static str, Value)> { vec![ ("books deck", json!({"table": "book"})), ("books deck page 2", json!({"table": "book", "cursor": 50})), ("books deck narrowed", json!({"table": "book", "where": {"status": "reading"}})), ("people deck", json!({"table": "person"})), ("people deck middle", json!({"table": "person", "cursor": 25, "limit": 20})), ("notes deck", json!({"table": "note"})), ("notes deck inked", json!({"table": "note", "ink": "inv"})), // Asked again with nothing changed: the kept answer, the first's. ("books deck again", json!({"table": "book"})), ] } fn asked(handle: &CottonHandle, method: &str, request: &Value) -> Value { let mut request = request.clone(); request["timezone"] = json!("Asia/Kolkata"); request["today"] = json!(TODAY); crate::methods::dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} reads: {error:?}")) } /// The deck's pages are the golden's byte for byte, written before its /// answers were kept. `SHELL_LIST_GOLDEN=write` writes them. #[test] fn deck_answers_are_the_golden() { let (_dir, handle) = golden_book(); let answers = Value::Object(deck_golden_asks().into_iter().map(|(name, ask)| (name.to_string(), unclocked(asked(&handle, "shell.deck", &ask)))).collect()); let path = cotton_store::manifest_dir().join("tests/fixtures/shell_deck_golden.json"); let answers = serde_json::to_string_pretty(&answers).expect("serialised"); if std::env::var("SHELL_LIST_GOLDEN").as_deref() == Ok("write") { std::fs::write(&path, &answers).expect("the golden written"); return; } let golden = std::fs::read_to_string(&path).expect("the golden is there"); if golden != answers { let (golden, answers): (Value, Value) = (serde_json::from_str(&golden).expect("golden"), serde_json::from_str(&answers).expect("answers")); for (name, said) in answers.as_object().unwrap() { assert_eq!(said, &golden[name], "{name} is the golden's"); } panic!("the answers differ from the golden only in their bytes"); } } /// The steps every store handle on this thread ran across `body`. fn steps_of(body: impl FnOnce() -> T) -> (T, u64) { let before = cotton_store::Driver::thread_steps(); let answer = body(); (answer, cotton_store::Driver::thread_steps() - before) } // RULE (8 Nov 2026): a kept list or deck asked again // with nothing moved, or after a row of a table it does not read moved, reads // no row; after its own table moved it answers as a fresh read does. #[test] fn a_kept_list_or_deck_reads_no_row_until_its_table_moves() { let (_dir, handle) = golden_book(); // The rows a move writes: made, so their ids are the store's own. let mover = make(&handle, "book", json!({"title": "Invented mover", "author": "Invented Author", "status": "reading", "added_on": TODAY})); let person = make(&handle, "person", json!({"full_name": "Invented Mover", "language": "en"})); let note = make(&handle, "note", json!({"title": "Invented mover", "body": "Invented"})); // Rows of tables another ask may leave aside, each with the column a move changes. let others = [ ("note", "title", make(&handle, "note", json!({"title": "Invented other", "body": "Invented"}))), ("todo", "title", make(&handle, "todo", json!({"title": "Invented other"}))), ("person", "full_name", make(&handle, "person", json!({"full_name": "Invented Other", "language": "en"}))), ("event", "title", make(&handle, "event", json!({"title": "Invented other", "starts_at": "2026-11-09T10:00:00+05:30"}))), ("book", "title", make(&handle, "book", json!({"title": "Invented other", "author": "A. Writer", "status": "reading"}))), ("film", "title", make(&handle, "film", json!({"title": "Invented other", "kind": "film", "status": "want_to_watch"}))), ]; let tables = crate::methods::shell_deck::definitions(&handle.client()).expect("definitions"); let asks = [ ("shell.list", json!({"table": "book"}), "book", "title", &mover), ("shell.list", json!({"table": "person"}), "person", "full_name", &person), ("shell.list", json!({"table": "note", "cursor": 20, "limit": 10}), "note", "title", ¬e), ("shell.deck", json!({"table": "book"}), "book", "title", &mover), ("shell.deck", json!({"table": "person"}), "person", "full_name", &person), ("shell.deck", json!({"table": "note"}), "note", "title", ¬e), ]; for (round, (method, ask, table, column, id)) in asks.into_iter().enumerate() { // A kept answer is never older than its minute: a round starts well inside one. let second = handle.client().clock().now().timestamp().rem_euclid(60); if second > 45 { std::thread::sleep(std::time::Duration::from_secs((61 - second) as u64)); } // The voice context's timer says a changed vocabulary as a move, and // this test's own writes change it (a new name, a renamed row): heard // here first, a tick between the two asks finds nothing new (run 9014). crate::phone::voice_words::refresh(&handle.client()).expect("the voice context"); let heard = handle.events().buffered_events().len(); let first = asked(&handle, method, &ask); let (kept, steps) = steps_of(|| asked(&handle, method, &ask)); let since: Vec = handle.events().buffered_events().into_iter().skip(heard).filter(|event| event["kind"] != "log").collect(); assert_eq!(steps, 0, "{method} {ask}: asked again with nothing moved, no row is read (heard {since:?})"); assert_eq!(kept, first, "{method} {ask}: the kept answer is the first's"); // A row of a table the ask does not read. let definition = tables.iter().find(|found| found.id == ask["table"]).expect("the asked table"); let aside = crate::methods::shell_kept::aside(&tables, definition); let (other, other_column, other_id) = others.iter() .find(|(other, _, _)| tables.iter().find(|found| found.id == *other).is_some_and(|other| crate::methods::shell_kept::stores(other).iter().any(|store| aside.contains(store)))) .unwrap_or_else(|| panic!("{method} {ask}: some table is left aside: {aside:?}")); crate::methods::dispatch(&handle, "records.update", &json!({"table": other, "id": other_id, "patch": {*other_column: format!("Invented move {round}")}})).expect("another table moves"); let (aside, steps) = steps_of(|| asked(&handle, method, &ask)); let named = handle.events().buffered_events().iter().rev().find(|event| event["kind"] == "data").map(|event| event["payload"]["tables"].clone()); assert_eq!(steps, 0, "{method} {ask}: a move of {other} reads no row (it named {named:?})"); assert_eq!(aside, first, "{method} {ask}: and changes nothing"); // A row of its own table: read again, as a fresh read reads it. crate::methods::dispatch(&handle, "records.update", &json!({"table": table, "id": id, "patch": {column: format!("Invented own move {round}")}})).expect("its table moves"); let (moved, steps) = steps_of(|| asked(&handle, method, &ask)); assert!(steps > 0, "{method} {ask}: its own table moved, it reads again"); assert_eq!(unclocked(moved), unclocked(crate::methods::shell_kept::fresh(|| asked(&handle, method, &ask))), "{method} {ask}: after its own move, a fresh read's answer"); } } // RULE (9 Nov 2026): a definition names another table by // a value, never by a key: Todos' section `"note": "Dropped"` names no // notes, so a note's write leaves a kept Todos list standing. #[test] fn a_key_named_like_a_table_names_no_table() { let (_dir, handle) = golden_book(); let tables = crate::methods::shell_deck::definitions(&handle.client()).expect("definitions"); let todo = tables.iter().find(|found| found.id == "todo").expect("todo"); assert!(serde_json::to_string(todo).unwrap().contains("\"note\":"), "Todos still say a section's note"); let aside = crate::methods::shell_kept::aside(&tables, todo); assert!(aside.contains("cotton_notes"), "Todos leave notes aside: {aside:?}"); let note = tables.iter().find(|found| found.id == "note").expect("note"); assert!(crate::methods::shell_kept::aside(&tables, note).contains("cotton_todos"), "Notes leave todos aside"); } #[path = "shell_list_bench.rs"] mod bench; /// RULE: a numbered table's rows count from past the cursor, the archived /// not counted, a record listed twice keeping its first place, and a row /// with no title of its own is titled by its place. #[test] fn numbered_rows_say_their_place() { let row = |id: &str, title: Value, archived: bool| json!({"id": id, "slip": {"title": title, "record": {"data": {"@said": {"archived": archived, "slip": {}}}}}}); let mut sections = vec![json!({"rows": [row("a", json!("Named"), false), row("b", Value::Null, true), row("c", Value::Null, false)]}), json!({"rows": [row("a", json!("Named"), false)]})]; number_rows(&mut sections, 2, "Set"); let rows = sections[0]["rows"].as_array().unwrap(); assert_eq!(rows[0]["place"], 3); assert_eq!(rows[0]["slip"]["title"], "Named"); assert!(rows[1].get("place").is_none()); assert_eq!(rows[2]["place"], 4); assert_eq!(rows[2]["slip"]["title"], "Set 4"); assert_eq!(rows[2]["slip"]["record"]["data"]["@said"]["slip"]["title"], "Set 4"); assert_eq!(sections[1]["rows"][0]["place"], 3); } /// RULE: A route's list opens on its deck where the table has a card and the list is plain, and on the slips where it is searched, archived or one section; the answer says which face, and the shell only says whether it draws it. #[test] fn a_routes_list_says_it_is_a_deck_only_when_plain() { let (_dir, handle) = phone(); let deck = list(&handle, json!({"table": "note", "opens": true})); assert!(deck["deck"].is_string(), "a plain list of a table with a card is its deck: {deck}"); assert_eq!(list(&handle, json!({"table": "note", "opens": true, "where": {"title": "x"}}))["deck"], deck["deck"], "narrowed by a link it is still the deck"); assert!(list(&handle, json!({"table": "note", "opens": true, "query": "x"}))["deck"].is_null(), "searched: the slips"); assert!(list(&handle, json!({"table": "note", "opens": true, "archived": true}))["deck"].is_null(), "archived: the slips"); assert!(list(&handle, json!({"table": "note", "opens": true, "section": "earlier"}))["deck"].is_null(), "one section: the slips"); } /// RULE: A menu's lines say the object they stand and what they do: New an edit with no class, Select a done, anything that takes something away the bin in red, the rest named or a link that moves. #[test] fn menu_lines_say_their_card() { let mut new = json!({"id": "new", "red": false}); menu_card(&mut new); assert_eq!((new["object"].as_str(), new["does"].is_null()), (Some("edit"), true)); let mut gone = json!({"id": "x", "red": true, "object": "star"}); menu_card(&mut gone); assert_eq!((gone["object"].as_str(), gone["does"].as_str()), (Some("bin"), Some("destroys"))); let mut named = json!({"id": "menu:a", "red": false, "object": "star"}); menu_card(&mut named); assert_eq!((named["object"].as_str(), named["does"].as_str()), (Some("star"), Some("moves"))); let mut bare = json!({"id": "related:0", "red": false}); menu_card(&mut bare); assert_eq!(bare["object"], "link"); let mut act = json!({"id": "rename", "red": false, "act": {"icon": "act-edit"}}); menu_card(&mut act); assert_eq!(act["object"], "edit"); } // RULE (11 Nov 2026): a write that names its rows // patches a kept cut for those rows alone (read again, placed by the store's // own order among the kept rows), and every golden ask answers after it as a // fresh whole read does, byte for byte: after an insert, an update that moves // a row to another section and another place, a delete, and a bulk write // (which names no rows and is read whole). #[test] fn a_write_patches_the_kept_cut_as_a_whole_read_answers() { let (_dir, handle) = golden_book(); let every_ask = |handle: &CottonHandle| -> Vec<(&'static str, Value)> { golden_asks().into_iter().map(|(name, ask)| (name, unclocked(list(handle, ask)))) .chain(deck_golden_asks().into_iter().map(|(name, ask)| (name, unclocked(asked(handle, "shell.deck", &ask))))).collect() }; let fresh = |handle: &CottonHandle| crate::methods::shell_kept::fresh(|| every_ask(handle)); // Rows the writes move, made so their ids are the store's own. // Rows the writes move are notes (Money's spends were until TABLE DROP 1); the golden asks read Notes too. let note = |title: &str| make(&handle, "note", json!({"title": title, "body": "Invented"})); let (mover, leaver, goner) = (note("Invented note mover"), note("Invented note leaver"), note("Invented note goner")); let renamed = make(&handle, "person", json!({"full_name": "Mid Invented Person", "language": "en"})); // Every ask read once, so each cut is kept before the first write. every_ask(&handle); let writes: Vec<(&str, Box, &str, bool)> = vec![ ("insert", Box::new(|handle: &CottonHandle| { make(handle, "note", json!({"title": "Invented note inserted", "body": "Invented"})); }), "note", true), ("update moving its place", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.update", &json!({"table": "note", "id": mover, "patch": {"title": "Invented note moved"}})).expect("a row moves"); }), "note", true), ("update leaving the list", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.update", &json!({"table": "note", "id": leaver, "patch": {"archived_at": "2026-11-08T04:30:00.000Z"}})).expect("a row leaves"); }), "note", true), ("delete", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.delete", &json!({"table": "note", "id": goner})).expect("a row goes"); }), "note", true), ("person renamed", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.update", &json!({"table": "person", "id": renamed, "patch": {"full_name": "Zed Invented Renamed"}})).expect("a person moves"); }), "person", true), ("note made", Box::new(|handle: &CottonHandle| { make(handle, "note", json!({"title": "Invented note made", "body": "Invented"})); }), "note", true), ("bulk", Box::new(|handle: &CottonHandle| { // Rows written straight to the store name no rows: read whole. bench::cloned(handle, "cotton_book", "gold-book-0002", 30, &[("id", "printf('gold-bulk-%04d', i)"), ("added_on", "n.day")]); }), "book", false), ]; for (name, write, probe, patches) in writes { let patched_before = patched(); write(&handle); let (_, steps) = steps_of(|| list(&handle, json!({"table": probe}))); let after = every_ask(&handle); let patched_now = patched() - patched_before; let (_, whole_steps) = crate::methods::shell_kept::fresh(|| steps_of(|| list(&handle, json!({"table": probe})))); let whole = fresh(&handle); for ((ask, said), (_, read)) in after.iter().zip(&whole) { assert_eq!(said, read, "after {name}, {ask} is a whole read's answer"); } if patches { assert!(patched_now > 0, "{name} patched a kept cut"); // The steps are the 50k bench's to say (`bench::kept_asks`): over // the golden book's 240 rows a whole read costs about a patch. eprintln!("{name}: the patched {probe} read {steps} steps, a whole read {whole_steps}"); } else { assert_eq!(patched_now, 0, "{name} names no rows and is read whole"); } // Every cut kept again from a whole read, for the next write. every_ask(&handle); } } // RULE (12 Nov 2026): a write to a todo re-reads the // todo it named, never the whole plan: the kept plan (`shell_plan`) files the // named row under the section it stands in now, and every Todos list and deck // ask answers as a fresh whole read does, byte for byte: after an insert into // today, an update moving a todo to another day, one closing it (done), a // delete, and a bulk write (which names no rows and is read whole). #[test] fn a_todo_write_patches_the_kept_plan_as_a_whole_read_answers() { let (_dir, handle) = phone(); for (n, due) in ["2026-11-05T09:00:00+05:30", "2026-11-05T18:00:00+05:30", "2026-11-01T12:00:00+05:30", "2026-11-06T12:00:00+05:30", "2026-11-08T08:00:00+05:30", "2026-12-20T08:00:00+05:30"].iter().enumerate() { make(&handle, "todo", json!({"title": format!("Invented todo {n}"), "due_at": due})); } make(&handle, "todo", json!({"title": "Invented undated"})); make(&handle, "todo", json!({"title": "Invented done", "due_at": "2026-11-04T09:00:00+05:30", "status": "done"})); let mover = make(&handle, "todo", json!({"title": "Invented mover", "due_at": "2026-11-05T11:00:00+05:30"})); let closer = make(&handle, "todo", json!({"title": "Invented closer", "due_at": "2026-11-06T10:00:00+05:30"})); let goner = make(&handle, "todo", json!({"title": "Invented goner", "due_at": "2026-11-02T10:00:00+05:30"})); let template = make(&handle, "todo", json!({"title": "Invented template", "due_at": "2026-11-05T12:00:00+05:30"})); let asks: Vec<(&str, &str, Value)> = vec![ ("todos", "shell.list", json!({"table": "todo"})), ("todos paged", "shell.list", json!({"table": "todo", "limit": 1})), ("todos page 2", "shell.list", json!({"table": "todo", "cursor": 1, "limit": 1})), ("late", "shell.list", json!({"table": "todo", "section": "late"})), ("done", "shell.list", json!({"table": "todo", "section": "done"})), ("later", "shell.list", json!({"table": "todo", "section": "later"})), ("tomorrow", "shell.list", json!({"table": "todo", "section": "day:2026-11-06"})), ("todos deck", "shell.deck", json!({"table": "todo"})), ("todos deck page 2", "shell.deck", json!({"table": "todo", "cursor": 1, "limit": 1})), ]; // How long ago a todo was made or closed is the real clock's ("just now", // "1 min ago", and that moment "late" once its minute has passed today): a // kept read and a fresh one a minute tick apart differ there alone. fn unaged(mut answer: Value) -> Value { fn walk(value: &mut Value) { match value { Value::Object(map) => { map.remove("ago"); if let Some(Value::Object(parts)) = map.get_mut("@day_parts") { for made in ["created_at", "updated_at", "completed_at"] { if let Some(Value::Object(part)) = parts.get_mut(made) { part.remove("late"); } } } map.values_mut().for_each(walk); } Value::Array(items) => items.iter_mut().for_each(walk), _ => {} } } walk(&mut answer); answer } let every_ask = |handle: &CottonHandle| -> Vec<(&str, Value)> { asks.iter().map(|(name, method, ask)| (*name, unaged(unclocked(asked(handle, method, ask))))).collect() }; let fresh = |handle: &CottonHandle| crate::methods::shell_kept::fresh(|| every_ask(handle)); for ((ask, said), (_, read)) in every_ask(&handle).iter().zip(&fresh(&handle)) { assert!(said == read, "first read, {ask} is a whole read's answer: {}", difference(said, read, "")); } let writes: Vec<(&str, Box, bool)> = vec![ ("insert into today", Box::new(|handle: &CottonHandle| { make(handle, "todo", json!({"title": "Invented inserted", "due_at": "2026-11-05T07:00:00+05:30"})); }), true), ("update moving its day", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.update", &json!({"table": "todo", "id": mover, "patch": {"due_at": "2026-11-07T09:00:00+05:30", "title": "Invented moved"}})).expect("a todo moves"); }), true), ("update closing it", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.update", &json!({"table": "todo", "id": closer, "patch": {"status": "done"}})).expect("a todo is done"); }), true), ("delete", Box::new(move |handle: &CottonHandle| { crate::methods::dispatch(handle, "records.delete", &json!({"table": "todo", "id": goner})).expect("a todo goes"); }), true), ("bulk", Box::new(move |handle: &CottonHandle| { bench::cloned(handle, "cotton_todos", &template, 12, &[("id", "printf('gold-bulk-todo-%04d', i)"), ("due_at", "@moment")]); }), false), ]; for (name, write, patches) in writes { let before = crate::methods::shell_plan::patched_count(); write(&handle); every_ask(&handle); let patched_now = crate::methods::shell_plan::patched_count() - before; // Each ask off the patched plan beside a fresh whole read of it: a // slip's words say the real clock's minute (an hour just passed). for (ask, method, request) in &asks { let read = crate::methods::shell_kept::fresh(|| unaged(unclocked(asked(&handle, method, request)))); let said = unaged(unclocked(asked(&handle, method, request))); assert!(said == read, "after {name}, {ask} is a whole read's answer: {}", difference(&said, &read, "")); } if patches { assert!(patched_now > 0, "{name} patched the kept plan"); } else { assert_eq!(patched_now, 0, "{name} names no rows and is read whole"); } } } /// Where two answers first differ: the path and both values there. fn difference(said: &Value, read: &Value, at: &str) -> String { match (said, read) { (Value::Object(left), Value::Object(right)) => { for key in left.keys().chain(right.keys()) { let (one, two) = (left.get(key).unwrap_or(&Value::Null), right.get(key).unwrap_or(&Value::Null)); if one != two { return difference(one, two, &format!("{at}/{key}")); } } String::new() } (Value::Array(left), Value::Array(right)) if left.len() == right.len() => { for (n, (one, two)) in left.iter().zip(right).enumerate() { if one != two { return difference(one, two, &format!("{at}/{n}")); } } String::new() } _ => format!("{at}: {} vs {}", said.to_string().chars().take(600).collect::(), read.to_string().chars().take(600).collect::()), } }