use super::*; use crate::shell::client::phone_tests::attached; use rusqlite::types::Value as SqlValue; use serde_json::json; // RULE: A view's count comes from its complete list read, never the visible page or a composed sentence. #[test] fn a_tool_views_count_is_the_reads() { let (_dir, client) = attached(); let before = read( &client, &json!({"tool":"todos","today":"2026-10-20","timezone":"UTC"}), ) .unwrap(); let today = before["views"].as_array().unwrap().iter().find(|view| view["id"] == "today").unwrap(); assert_eq!(today["read"]["empty"]["line"], "empty_views.todos.today"); assert_eq!(today["read"]["empty"]["counts"]["late"], "empty_views.todo_late_count"); for n in 0..3 { crate::phone::records::call( &client, "records.create", &json!({"table":"todo", "data":{"title":format!("Synthetic todo {n}")}}), ) .unwrap(); } let answer = read( &client, &json!({"tool":"todos", "today":"2026-10-20", "timezone":"UTC"}), ) .unwrap(); for view in answer["views"].as_array().unwrap() { let mut request = view["read"].clone(); request["limit"] = json!(1); let list = crate::phone::records::call(&client, "records.list", &request).unwrap(); assert_eq!(view["count"], list["total"], "{}", view["id"]); assert!(view["count"].is_u64()); if view["read"]["empty"]["table"] == true { let whole = crate::phone::records::call(&client, "records.list", &json!({"table":"todo", "count_only":true, "today":"2026-10-20", "timezone":"UTC"})).unwrap(); assert_eq!(view["read"]["empty"]["total"], whole["total"]); } } let all = answer["views"] .as_array() .unwrap() .iter() .find(|view| view["id"] == "all") .unwrap(); assert_eq!(all["count"], count(&before, "all") + 3); assert_eq!( answer["views"] .as_array() .unwrap() .iter() .find(|view| view["is_default"] == true) .unwrap()["id"], "today" ); } #[test] fn generated_groups_follow_fixed_views_and_use_the_same_list() { let (_dir, client) = attached(); let person = crate::phone::records::call( &client, "records.create", &json!({"table":"person","data":{"full_name":"Synthetic Person"}}), ) .unwrap(); let id = person["record"]["id"].as_str().unwrap(); crate::phone::records::call( &client, "groups.create", &json!({"table":"person","name":"Synthetic group","records":[id]}), ) .unwrap(); // The phone's index is rebuilt beside its writes; the list reads it rebuilt. client.bring_moves_done_for_tests().unwrap(); let answer = read(&client, &json!({"tool":"people"})).unwrap(); let views = answer["views"].as_array().unwrap(); assert_eq!(views[0]["id"], "all"); assert_eq!(views[0]["is_default"], true); // The group follows every fixed view (All, Between us). let group = views.last().unwrap(); assert_eq!(group["label"], "Synthetic group"); assert_eq!(group["is_default"], false); assert!(views[..views.len() - 1].iter().all(|view| !view["id"].as_str().unwrap().starts_with("group:"))); for view in views { let list = crate::phone::records::call(&client, "records.list", &view["read"]).unwrap(); assert_eq!(view["count"], list["total"]); if view["id"].as_str().unwrap().starts_with("group:") { assert_eq!(view["count"], 1); } } } // RULE: An empty named group is not an empty table. #[test] fn an_empty_group_carries_its_name_and_the_whole_tables_count() { let (_dir, client) = attached(); crate::phone::records::call(&client, "records.create", &json!({"table":"person","data":{"full_name":"Synthetic person"}})).unwrap(); crate::phone::records::call(&client, "groups.create", &json!({"table":"person","name":"Synthetic empty group"})).unwrap(); client.bring_moves_done_for_tests().unwrap(); let answer = read(&client, &json!({"tool":"people"})).unwrap(); let group = answer["views"].as_array().unwrap().iter().find(|view| view["label"] == "Synthetic empty group").unwrap(); assert_eq!(group["count"], 0); assert_eq!(group["read"]["empty"]["line"], "empty_views.named"); assert_eq!(group["read"]["empty"]["view"], "Synthetic empty group"); let whole = crate::phone::records::call(&client, "records.list", &json!({"table":"person","count_only":true})).unwrap(); assert_eq!(group["read"]["empty"]["total"], whole["total"]); assert!(whole["total"].as_u64().unwrap() > 0); } #[test] fn date_views_use_the_reader_day_including_later_recurrences() { let (_dir, client) = attached(); let before = read( &client, &json!({"tool":"todos","today":"2026-10-20","timezone":"UTC"}), ) .unwrap(); let calendar_before = read( &client, &json!({"tool":"calendar","today":"2026-10-20","timezone":"UTC"}), ) .unwrap(); for (title, day) in [ ("Today", "2026-10-20"), ("Late", "2026-10-19"), ("Upcoming", "2026-10-21"), ] { crate::phone::records::call( &client, "records.create", &json!({"table":"todo","data":{"title":title,"due_at":format!("{day}T12:00:00.000Z")}}), ) .unwrap(); } let answer = read( &client, &json!({"tool":"todos","today":"2026-10-20","timezone":"UTC"}), ) .unwrap(); for view in answer["views"].as_array().unwrap() { let id = view["id"].as_str().unwrap(); let added = match id { "done" => 0, "all" => 3, _ => 1, }; assert_eq!(view["count"], count(&before, id) + added, "{}", view["id"]); } let workspace = client .with_writer(|file| Ok(file.workspace_id.to_string())) .unwrap(); seed(&client, "INSERT INTO cotton_collections (id,workspace_id,kind,name,created_at) VALUES ('00000000-0000-4000-8000-000000000101',?,'calendar','Synthetic calendar','2026-10-20T00:00:00.000Z')", &[rusqlite::types::Value::Text(workspace)]); for (title, starts) in [ ("One-off", "2026-10-20T14:00:00Z"), ("Weekly", "2026-10-13T14:00:00Z"), ] { let mut data = json!({"title":title,"starts_at":starts,"ends_at":starts.replace("14:00", "15:00")}); if title == "Weekly" { data["rrule"] = json!("FREQ=WEEKLY"); } crate::phone::records::call( &client, "records.create", &json!({"table":"event","data":data}), ) .unwrap(); } let answer = read( &client, &json!({"tool":"calendar","today":"2026-10-20","timezone":"UTC"}), ) .unwrap(); for view in answer["views"].as_array().unwrap() { let list = crate::phone::records::call(&client, "records.list", &view["read"]).unwrap(); assert_eq!(view["count"], list["total"]); if view["id"] == "today" { assert_eq!(view["count"], count(&calendar_before, "today") + 2); } if view["id"] == "upcoming" { assert!(view["count"].as_u64().unwrap() > 1); } } } // RULE: The read follows edited definition order, labels and default; hard-coded tool cases would discard the owner's data. #[test] fn tool_view_order_is_the_definitions() { let (_dir, client) = attached(); let definition = cotton_core::definitions::builtin_table_definitions() .iter() .find(|table| table.id == "todo") .unwrap(); let mut tool = serde_json::to_value(definition.tool.as_ref().unwrap()).unwrap(); let declared = tool["views"].as_array_mut().unwrap(); declared.reverse(); declared[0]["label"] = json!("Everything to do"); for (index, view) in declared.iter_mut().enumerate() { view["is_default"] = json!(index == 0); } let expected = declared.clone(); crate::phone::records::call( &client, "definitions.saveTable", &json!({"table":"todo","tool":tool}), ) .unwrap(); let answer = read(&client, &json!({"tool":"todos"})).unwrap(); let actual = answer["views"].as_array().unwrap(); for (view, declared) in actual.iter().zip(&expected) { for key in ["id", "label", "is_default"] { assert_eq!(view[key], declared[key]); } } assert_eq!(actual.len(), expected.len()); } fn seed(client: &ClientController, sql: &str, params: &[rusqlite::types::Value]) { client .with_writer(|file| { file.driver .run(sql, params) .map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, sql); Ok(()) }) .unwrap(); } #[test] fn generated_albums_follow_the_photos_default_and_count_their_list() { use rusqlite::types::Value as Sql; let (_dir, client) = attached(); let workspace = client .with_writer(|file| Ok(file.workspace_id.to_string())) .unwrap(); let at = "2026-10-20T08:00:00.000Z"; let hash = "a".repeat(64); let photo = format!("photo:{hash}"); let album = "album:trip:2026-10-20"; seed(&client,"INSERT INTO cotton_photos (id,workspace_id,key,sha256,content_type,size_bytes,taken_at,created_at,updated_at) VALUES (?,?,?,?,'image/jpeg',2048,?,?,?)",&[Sql::Text(photo.clone()),Sql::Text(workspace.clone()),Sql::Text(format!("{workspace}/photos/{hash}.jpg")),Sql::Text(hash),Sql::Text(at.into()),Sql::Text(at.into()),Sql::Text(at.into())]); seed(&client,"INSERT INTO cotton_media_albums (id,workspace_id,kind,state,title,title_by,starts_at,ends_at,created_at,updated_at) VALUES (?,?,'trip','open','Synthetic trip','user','2026-10-20','2026-10-20',?,?)",&[Sql::Text(album.into()),Sql::Text(workspace),Sql::Text(at.into()),Sql::Text(at.into())]); crate::phone::records::call( &client, "records.create", &json!({"table":"album_item","data":{"album_id":album,"record_id":photo}}), ) .unwrap(); let answer = read(&client, &json!({"tool":"photos"})).unwrap(); let views = answer["views"].as_array().unwrap(); let ids: Vec<&str> = views.iter().map(|view| view["id"].as_str().unwrap()).collect(); let fixed = ["all", "albums", "favourites", "videos", "on_phone"]; assert_eq!(ids[..fixed.len()], fixed, "the fixed views first, in the definition's order"); assert_eq!(views[0]["is_default"], true); assert_eq!(views[fixed.len()]["label"], "Synthetic trip", "then each album"); for view in views { let list = crate::phone::records::call(&client, "records.list", &view["read"]).unwrap(); assert_eq!(view["count"], list["total"]); } for id in ["all", "albums"] { assert_eq!(views.iter().find(|view| view["id"] == id).unwrap()["count"], 1, "{id}"); } assert_eq!(views[fixed.len()]["count"], 1); } #[test] fn shipped_database_views_have_readable_counts() { let (_dir, client) = attached(); for table in cotton_core::definitions::builtin_table_definitions() { let Some(tool) = &table.tool else { continue }; // Everything's rows include native host facts: its handle-bound read is tested by that engine. if crate::phone::records::settings_tables::TABLES .iter() .any(|(id, _)| *id == table.id) { continue; } let key = tool.key.as_deref().unwrap_or(&table.id); let answer = read(&client, &json!({"tool":key})).unwrap_or_else(|e| panic!("{key}: {e:?}")); assert!(answer["views"] .as_array() .unwrap() .iter() .all(|view| view["count"].is_u64())); } } fn count(answer: &Value, id: &str) -> u64 { answer["views"] .as_array() .unwrap() .iter() .find(|view| view["id"] == id) .unwrap()["count"] .as_u64() .unwrap() } // RULE: Reading a built-in's views depends on its own definition, so a broken imported tool cannot hide Todos. #[test] fn an_unrelated_imported_definition_cannot_hide_builtin_views() { use rusqlite::types::Value as Sql; let (_dir, client) = attached(); let workspace = client .with_writer(|file| Ok(file.workspace_id.to_string())) .unwrap(); seed(&client, "INSERT INTO cotton_tool_definitions (id,workspace_id,definition,builtin,instructions_edited,created_at,updated_at) VALUES ('broken',?,'{}',0,0,'2026-10-20T00:00:00.000Z','2026-10-20T00:00:00.000Z')", &[Sql::Text(workspace)]); let answer = read(&client, &json!({"tool":"todos"})).unwrap(); assert!(answer["views"] .as_array() .unwrap() .iter() .any(|view| view["is_default"] == true)); } // GUARD (22 Oct 2026): a tool's view over another tool's // table is headed by the viewing tool's own name and draws the view's own // slip — Artifacts over Documents' document table said "Documents", "Search // documents", the document kind "Other" and an absolute date, because the // list fell back to the table's plural and the table's slip. The core answers // the heading, the search words and the slip, so every reader draws the same. #[test] #[ignore = "TABLE DROP 1: the artifacts tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"] fn a_view_over_another_tools_table_is_headed_by_its_own_name() { let (_dir, client) = attached(); let answer = read(&client, &json!({"tool":"artifacts","today":"2026-10-22","timezone":"UTC"})).unwrap(); let made = answer["views"].as_array().unwrap().iter().find(|view| view["id"] == "made").unwrap(); assert_eq!(made["read"]["table"], "document"); assert_eq!(made["title"], "Web pages"); assert_eq!(made["search"], "Search web pages"); assert_eq!(made["slip"]["caption"]["dates"], json!(["created_at"])); assert!(made["slip"]["subtitle"].is_null(), "the view's slip names no kind"); // The table's own tool keeps its own name over its own table. let documents = read(&client, &json!({"tool":"documents","today":"2026-10-22","timezone":"UTC"})).unwrap(); assert!(documents["views"].as_array().unwrap().iter().all(|view| view["title"] == "Documents")); } // GUARD (Money's By person, 6 Nov 2026): a view's own card crosses with // the view, as its slip and tile do — the shell draws a view as a deck only // when the view it was handed carries a card (`DeckSwitch`), so a view whose // card stood only in the core (By person's group face, Owed's receipt) was // drawn as the table's slip list over the core's group cards, which say no // slip words: four blank cream slips, one per person. #[test] fn a_views_own_card_crosses_with_the_view() { let (_dir, client) = attached(); let answer = read(&client, &json!({"tool":"money","today":"2026-11-06","timezone":"UTC"})).unwrap(); let view = |id: &str| answer["views"].as_array().unwrap().iter().find(|view| view["id"] == id).cloned().unwrap_or_else(|| panic!("no view {id}: {answer}")); let by_person = view("by_person"); assert_eq!(by_person["card"]["face"], "group", "{by_person}"); let people = by_person["card"]["fields"].as_array().unwrap().iter().find(|field| field["slot"] == "people").cloned(); assert_eq!(people.map(|field| field["column"].clone()), Some(json!("counterparty_person_id"))); assert_eq!(view("owed")["card"]["face"], "transaction.receipt"); assert!(view("past")["card"].is_null(), "a view naming no card leaves the table's"); } // RULE: a table's own empty words are its owner's. A view over another // tool's table says its own line however empty that table is: Web pages' // Made for you over Documents' empty document table says "No pages made for // you yet.", never "No documents yet…", so it carries no whole-table total to // fall back on. A tool over its own table (Todos' Today, Web pages' All over // its page table) keeps the fallback. // // WHY: Cotton 348's walk — the Web pages tool drew Documents' empty card. #[test] #[ignore = "TABLE DROP 1: the artifacts tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"] fn a_view_over_another_tools_empty_table_says_its_own_line() { let (_dir, client) = attached(); let whole = crate::phone::records::call(&client, "records.list", &json!({"table":"document","count_only":true})).unwrap(); assert_eq!(whole["total"], 0, "the document table is empty"); let answer = read(&client, &json!({"tool":"artifacts","today":"2026-10-22","timezone":"UTC"})).unwrap(); let made = answer["views"].as_array().unwrap().iter().find(|view| view["id"] == "made").unwrap(); assert_eq!(made["count"], 0); assert_eq!(made["read"]["empty"]["line"], "empty_views.artifacts.made"); assert!(made["read"]["empty"].get("table").is_none() && made["read"]["empty"].get("total").is_none(), "{made}"); let all = answer["views"].as_array().unwrap().iter().find(|view| view["id"] == "all").unwrap(); assert_eq!(all["read"]["table"], "page", "Web pages' own links are its home"); assert_eq!(all["read"]["empty"]["table"], true); let todos = read(&client, &json!({"tool":"todos","today":"2026-10-22","timezone":"UTC"})).unwrap(); let today = todos["views"].as_array().unwrap().iter().find(|view| view["id"] == "today").unwrap(); assert_eq!(today["read"]["empty"]["table"], true); assert!(today["read"]["empty"]["total"].is_u64(), "{today}"); } // RULE: The Calendar's Today and Upcoming draw the events the copy holds, in no calendar at all — the object keeps none and serves its events naming one the copy never holds — each on the reader's own day. #[test] fn today_and_upcoming_draw_the_events_the_copy_holds_in_no_calendar() { let (_dir, client) = attached(); let calendars = client .with_writer(|file| { Ok(file .driver .get("SELECT count(*) AS n FROM cotton_collections", &[]) .map_err(|error| error.to_string())? .and_then(|row| row.int("n"))) }) .unwrap(); assert_eq!(calendars, Some(0), "the copy holds no calendar"); // Now is 27 Oct 2026 in Kolkata (UTC+5:30). for (id, collection, starts, ends, all_day, rrule, zone) in [ ("e-today", None, "2026-10-27T06:00:00.000Z", "2026-10-27T07:00:00.000Z", 0, None, None), // Named under a calendar the copy never holds, as the object serves it. ("e-tomorrow", Some("a-calendar-never-served"), "2026-10-28T06:00:00.000Z", "2026-10-28T07:00:00.000Z", 0, None, None), ("e-next-week", None, "2026-11-03T06:00:00.000Z", "2026-11-03T07:00:00.000Z", 0, None, None), ("e-last-week", None, "2026-10-20T06:00:00.000Z", "2026-10-20T07:00:00.000Z", 0, None, None), ("e-all-day", None, "2026-10-27T00:00:00.000Z", "2026-10-28T00:00:00.000Z", 1, None, None), // 26 Oct in its own zone and in UTC; 01:30 on the 27th for the reader. ("e-elsewhere", None, "2026-10-26T20:00:00.000Z", "2026-10-26T21:00:00.000Z", 0, None, Some("America/Los_Angeles")), // A weekly series begun two weeks ago whose last occurrence is today. ("e-weekly", None, "2026-10-13T06:00:00.000Z", "2026-10-13T07:00:00.000Z", 0, Some("FREQ=WEEKLY;COUNT=3"), None), ] { use rusqlite::types::Value as V; let text = |value: Option<&str>| value.map_or(V::Null, |value| V::Text(value.to_string())); seed( &client, "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, rrule, timezone, created_at, updated_at) \ VALUES (?, ?, 'Synthetic event', ?, ?, ?, ?, ?, '2026-10-20T00:00:00.000Z', '2026-10-20T00:00:00.000Z')", &[V::Text(id.into()), text(collection), V::Text(starts.into()), V::Text(ends.into()), V::Integer(all_day), text(rrule), text(zone)], ); } let answer = read(&client, &json!({"tool":"calendar","today":"2026-10-27","timezone":"Asia/Kolkata"})).unwrap(); let drawn = |id: &str| { let view = answer["views"].as_array().unwrap().iter().find(|view| view["id"] == id).unwrap().clone(); let list = crate::phone::records::call(&client, "records.list", &view["read"]).unwrap(); assert_eq!(view["count"], list["total"], "{id}"); let mut ids: Vec = list["records"] .as_array() .unwrap() .iter() .map(|record| record["id"].as_str().unwrap().to_string()) .collect(); ids.sort(); ids }; assert_eq!(drawn("today"), ["e-all-day", "e-elsewhere", "e-today", "e-weekly@2026-10-27T06:00:00.000Z"], "the series is drawn by its occurrence today"); assert_eq!(drawn("upcoming"), ["e-next-week", "e-tomorrow"]); assert_eq!(drawn("all").len(), 7); } // RULE: Memories counts and lists its active memories under All and its archived ones under Archived, the archive a plain list leaves out. #[test] fn memories_reads_its_archive_under_archived() { let (_dir, client) = attached(); for (n, archived) in [(1, false), (2, false), (3, true)] { let (status, at) = if archived { ("archived", SqlValue::Text("2026-10-02T00:00:00.000Z".into())) } else { ("active", SqlValue::Null) }; client .with_writer(|file| { let sql = "INSERT INTO cotton_memories (id, workspace_id, slug, title, body, status, archived_at, visibility, origin_kind, created_at, updated_at) \ VALUES (?, ?, ?, ?, '', ?, ?, 'private', 'user', '2026-10-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z')"; let params = vec![ SqlValue::Text(format!("aaaaaaaa-0000-4000-8000-00000000000{n}")), SqlValue::Text(file.workspace_id.to_string()), SqlValue::Text(format!("synthetic-{n}")), SqlValue::Text(format!("Synthetic memory {n}")), SqlValue::Text(status.into()), at.clone(), ]; file.driver.run(sql, ¶ms).map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, sql); Ok(()) }) .expect("a synthetic memory"); } let answer = read(&client, &json!({"tool":"memories","timezone":"UTC"})).unwrap(); assert_eq!(count(&answer, "all"), 2, "{answer}"); assert_eq!(count(&answer, "archived"), 1, "{answer}"); let archive = crate::phone::records::call(&client, "records.list", &json!({"table":"memory","view":"memories/archived","where":{"status":"archived"}})).unwrap(); let titles: Vec<&str> = archive["records"].as_array().unwrap().iter().filter_map(|record| record["data"]["title"].as_str()).collect(); assert_eq!(titles, ["Synthetic memory 3"], "{archive}"); } /// The Books tool with Finished's year head and the lists before On this /// phone (owner, 4 Nov 2026), stored over the kit's. fn books_with_head(client: &ClientController) { let mut tool: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tools/books/manifest.json")).unwrap(); for view in tool["views"].as_array_mut().unwrap() { match view["id"].as_str() { Some("finished") => { view["head"] = json!({"period": "this_year", "line": "list.this_year", "goal": {"table": "face_settings", "row": "reader", "column": "year_goal", "line": "list.this_year_of_goal"}}); } Some("on_phone") => view["lists_before"] = json!(true), _ => {} } } let definition: cotton_core::definitions::ToolDefinition = serde_json::from_value(tool.clone()).unwrap(); definition.validate().expect("the head and the lists' place validate"); let workspace = client.with_writer(|file| Ok(file.workspace_id.to_string())).unwrap(); seed( client, "INSERT OR REPLACE INTO cotton_tool_definitions (id, workspace_id, definition, created_at, updated_at) \ VALUES ('books', ?, ?, '2026-11-04T09:00:00.000Z', '2026-11-04T09:00:00.000Z')", &[SqlValue::Text(workspace), SqlValue::Text(tool.to_string())], ); } /// The lists table as the object syncs it to a phone, with its `send` shape: a list is sent from its tile. fn lists_kept(client: &ClientController) { let workspace = client.with_writer(|file| Ok(file.workspace_id.to_string())).unwrap(); seed( client, "INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) \ VALUES ('record_group', ?, ?, 0, 0, '2026-11-13', '2026-11-13')", &[SqlValue::Text(workspace), SqlValue::Text(include_str!("../../../cotton-core/kits/personal/tables/record_group.json").to_string())], ); } fn a_book(client: &ClientController, data: Value) -> String { let made = crate::phone::records::call(client, "records.create", &json!({"table": "book", "data": data})).unwrap(); made["record"]["id"].as_str().unwrap().to_string() } // RULE (owner, 4 Nov 2026): Finished's head counts the books finished this year, against the reader's year goal when one is kept; the lists stand before On this phone; each fixed view carries its painted tile, a list none. #[test] fn finished_counts_the_year_and_the_lists_stand_before_on_this_phone() { let (_dir, client) = attached(); books_with_head(&client); for (title, day) in [("Synthetic Atlas", "2026-03-01"), ("Synthetic Harbour", "2026-10-01"), ("Synthetic Last Year", "2025-12-31")] { a_book(&client, json!({"title": title, "status": "finished", "finished_on": day})); } let reading = a_book(&client, json!({"title": "Synthetic Reading", "status": "reading"})); crate::phone::records::call(&client, "groups.create", &json!({"table": "book", "name": "Synthetic favourites", "records": [reading]})).unwrap(); client.bring_moves_done_for_tests().unwrap(); let read = |client: &ClientController| super::read(client, &json!({"tool": "books", "today": "2026-11-04", "timezone": "UTC"})).unwrap(); let answer = read(&client); let views = answer["views"].as_array().unwrap(); let ids: Vec<&str> = views.iter().map(|view| view["id"].as_str().unwrap()).collect(); let at = |id: &str| ids.iter().position(|held| *held == id).unwrap(); let list = ids.iter().position(|id| id.starts_with("group:")).expect("the list is a view"); assert_eq!((at("highlights") + 1, list + 1), (list, at("on_phone")), "{ids:?}"); assert_eq!(*ids.last().unwrap(), "all"); let finished = views.iter().find(|view| view["id"] == "finished").unwrap(); assert_eq!(finished["count"], 3); assert_eq!(finished["head"], "2 this year", "last year's book is not this year's"); assert!(views.iter().filter(|view| view["id"] != "finished" && view["id"] != "on_phone").all(|view| view["head"].is_null())); assert_eq!(views.iter().find(|view| view["id"] == "on_phone").unwrap()["head"], "0\u{a0}books · 0\u{a0}B · not synced\u{a0}yet"); // Each view's painted tile crosses for the fan to draw (Round 17); a list carries none. let picture = |id: &str| views.iter().find(|view| view["id"] == id).unwrap()["picture"].clone(); assert_eq!((picture("reading"), picture("on_phone"), picture("all")), (json!("open_book"), json!("keypad_phone"), json!("book_pile"))); assert!(views[list]["picture"].is_null(), "a list's tile is the plain card"); crate::phone::records::call(&client, "records.create", &json!({"table": "face_settings", "id": "reader", "data": {"table": "reader", "face": "reader.original", "year_goal": 24}})).unwrap(); let answer = read(&client); let finished = answer["views"].as_array().unwrap().iter().find(|view| view["id"] == "finished").unwrap(); assert_eq!(finished["head"], "2 of 24 this year"); } // RULE: a head counts a view's rows in a period by its table's date — a view whose read keeps a period of its own, or whose table has no date, is refused — and one view at most says where the lists stand. #[test] fn a_head_and_the_lists_place_are_checked_when_authored() { let tool: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tools/books/manifest.json")).unwrap(); let with = |change: &dyn Fn(&mut Value)| { let mut tool = tool.clone(); change(&mut tool); serde_json::from_value::(tool).unwrap().validate() }; assert!(with(&|tool| tool["views"][2]["head"] = json!({"period": "this_year", "line": "list.this_year"})).is_ok()); assert!(with(&|tool| { tool["views"][2]["head"] = json!({"period": "this_year", "line": "list.this_year"}); tool["views"][2]["read"]["period"] = json!("this_month"); }).is_err()); assert!(with(&|tool| tool["views"][2]["head"] = json!({"period": "next_day", "line": "list.this_year"})).is_err()); assert!(with(&|tool| { tool["views"][1]["lists_before"] = json!(true); tool["views"][2]["lists_before"] = json!(true); }).is_err()); let book: cotton_core::definitions::TableDefinition = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/book.json")).unwrap(); let mut dateless = book.clone(); dateless.date = None; let views: Vec = serde_json::from_value(json!([{"id": "finished", "label": "Finished", "is_default": true, "read": {"table": "book"}, "head": {"period": "this_year", "line": "list.this_year"}}])).unwrap(); assert!(cotton_core::definitions::tool_views::validate_public_reads(&views, &[book]).is_ok()); assert!(cotton_core::definitions::tool_views::validate_public_reads(&views, &[dateless]).is_err()); } // RULE: a link shared into the app is a `page` row, and the page table is // Web pages' own: its default view reads it and the share closes on that // card (`ShareIntake.pages`, `.tableRecord(table: "page")`). The kit defines // `page` through the Web pages tool, so a phone that holds the kit holds it. // // WHY: 4 Nov 2026 — a URL shared into Cotton filed a `page` // row no tool shipped, and the share ended on "This app cannot show these // records". #[test] #[ignore = "TABLE DROP 1: the artifacts tool is retired (GONE_TOOLS) and the Cotton manifest no longer names it (RUST GREEN 2)"] fn a_shared_link_is_a_card_on_web_pages_own_view() { let (_dir, client) = attached(); let request = json!({"url": "https://example.test/a/page", "title": "A page"}); let pages = crate::phone::page::validate_pages(&request).unwrap(); client.write_rows("page.save", &mut |ctx| crate::phone::page::write_pages(ctx, &pages)).unwrap(); let answer = read(&client, &json!({"tool":"artifacts","today":"2026-10-22","timezone":"UTC"})).unwrap(); let all = answer["views"].as_array().unwrap().iter().find(|view| view["id"] == "all").unwrap(); assert_eq!(all["read"]["table"], "page"); assert_eq!(all["count"], 1, "{all}"); let kit = cotton_core::kit::package("artifacts").unwrap().unwrap().package; let page = kit.tables.iter().find(|table| table.id == "page").expect("Web pages carries page"); assert_eq!(page.card.as_ref().map(|card| card.face.as_str()), Some("page.clipping"), "the card the share closes on: a kept page's clipping"); assert_eq!(page.tool.as_ref().and_then(|tool| tool.route.as_deref()), None, "Web pages opens on its own views, never a screen of the table's"); } // RULE (5 Nov 2026): a list's tile is made from its contents — `stack` is the first three members' pictures in the list's order (a member with no picture left out), `cover` the person's own picture, which `groups.update {picture}` sets and a null takes off; the list's deck offers Set picture, and Remove picture while it has one. #[test] fn a_lists_tile_stacks_its_first_covers_and_takes_its_own_picture() { let (_dir, client) = attached(); books_with_head(&client); lists_kept(&client); let file = client.with_file(|file| Ok(file.identity.id().to_string())).unwrap(); let cover = |n: char| format!("{file}/photos/{}.jpg", n.to_string().repeat(64)); let first = a_book(&client, json!({"title": "Synthetic First", "status": "reading", "cover": cover('a')})); let bare = a_book(&client, json!({"title": "Synthetic Bare", "status": "reading"})); let third = a_book(&client, json!({"title": "Synthetic Third", "status": "reading", "cover": cover('c')})); let fourth = a_book(&client, json!({"title": "Synthetic Fourth", "status": "reading", "cover": cover('d')})); let made = crate::phone::records::call(&client, "groups.create", &json!({"table": "book", "name": "Synthetic shelf", "records": [first, bare, third, fourth]})).unwrap(); let group = made["group"]["id"].as_str().unwrap().to_string(); crate::phone::records::call(&client, "groups.create", &json!({"table": "book", "name": "Synthetic empty shelf"})).unwrap(); client.bring_moves_done_for_tests().unwrap(); let list = |client: &ClientController, name: &str| { let answer = super::read(client, &json!({"tool": "books", "today": "2026-11-05", "timezone": "UTC"})).unwrap(); answer["views"].as_array().unwrap().iter().find(|view| view["label"] == name).cloned().unwrap() }; let shelf = list(&client, "Synthetic shelf"); assert_eq!(shelf["stack"], json!([cover('a'), cover('c')]), "the first three members' covers, the bare one left out, the fourth not reached"); assert!(shelf["cover"].is_null()); assert_eq!(list(&client, "Synthetic empty shelf")["stack"], json!([]), "an empty list stacks nothing: the default tile"); let view = format!("books/group:{group}"); let acts = |client: &ClientController| -> Vec { let answer = crate::phone::tool_acts::acts(client, &json!({"table": "book", "view": view})).unwrap(); answer["actions"].as_array().unwrap().iter().filter(|act| act["group"] == json!(group)).map(|act| act["label"].as_str().unwrap().to_string()).collect() }; assert_eq!(acts(&client), ["Rename", "Set picture from Photos", "Move later", "Send", "Remove list"]); let own = format!("{file}/documents/{}.png", "e".repeat(64)); let set = crate::phone::records::call(&client, "groups.update", &json!({"id": group, "picture": own})).unwrap(); assert_eq!(set["change"]["receipt"]["said"], "Gave Synthetic shelf a picture"); assert_eq!(set["group"]["picture"], json!(own)); let shelf = list(&client, "Synthetic shelf"); assert_eq!((shelf["cover"].clone(), shelf["stack"].clone()), (json!(own), json!([cover('a'), cover('c')])), "the stack stays for the tile to fall back on"); assert_eq!(acts(&client), ["Rename", "Set picture from Photos", "Remove picture", "Move later", "Send", "Remove list"]); let refused = crate::phone::records::call(&client, "groups.update", &json!({"id": group, "picture": "another-database/photos/x.jpg"})).unwrap_err(); assert!(refused.message.contains("picture is the media key"), "{}", refused.message); let off = crate::phone::tool_acts::call(&client, &json!({"tool": "books", "act": "list_remove_picture", "group": group})).unwrap(); assert_eq!(off["said"], "Took Synthetic shelf's picture off"); assert!(list(&client, "Synthetic shelf")["cover"].is_null()); assert_eq!(acts(&client), ["Rename", "Set picture from Photos", "Move later", "Send", "Remove list"]); let picker = crate::phone::tool_acts::call(&client, &json!({"tool": "books", "act": "list_set_picture", "group": group})).unwrap(); assert_eq!(picker, json!({"platform_action": "open_picker", "picker": "photos", "for": "list", "group": group})); } /// The labels of a list's acts as its tile held on the fan's lists tier answers them. fn held_list_acts(client: &ClientController, group: &str) -> Vec { let answer = crate::phone::tool_acts::acts(client, &json!({"table": "book", "view": format!("books/group:{group}"), "held": "list"})).unwrap(); answer["actions"].as_array().unwrap().clone() } fn labels(acts: &[Value]) -> Vec<&str> { acts.iter().map(|act| act["label"].as_str().unwrap()).collect() } /// The lists on Books' fan, by name, in their order. fn list_names(client: &ClientController) -> Vec { let answer = super::read(client, &json!({"tool": "books", "today": "2026-11-07", "timezone": "UTC"})).unwrap(); answer["views"].as_array().unwrap().iter().filter(|view| view["id"].as_str().is_some_and(|id| id.starts_with("group:"))).map(|view| view["label"].as_str().unwrap().to_string()).collect() } // RULE (list-acts, 7 Nov 2026): a list is a whole thing — its tile held on the fan's lists tier and its own deck answer the same acts from one function, in order: Rename (the short-text input, prefilled with its name), Set picture, Remove picture while it has one, Move earlier and Move later (absent at the end it cannot pass, never refused), Remove list red, last and asked first. A new list lands last; a move and a removal are undone by the change they answer; a removed list leaves the fan and its counts at once, its books untouched. #[test] fn a_list_is_renamed_moved_and_removed_from_its_held_tile() { let (_dir, client) = attached(); books_with_head(&client); lists_kept(&client); let book = a_book(&client, json!({"title": "Synthetic Kept", "status": "reading"})); let make = |name: &str, records: Value| crate::phone::records::call(&client, "groups.create", &json!({"table": "book", "name": name, "records": records})).unwrap()["group"]["id"].as_str().unwrap().to_string(); let first = make("Synthetic first", json!([book])); let second = make("Synthetic second", Value::Null); assert_eq!(list_names(&client), ["Synthetic first", "Synthetic second"], "a new list lands last"); let acts = held_list_acts(&client, &first); assert_eq!(labels(&acts), ["Rename", "Set picture from Photos", "Move later", "Send", "Remove list"], "the first cannot move earlier: absent, not refused"); // RULE (Send, 13 Nov 2026): a held list is sent from its tile: Send's step on the list's own record. let send = acts.iter().find(|act| act["id"] == "send").expect("a list can be sent"); assert_eq!((send["kind"].as_str(), send["step"].as_str(), send["table"].as_str(), send["record"].as_str()), (Some("chooser"), Some("send"), Some("record_group"), Some(first.as_str()))); assert_eq!(acts[0]["words"], json!({"prefill": "Synthetic first", "hint": "List name"}), "Rename asks in the short-text input, holding the name"); let remove = acts.last().unwrap(); assert_eq!((remove["red"].clone(), remove["asks"].clone()), (json!(true), json!(true)), "Remove list is red and asked first"); assert_eq!(labels(&held_list_acts(&client, &second)), ["Rename", "Set picture from Photos", "Move earlier", "Send", "Remove list"]); let on_deck = crate::phone::tool_acts::acts(&client, &json!({"table": "book", "view": format!("books/group:{first}")})).unwrap(); let on_deck: Vec = on_deck["actions"].as_array().unwrap().iter().filter(|act| act["group"] == json!(first)).cloned().collect(); assert_eq!(on_deck, acts, "the list's own deck answers the same acts"); let run = |act: &str, extra: Value| { let mut asked = json!({"tool": "books", "act": act, "group": first}); asked.as_object_mut().unwrap().extend(extra.as_object().cloned().unwrap_or_default()); crate::phone::tool_acts::call(&client, &asked) }; let empty = run("list_rename", json!({"words": " "})).unwrap_err(); assert_eq!(empty.message, "Give the list a name."); let taken = run("list_rename", json!({"words": "synthetic SECOND"})).unwrap_err(); assert_eq!(taken.message, "There is already a list called synthetic SECOND."); let renamed = run("list_rename", json!({"words": " Synthetic renamed "})).unwrap(); assert_eq!(renamed["said"], "Renamed Synthetic first to Synthetic renamed"); assert!(renamed["undo"].is_string(), "{renamed}"); let moved = run("list_move_later", json!({})).unwrap(); assert_eq!(moved["said"], "Moved Synthetic renamed"); assert_eq!(list_names(&client), ["Synthetic second", "Synthetic renamed"]); assert_eq!(labels(&held_list_acts(&client, &first)), ["Rename", "Set picture from Photos", "Move earlier", "Send", "Remove list"]); crate::phone::records::call(&client, "records.undo", &json!({"change_id": moved["undo"]})).unwrap(); assert_eq!(list_names(&client), ["Synthetic renamed", "Synthetic second"], "undo puts the list back"); let removed = run("list_remove", json!({})).unwrap(); assert!(removed["said"].as_str().unwrap().contains("Synthetic renamed"), "{removed}"); assert_eq!(list_names(&client), ["Synthetic second"], "the fan forgets a removed list at once"); assert!(held_list_acts(&client, &first).is_empty(), "a list no longer here offers nothing"); let kept = crate::phone::records::call(&client, "records.get", &json!({"table": "book", "id": book})).unwrap(); assert!(kept.pointer("/deleted_at").is_none_or(Value::is_null), "its books are untouched: {kept}"); crate::phone::records::call(&client, "records.undo", &json!({"change_id": removed["undo"]})).unwrap(); assert_eq!(list_names(&client), ["Synthetic renamed", "Synthetic second"], "undo brings it back in its place"); let back = super::read(&client, &json!({"tool": "books", "only": format!("group:{first}"), "today": "2026-11-07", "timezone": "UTC"})).unwrap(); assert_eq!(back["views"][0]["count"], 1, "with its members"); } // RULE: a table whose face draws no picture stacks nothing on its lists' tiles. #[test] fn a_table_with_no_picture_place_stacks_nothing() { let (_dir, client) = attached(); let mut found = None; client.read_rows("test", &mut |ctx| { let definitions = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?; found = Some(definitions.definitions.iter().map(|table| (table.id.clone(), face_picture(table).map(str::to_string))).collect::>()); Ok(Value::Null) }).unwrap(); let found = found.unwrap(); let of = |id: &str| found.iter().find(|(table, _)| table == id).map(|(_, column)| column.clone()); assert_eq!(of("book"), Some(Some("cover".to_string()))); assert_eq!(of("todo"), Some(None)); } // RULE (8 Nov 2026): a group view's tile counts the cards // its deck deals, one per person, never the rows under them: By person // read "9" on the fan over a deck of 4 people until it was opened. #[test] fn a_group_views_tile_counts_its_people_not_its_rows() { let (_dir, client) = attached(); let person = |name: &str| crate::phone::records::call(&client, "records.create", &json!({"table":"person","data":{"full_name":name}})) .unwrap()["record"]["id"].as_str().unwrap().to_string(); let (ana, ben) = (person("Ana Invented"), person("Ben Invented")); for (who, amount, direction) in [(&ana, 50_000, "out"), (&ana, 12_000, "in"), (&ben, 2_500, "out")] { crate::phone::records::call(&client, "records.create", &json!({"table":"transaction","data":{"description":"Invented", "occurred_on":"2026-11-06","amount_minor":amount,"currency":"INR","direction":direction,"status":"actual","moves_money":false, "counterparty_person_id":who}})).unwrap(); } client.bring_moves_done_for_tests().unwrap(); let answer = read(&client, &json!({"tool":"money","today":"2026-11-06","timezone":"UTC"})).unwrap(); let view = |id: &str| answer["views"].as_array().unwrap().iter().find(|view| view["id"] == id).cloned().unwrap_or_else(|| panic!("no view {id}: {answer}")); assert_eq!(view("owed")["count"], 3, "Owed counts its slips"); assert_eq!(view("by_person")["count"], 2, "By person counts its people"); }