//! `arrange_tools` — Home's tiles added and removed (never ordered) from a //! conversation, through the row the phone's own drag writes — and Remove //! tool, which takes a tool out of a database only while it holds nothing. mod support; #[path = "support/work_fixture.rs"] mod work_fixture; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::Harness; use support::mcp::{call_tool_raw, mint_token}; /// Through the MCP transport, as an assistant calls it: no commit but the /// handler's own, so a tool that forgets to commit answers and writes nothing. fn call(h: &Harness, secret: &str, tool: &str, args: Value) -> Result { let answer = call_tool_raw(h, secret, tool, args); if answer.is_error { Err(answer.text) } else { Ok(serde_json::from_str(&answer.text).unwrap()) } } fn arrange(h: &Harness, secret: &str, args: Value) -> Result { call(h, secret, "arrange_tools", args) } /// Home's tiles as the answer draws them: (view, empty), in order. fn tiles(answer: &Value) -> Vec<(String, bool)> { answer["home"]["tiles"] .as_array() .unwrap() .iter() .map(|tile| (tile["view"].as_str().unwrap().to_string(), tile["empty"].as_bool().unwrap())) .collect() } fn at(tiles: &[(String, bool)], view: &str) -> usize { tiles.iter().position(|(id, _)| id == view).unwrap_or_else(|| panic!("{view} is not on Home: {tiles:?}")) } fn stored_views(h: &Harness) -> Vec { let row = h.one("SELECT view_ids FROM cotton_home_arrangement", &[]).expect("the row is in the file"); serde_json::from_str(row["view_ids"].as_str().unwrap()).unwrap() } /// RULE: the arrangement writer refuses a tile this database cannot show, /// whole and before writing — a stored unknown falls out of Home's read /// silently, so the assistant would report a change the screen never draws — /// and a tile it adds or removes is what Home then reads, through the /// transport an assistant calls it by (the first version answered a change on /// the owner's real database and, never committing, wrote nothing). #[test] fn the_arrangement_writer_refuses_an_unknown_tile_and_writes_what_home_reads() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); let unknown = arrange(&h, &secret, json!({"add": ["calendar", "no_such_tool"]})).unwrap_err(); assert!(unknown.contains("no_such_tool") && unknown.contains("no tile"), "{unknown}"); assert!(arrange(&h, &secret, json!({"add": ["Calendar"]})).is_err(), "a key is matched exactly"); assert!(arrange(&h, &secret, json!({"add": ["bin"], "remove": ["bin"]})).is_err()); assert!(arrange(&h, &secret, json!({"show": ["calendar"]})).is_err(), "an argument it does not take"); let untouched = arrange(&h, &secret, json!({})).unwrap(); assert_eq!(untouched["changed"], json!(false)); assert!(h.one("SELECT workspace_id FROM cotton_home_arrangement", &[]).is_none(), "a refusal and a read write nothing"); let removed = arrange(&h, &secret, json!({"remove": ["calendar", "everything"]})).unwrap(); assert!(!tiles(&removed).iter().any(|(view, _)| view == "tool/calendar" || view == "ready/everything"), "{removed}"); assert!(removed["home"]["tools"].as_array().unwrap().contains(&json!("calendar")), "a tile off Home is still a tool"); let added = arrange(&h, &secret, json!({"add": ["calendar"]})).unwrap(); assert!(stored_views(&h).contains(&"tool/calendar".to_string())); let drawn = tiles(&added); assert!(at(&drawn, "tool/calendar") < at(&drawn, "tool/todos"), "Calendar before Todos, by the alphabet: {drawn:?}"); let read = arrange(&h, &secret, json!({})).unwrap(); assert_eq!(read["home"], added["home"], "the read answers what was written"); } /// RULE (owner, 17 Oct 2026): the fan's order is alphabetical in every database, always, and no MCP tool sets an order — `arrange_tools` takes no `order`, and `propose_home` and `use_home` (which only reordered) are gone. A tile with nothing to show is drawn faint IN ITS PLACE, and gains its colour there on its first record — over a real file, through the read an assistant gets. #[test] fn home_is_alphabetical_and_no_tool_sets_an_order() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); for refused in [ call(&h, &secret, "arrange_tools", json!({"order": ["todos", "calendar"]})), call(&h, &secret, "propose_home", json!({})), call(&h, &secret, "use_home", json!({"views": [], "before": [], "board": {}})), ] { assert!(refused.is_err(), "no tool sets Home's order: {refused:?}"); } let definitions = cotton_tools::definitions::tool_definitions_from_driver(&h.db, &h.workspace_id).unwrap(); let name = |view: &str| -> String { match view.strip_prefix("tool/") { Some(key) => definitions.definitions.iter().find(|tool| tool.id == key) .map(|tool| tool.name.clone()).unwrap_or_else(|| { assert_eq!(key, "bin", "every installed tool has a definition"); "Bin".into() }), None if view == "ready/everything" => "Everything".to_string(), None => panic!("unexpected default Home view: {view}"), } }; let before = tiles(&arrange(&h, &secret, json!({"add": ["todos", "calendar"]})).unwrap()); let names: Vec = before.iter().map(|(view, _)| name(view)).collect(); assert!( names.windows(2).all(|pair| cotton_core::js_text::compare_names(&pair[0], &pair[1]) != std::cmp::Ordering::Greater), "alphabetical: {names:?}" ); let todos = at(&before, "tool/todos"); assert!(before[todos].1, "an empty Todos is faint: {before:?}"); assert!(at(&before, "tool/calendar") < todos, "Calendar before Todos, by the alphabet: {before:?}"); call(&h, &secret, "create_todo", json!({"title": "Buy invented string"})).unwrap(); let after = tiles(&arrange(&h, &secret, json!({})).unwrap()); assert_eq!(after[todos], ("tool/todos".to_string(), false), "its place, now in colour: {after:?}"); assert_eq!( after.iter().map(|(view, _)| view.clone()).collect::>(), before.iter().map(|(view, _)| view.clone()).collect::>(), "a first record moves nothing" ); } /// RULE (owner's ruling, 12 Oct 2026): a tile points at ANY view of its tool, /// not only its list — Todos' Today, Calendar's Month — and wears that tool: /// the view joins Home through the same writer, answers its tool, its own name /// and the path a view's definition names, and is drawn faint while the tool /// holds nothing; a view of a tool this database lacks, or a face no table /// ships, is no tile. #[test] fn a_tile_points_at_any_view_of_its_tool_and_wears_that_tool() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); let added = arrange(&h, &secret, json!({"add": ["ready/today", "ready/month"]})).unwrap(); let tile = |view: &str| -> Value { added["home"]["tiles"].as_array().unwrap().iter().find(|tile| tile["view"] == view).cloned() .unwrap_or_else(|| panic!("{view} is not on Home: {added}")) }; assert_eq!(tile("ready/today")["tool"], "todos"); assert_eq!(tile("ready/today")["name"], "Today"); assert_eq!(tile("ready/month")["tool"], "calendar"); assert_eq!(tile("tool/todos")["name"], Value::Null, "a tool's list is named by its tool"); assert_eq!(tile("ready/today")["empty"], tile("tool/todos")["empty"], "a view is as full as its tool"); assert!(stored_views(&h).contains(&"ready/today".to_string())); assert!(arrange(&h, &secret, json!({"add": ["ready/nowhere"]})).is_err(), "a face no table ships"); assert!(arrange(&h, &secret, json!({"add": ["ready/everything_else"]})).is_err()); } /// RULE: Home resolves only this database's tiles. Personal's project directory /// is a switch to those databases, never a source of project section tiles; /// stale stored section ids must disappear too, without changing the records. #[test] fn home_sections_belong_to_the_project_database_and_never_to_personal() { use cotton_core::rules::home_arrangement::HomeArrangement; use cotton_tools::home_arrangement::home; let personal = Harness::new(); let mut project = Harness::new(); let project_database = support::synthetic_uuid("kiln-database"); project.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, kind, namespace) VALUES (?, 'Kiln database', ?, '2026-10-14', 'shared', ?)", &[ SqlValue::Text(project_database.clone()), SqlValue::Text(support::synthetic_uuid("kiln-owner")), SqlValue::Text(project_database.clone()), ], ); project.run( "UPDATE _meta SET workspace_id = ?", &[SqlValue::Text(project_database.clone())], ); project.workspace_id = project_database; assert_ne!(personal.workspace_id, project.workspace_id); // Personal retains a project directory entry, while the project's file // has the project itself. Both have a briefing, so emptiness cannot hide // a failure to enforce the database boundary. for (h, slug) in [(&personal, "kiln"), (&project, "kiln")] { h.run( "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, description, created_at, updated_at) VALUES (?, ?, ?, 'Kiln', 'Synthetic working context', '2026-10-14', '2026-10-14')", &[ SqlValue::Text(support::synthetic_uuid(slug)), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(slug.into()), ], ); } let stale = HomeArrangement { tools: vec!["notes".into(), "project/briefing/kiln".into()], view_ids: vec!["tool/notes".into(), "project/briefing/kiln".into()], ..HomeArrangement::default() }; for manual in [None, Some(&stale)] { let mine = home(&personal.db, &personal.workspace_id, manual, true).unwrap(); assert!( mine.offered .iter() .all(|view| !view.view.starts_with("project/")), "{:?}", mine.offered ); assert!( mine.tiles .iter() .all(|tile| !tile.id.starts_with("project/")), "{:?}", mine.tiles ); let theirs = home(&project.db, &project.workspace_id, manual, false).unwrap(); assert!(theirs.shows("project/briefing/kiln"), "{:?}", theirs.tiles); assert!(theirs.view("project/briefing/kiln").unwrap().holds == Some(true)); for tile in &theirs.tiles { assert!( theirs.view(&tile.id).is_some(), "{} has no local resolution", tile.id ); } } assert!( personal .one( "SELECT id FROM cotton_memory_projects WHERE slug = 'kiln'", &[] ) .is_some(), "reading Home leaves the directory entry alone" ); } fn import_work(h: &Harness, secret: &str) { use base64::{engine::general_purpose::STANDARD, Engine}; let bytes = cotton_core::definitions::package::encode_unsigned_package(&work_fixture::package()).unwrap(); call(h, secret, "import_tool", json!({"bytes": STANDARD.encode(bytes)})).unwrap(); } /// RULE (architect, 14 Oct 2026): any table of a tool with several is a tile /// of its own on Home, `/`, and that tile opens the TABLE's list. /// The view id has a group's shape (`
/`), so the answer names /// the table outright and the app opens its list from that field, never by /// parsing the id — parsed, `work/landing` opened table "work" filtered by a /// group called "landing". #[test] fn a_table_of_a_tool_with_several_is_a_tile_that_names_its_table() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); import_work(&h, &secret); let added = arrange(&h, &secret, json!({"add": ["work/landing", "work/effort"]})).unwrap(); let tile = |view: &str| -> Value { added["home"]["tiles"].as_array().unwrap().iter().find(|tile| tile["view"] == view).cloned() .unwrap_or_else(|| panic!("{view} is not on Home: {added}")) }; assert_eq!(tile("work/landing")["table"], "landing"); assert_eq!(tile("work/landing")["tool"], "work"); assert_eq!(tile("work/landing")["name"], "Landings"); assert_eq!(tile("work/effort")["table"], "effort"); assert_eq!(tile("tool/work")["table"], Value::Null, "the tool's own tile opens the tool"); assert!(arrange(&h, &secret, json!({"add": ["work/no_such_table"]})).is_err(), "a table the tool lacks is no tile"); } /// RULE (architect, 14 Oct 2026): a removed tool takes every tile of its /// views off Home — its tables' own tiles and their charts with its list — /// so no stored placement is left pointing at a tool the database lacks. #[test] fn a_removed_tools_table_tiles_leave_home_with_it() { let mut h = Harness::new(); h.run("UPDATE cotton_workspaces SET kind = 'shared' WHERE id = ?", &[SqlValue::Text(h.workspace_id.clone())]); let secret = mint_token(&mut h, &["read", "write"], "Claude"); import_work(&h, &secret); arrange(&h, &secret, json!({"add": ["work", "work/landing", "work/lane", "chart/landing", "todos"]})).unwrap(); let placed = stored_views(&h); assert!(placed.contains(&"work/landing".to_string()) && placed.contains(&"chart/landing".to_string()), "{placed:?}"); call(&h, &secret, "remove_tool", json!({"tool_id": "work"})).unwrap(); let left = stored_views(&h); for view in ["tool/work", "work/landing", "work/lane", "chart/landing"] { assert!(!left.contains(&view.to_string()), "{view} stayed on Home: {left:?}"); } assert!(left.contains(&"tool/todos".to_string()), "the other tiles stay: {left:?}"); }