//! The project scope over the list reads — the pure narrowing, and the whole //! path through `answer_read` over a synthetic replica with two projects. //! //! Every fixture is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]): //! the seeded file's `alpaca-work` (active, `note-a` linked) and `alpaca-old` //! (archived), plus a second active project, `garden`, added here. use std::collections::HashSet; use serde_json::{json, Map, Value}; use super::*; use crate::shell::client::phone_tests::{args, attached}; use crate::shell::client::ClientController; // ── The argument ──────────────────────────────────────────────────────────── #[test] fn no_scope_is_absent_null_or_an_empty_list() { assert_eq!(requested(&Map::new()), Ok(None)); assert_eq!(requested(&args(&[("projects", Value::Null)])), Ok(None)); assert_eq!(requested(&args(&[("projects", json!([]))])), Ok(None)); } #[test] fn a_scope_is_its_slugs_trimmed_and_once_each() { assert_eq!( requested(&args(&[("projects", json!(["garden", " garden ", "kitchen"]))])), Ok(Some(vec!["garden".to_string(), "kitchen".to_string()])) ); } #[test] fn a_scope_that_is_not_a_list_of_slugs_is_refused() { for bad in [json!("garden"), json!([1]), json!([""]), json!({"slug": "garden"})] { assert!(requested(&args(&[("projects", bad.clone())])).is_err(), "{bad}"); } } #[test] fn the_read_never_sees_the_scope_or_the_seams_own_keys() { let stripped = without_scope(&args(&[ ("projects", json!(["garden"])), (PROJECT_IDS, json!(["forged"])), (RECORD_IDS, json!(["forged"])), ("folder", json!("inbox")), ])); assert_eq!(stripped, args(&[("folder", json!("inbox"))])); } // ── The table — derived from the registered reads ─────────────────────────── use crate::phone::reads::{ScreenRead, READS}; /// Every read that takes a scope — DERIVED from `READS`, never listed. fn scoped_reads() -> impl Iterator { READS.iter().filter(|entry| entry.scope.is_some()) } /// How `read` (a name WITHOUT its `read.` prefix) takes a scope, if it does. fn scoped(read: &str) -> Option<&'static Narrowing> { crate::phone::reads::read_for(&format!("read.{read}")).and_then(|entry| entry.scope.as_ref()) } #[test] fn every_scoped_read_is_a_registered_read_a_screen_draws() { for entry in scoped_reads() { // By construction the entry is registered; what can still go wrong is // a SECOND entry of the same name answering the method instead. let answering = crate::phone::reads::read_for(&format!("read.{}", entry.name)).expect("registered"); assert!(std::ptr::eq(answering, entry), "read.{} is scoped but another entry answers it", entry.name); assert!(scoped(entry.name).is_some(), "read.{} is scoped but `scoped` does not find it", entry.name); assert!( matches!(entry.audience, crate::phone::reads::Audience::Screens(_)), "read.{} takes a scope but no screen draws it — only the Mac's lists are filtered", entry.name ); } } #[test] fn money_takes_no_scope_and_a_read_that_is_not_registered_has_none() { // Accounts are not a kind a project links. assert!(scoped("money").is_none()); assert!(scoped("nothingByThisName").is_none()); } #[test] fn every_after_narrowing_names_a_list() { for entry in scoped_reads() { if let Some(Narrowing::After(lists)) = entry.scope { assert!(!lists.is_empty(), "read.{} narrows nothing — declare `None` instead", entry.name); } } } #[test] fn every_kind_the_table_names_is_a_kind_a_project_links() { let linkable: HashSet<&str> = cotton_core::constants::ProjectLinkKind::ALL .iter() .map(|kind| kind.as_str()) .collect(); for entry in scoped_reads() { let kinds: Vec<&str> = match entry.scope.expect("scoped") { Narrowing::After(lists) => lists.iter().map(|list| list.kind).collect(), Narrowing::InRead { record_kind } => record_kind.into_iter().collect(), }; for kind in kinds { assert!(linkable.contains(kind), "read.{} narrows by `{kind}`, which nothing links", entry.name); } } } // ── Narrowing an answer ───────────────────────────────────────────────────── fn set(ids: &[&str]) -> HashSet { ids.iter().map(|id| (*id).to_string()).collect() } #[test] fn a_list_keeps_only_its_members_by_id() { let mut answer = json!({ "notes": [{"id": "a"}, {"id": "b"}, {"id": null}, {}], "other": 1 }); retain(&mut answer, &List { path: "notes", kind: "note", id: IdAt::Id, total: None }, &set(&["b"])); assert_eq!(answer, json!({ "notes": [{"id": "b"}], "other": 1 })); } #[test] fn an_occurrence_is_kept_for_its_event_or_its_series() { let mut answer = json!({ "occurrences": [ {"eventId": "one-off"}, {"eventId": "exception", "seriesId": "master"}, {"eventId": "elsewhere", "seriesId": "other"}, ]}); let entry = List { path: "occurrences", kind: "event", id: IdAt::AnyOf(&["eventId", "seriesId"]), total: None }; retain(&mut answer, &entry, &set(&["one-off", "master"])); let kept: Vec<&str> = answer["occurrences"].as_array().unwrap().iter().filter_map(|row| row["eventId"].as_str()).collect(); assert_eq!(kept, vec!["one-off", "exception"]); } #[test] fn a_merged_conversation_is_kept_when_any_of_its_threads_is_a_member() { let mut answer = json!({ "threads": [ {"id": "t1", "threadIds": ["t1", "t2"]}, {"id": "t3", "threadIds": ["t3"]}, {"threadIds": ["t4"]}, ]}); let entry = List { path: "threads", kind: "thread", id: IdAt::IdOrEach("threadIds"), total: None }; retain(&mut answer, &entry, &set(&["t2", "t4"])); assert_eq!(answer["threads"].as_array().unwrap().len(), 2); } #[test] fn a_nested_list_is_narrowed_and_an_absent_one_is_left_alone() { let entry = List { path: "hits.documents", kind: "document", id: IdAt::Id, total: None }; let mut searched = json!({ "hits": { "documents": [{"id": "d1"}, {"id": "d2"}] } }); retain(&mut searched, &entry, &set(&["d2"])); assert_eq!(searched, json!({ "hits": { "documents": [{"id": "d2"}] } })); let mut unsearched = json!({ "documents": [], "hits": null }); retain(&mut unsearched, &entry, &set(&["d2"])); assert_eq!(unsearched, json!({ "documents": [], "hits": null })); } #[test] fn a_count_that_describes_the_list_is_the_narrowed_count() { let mut answer = json!({ "total": 3, "people": [{"id": "p1"}, {"id": "p2"}, {"id": "p3"}] }); let entry = List { path: "people", kind: "person", id: IdAt::Id, total: Some("total") }; retain(&mut answer, &entry, &set(&["p3"])); assert_eq!(answer["total"], json!(1)); } // ── Over a replica, through the dispatch ──────────────────────────────────── const STAMP: &str = "2026-09-01T00:00:00.000Z"; fn exec(client: &ClientController, statement: &str) { client .with_writer(|replica| { replica .driver .run(&statement.replace("$WS", replica.workspace_id), &[]) .map(|_| ()) .map_err(|error| error.to_string()) }) .unwrap_or_else(|reason| panic!("seed: {reason}")); } fn link(client: &ClientController, id: &str, project: &str, kind: &str, record: &str) { exec( client, &format!( "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id, \ applied_by, created_at, updated_at) \ VALUES ('{id}', '$WS', '{project}', '{kind}', '{record}', 'user', '{STAMP}', '{STAMP}')" ), ); } /// The seeded file plus `garden`: a todo, a person and a note in `garden`, a /// todo in `alpaca-work`, and the seeded mail thread in `alpaca-work`. fn two_projects() -> (tempfile::TempDir, std::sync::Arc) { let (dir, client) = attached(); exec( &client, &format!( "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, created_at, updated_at) \ VALUES ('project-garden', '$WS', 'garden', 'Garden', 'active', '{STAMP}', '{STAMP}')" ), ); exec( &client, &format!( "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at) \ VALUES ('todo-garden', '$WS', 'Plant beans', 'open', '{STAMP}', '{STAMP}'), \ ('todo-work', '$WS', 'File a report', 'open', '{STAMP}', '{STAMP}')" ), ); exec( &client, &format!( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \ VALUES ('person-garden', '$WS', 'Synthetic Gardener', '{STAMP}', '{STAMP}')" ), ); exec( &client, &format!( "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \ VALUES ('note-garden', '$WS', 'note', 'Beds', 'Where the beans go.', '{STAMP}', '{STAMP}')" ), ); link(&client, "l-1", "project-garden", "todo", "todo-garden"); link(&client, "l-2", "project-garden", "person", "person-garden"); link(&client, "l-3", "project-garden", "note", "note-garden"); link(&client, "l-4", "project-a", "todo", "todo-work"); link(&client, "l-5", "project-a", "email_thread", "thread-a"); (dir, client) } fn answer(client: &ClientController, read: &str, pairs: &[(&str, Value)]) -> Result { let entry = crate::phone::reads::read_for(&format!("read.{read}")).expect("declared"); crate::phone::answer_read(client, entry, &args(pairs)) } fn ids(answer: &Value, key: &str) -> Vec { let mut out: Vec = answer[key] .as_array() .unwrap_or_else(|| panic!("{key} is not a list in {answer}")) .iter() .filter_map(|row| row["id"].as_str().map(str::to_string)) .collect(); out.sort(); out } #[test] fn a_scope_resolves_active_slugs_and_names_one_it_cannot() { let (_dir, client) = two_projects(); let resolved = client.with_writer(|replica| resolve(replica, &["garden".to_string(), "alpaca-work".to_string()])); assert_eq!(resolved, Ok(vec!["project-garden".to_string(), "project-a".to_string()])); let archived = client.with_writer(|replica| resolve(replica, &["alpaca-old".to_string()])); assert_eq!(archived, Err("unknown project \"alpaca-old\"".to_string()), "an archived project is not a filter"); let unknown = answer(&client, "notes", &[("projects", json!(["attic"]))]); assert_eq!(unknown, Err("unknown project \"attic\"".to_string())); } #[test] fn todos_narrow_to_the_chosen_project() { let (_dir, client) = two_projects(); let garden = answer(&client, "todos", &[("projects", json!(["garden"]))]).unwrap(); assert_eq!(ids(&garden, "todos"), vec!["todo-garden"]); let both = answer(&client, "todos", &[("projects", json!(["garden", "alpaca-work"]))]).unwrap(); assert_eq!(ids(&both, "todos"), vec!["todo-garden", "todo-work"], "a multi scope is the union"); let all = answer(&client, "todos", &[]).unwrap(); assert!(ids(&all, "todos").len() > 2, "no scope is every todo"); } #[test] fn notes_narrow_to_the_chosen_project() { let (_dir, client) = two_projects(); let work = answer(&client, "notes", &[("projects", json!(["alpaca-work"]))]).unwrap(); assert_eq!(ids(&work, "notes"), vec!["note-a"]); let garden = answer(&client, "notes", &[("projects", json!(["garden"]))]).unwrap(); assert_eq!(ids(&garden, "notes"), vec!["note-garden"]); } #[test] fn people_narrow_and_their_count_follows() { let (_dir, client) = two_projects(); let garden = answer(&client, "people", &[("projects", json!(["garden"]))]).unwrap(); assert_eq!(ids(&garden, "people"), vec!["person-garden"]); assert_eq!(garden["total"], json!(1)); } #[test] fn the_mailbox_is_narrowed_inside_the_query() { let (_dir, client) = two_projects(); let work = answer(&client, "email", &[("folder", json!("inbox")), ("projects", json!(["alpaca-work"]))]).unwrap(); assert_eq!(ids(&work, "threads"), vec!["thread-a"]); let garden = answer(&client, "email", &[("folder", json!("inbox")), ("projects", json!(["garden"]))]).unwrap(); assert_eq!(ids(&garden, "threads"), Vec::::new()); let all = answer(&client, "email", &[("folder", json!("inbox"))]).unwrap(); assert_eq!(ids(&all, "threads"), vec!["thread-a"]); } #[test] fn a_scoped_journal_is_the_projects_pages_and_the_unscoped_one_never_is() { let (_dir, client) = two_projects(); exec( &client, &format!( "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, journal_date, project_id, \ created_at, updated_at) \ VALUES ('page-garden', '$WS', 'journal', NULL, 'Beans are up.', '2026-09-10', 'project-garden', \ '{STAMP}', '{STAMP}')" ), ); let clock = [("nowMs", json!(1_789_128_000_000_i64)), ("timezone", json!("UTC"))]; let mut scoped_args = clock.to_vec(); scoped_args.push(("projects", json!(["garden"]))); let garden = answer(&client, "journal", &scoped_args).unwrap(); assert_eq!(ids(&garden, "pages"), vec!["page-garden"]); let own = answer(&client, "journal", &clock).unwrap(); assert!(!ids(&own, "pages").contains(&"page-garden".to_string()), "a project page is not the person's journal"); } #[test] fn a_read_that_cannot_be_narrowed_says_so() { let (_dir, client) = two_projects(); let refused = answer(&client, "storage", &[("projects", json!(["garden"]))]); assert_eq!(refused, Err("read.storage cannot be narrowed by project".to_string())); } #[test] fn a_caller_cannot_hand_a_read_the_seams_own_ids() { // Unscoped, a forged record list is stripped before the read runs: the // mailbox answers every thread, not the forged one. let (_dir, client) = two_projects(); let forged = answer(&client, "email", &[("folder", json!("inbox")), (RECORD_IDS, json!(["nothing"]))]).unwrap(); assert_eq!(ids(&forged, "threads"), vec!["thread-a"]); }