//! The project scope, applied to the phone's LIST reads. //! //! Mac redesign spec §4. The Mac's sidebar turned projects into a FILTER: one //! or more projects chosen, and every list in column 2 narrowed to what is //! linked to them. A read takes that as `projects: [slug]` — absent or empty is //! every project (the phone never sends one), an unknown or archived slug is an //! error by name, never a quietly empty list. //! //! **One membership, one place.** What "in the project" means is a row of //! `cotton_project_links` for that kind — the table `get_project` counts from — //! and it is read HERE, once per kind, rather than restated in fourteen //! queries. The reads themselves are untouched and so are the MCP tools: a //! read declares on its own registry entry (`ScreenRead::scope` in //! `reads::READS`) WHERE its rows are and which kind they are, and //! [`crate::phone::answer_read`] narrows the answer after the read has run. //! That entry is the ONE declaration — there is no second list of scoped //! reads, so a read deleted from the registry takes its scope with it. //! Every scoped read answers its whole set (none pages), so narrowing the //! answer is narrowing the set. //! //! Two reads cannot be narrowed after the fact, and they are told the scope //! instead ([`Narrowing::InRead`]): //! //! * `email` — `list_email_threads` caps the conversations it reads at 500 //! ids BEFORE it orders them, so a filter over its answer could miss a //! linked thread that simply fell past the cap. The member thread ids are //! handed to the query, which intersects before the cap. //! * `journal` — its query keeps project pages OUT (`project_id IS NULL`), so //! there is nothing in its answer to narrow to. Scoped, it reads the chosen //! projects' pages instead. //! //! A read whose entry declares no scope refuses one by name. `money` is the //! one list read that stays unscoped: its rows are accounts, and an account is //! not a kind a project links. use std::collections::HashSet; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use crate::shell::file::ReadFile; /// The argument a screen sends. pub const PROJECTS: &str = "projects"; /// Seam-internal arguments, set by [`crate::phone::answer_read`] for an /// [`Narrowing::InRead`] read and stripped from anything a caller sends — so a /// read that finds one knows the seam resolved it. pub(crate) const PROJECT_IDS: &str = "__scopeProjectIds"; pub(crate) const RECORD_IDS: &str = "__scopeRecordIds"; /// Where a row's record id is. #[derive(Debug, Clone, Copy)] pub enum IdAt { /// The row's own `id`. Id, /// Kept when ANY of these keys holds a member id — a calendar occurrence /// is its event's (`eventId`) or its series master's (`seriesId`), because /// an exception inherits the master's projects. AnyOf(&'static [&'static str]), /// Kept when `id` or any id in this array is a member — a merged message /// conversation is several threads under one row. IdOrEach(&'static str), } /// One list inside a read's answer. #[derive(Debug, Clone, Copy)] pub struct List { /// A top-level key, or a dotted path (`hits.documents`). A path that is /// absent or null is left alone — a search that did not run has no hits. pub path: &'static str, /// The `record_kind` its rows are linked as. pub kind: &'static str, pub id: IdAt, /// A sibling count that describes this list and is rewritten to its /// narrowed length. pub total: Option<&'static str>, } #[derive(Debug, Clone, Copy)] pub enum Narrowing { /// Narrow these lists in the answer. After(&'static [List]), /// Tell the read; with a kind, the member record ids travel too. InRead { record_kind: Option<&'static str> }, } /// The list helper the `ScreenRead::scope` declarations in `reads.rs` use: rows linked as /// `kind`, by their own `id`, with no count beside them. pub(crate) const fn list(path: &'static str, kind: &'static str) -> List { List { path, kind, id: IdAt::Id, total: None } } /// The slugs a caller asked for: `None` for absent, null or an empty array /// (every project), refused for anything that is not an array of slugs. pub fn requested(args: &Map) -> Result>, String> { let Some(value) = args.get(PROJECTS) else { return Ok(None) }; let items = match value { Value::Null => return Ok(None), Value::Array(items) => items, _ => return Err("`projects` is a list of project slugs".to_string()), }; let mut slugs: Vec = Vec::new(); for item in items { let slug = item .as_str() .map(str::trim) .filter(|slug| !slug.is_empty()) .ok_or_else(|| "`projects` is a list of project slugs".to_string())?; if !slugs.iter().any(|seen| seen == slug) { slugs.push(slug.to_string()); } } Ok(if slugs.is_empty() { None } else { Some(slugs) }) } /// The caller's arguments without the scope or the seam's own keys — what the /// read and its tools see. pub fn without_scope(args: &Map) -> Map { let mut out = args.clone(); out.remove(PROJECTS); out.remove(PROJECT_IDS); out.remove(RECORD_IDS); out } /// The active projects' ids for `slugs`, in the order asked. An unknown or /// archived slug is an error naming it — a filter to a project that is not /// there is a mistake to show, not an empty list to draw. pub fn resolve(replica: &ReadFile<'_>, slugs: &[String]) -> Result, String> { let rows = replica .driver .all( "SELECT id, slug FROM cotton_memory_projects WHERE workspace_id = ? AND status = 'active'", &[SqlValue::Text(replica.workspace_id.to_string())], ) .map_err(|error| error.to_string())?; slugs .iter() .map(|slug| { rows.iter() .find(|row| row.text("slug") == Some(slug.as_str())) .and_then(|row| row.text("id").map(str::to_string)) .ok_or_else(|| format!("unknown project \"{slug}\"")) }) .collect() } /// The ids of every `kind` record linked to any of `project_ids`. pub fn members(replica: &ReadFile<'_>, project_ids: &[String], kind: &str) -> Result, String> { if project_ids.is_empty() { return Ok(HashSet::new()); } let holes = vec!["?"; project_ids.len()].join(","); let mut params = vec![ SqlValue::Text(replica.workspace_id.to_string()), SqlValue::Text(kind.to_string()), ]; params.extend(project_ids.iter().map(|id| SqlValue::Text(id.clone()))); let rows = replica .driver .all( &format!( "SELECT DISTINCT record_id FROM cotton_project_links WHERE workspace_id = ? AND record_kind = ? AND project_id IN ({holes})" ), ¶ms, ) .map_err(|error| error.to_string())?; Ok(rows.iter().filter_map(|row| row.text("record_id").map(str::to_string)).collect()) } /// Narrow `answer`'s lists to the records linked to `project_ids`. pub fn narrow( replica: &ReadFile<'_>, project_ids: &[String], lists: &[List], answer: Value, ) -> Result { let mut answer = answer; let mut by_kind: std::collections::HashMap<&str, HashSet> = std::collections::HashMap::new(); for entry in lists { if !by_kind.contains_key(entry.kind) { by_kind.insert(entry.kind, members(replica, project_ids, entry.kind)?); } } for entry in lists { retain(&mut answer, entry, &by_kind[entry.kind]); } Ok(answer) } /// The pure half of [`narrow`]: one list, one member set. pub fn retain(answer: &mut Value, entry: &List, members: &HashSet) { let mut parts: Vec<&str> = entry.path.split('.').collect(); let Some(last) = parts.pop() else { return }; let mut holder = &mut *answer; for part in parts { match holder.get_mut(part) { Some(next) if next.is_object() => holder = next, _ => return, } } let Some(object) = holder.as_object_mut() else { return }; let Some(Value::Array(rows)) = object.get_mut(last) else { return }; let is_member = |value: Option<&Value>| value.and_then(Value::as_str).is_some_and(|id| members.contains(id)); rows.retain(|row| match entry.id { IdAt::Id => is_member(row.get("id")), IdAt::AnyOf(keys) => keys.iter().any(|key| is_member(row.get(*key))), IdAt::IdOrEach(key) => { is_member(row.get("id")) || row .get(key) .and_then(Value::as_array) .is_some_and(|ids| ids.iter().any(|id| is_member(Some(id)))) } }); let count = rows.len(); if let Some(total) = entry.total { if object.contains_key(total) { object.insert(total.to_string(), Value::from(count)); } } } /// The member ids an [`Narrowing::InRead`] read was handed, or `None` when it /// was not scoped. pub fn handed_record_ids(args: &Map) -> Option> { handed(args, RECORD_IDS) } /// The project ids an [`Narrowing::InRead`] read was handed, or `None`. pub fn handed_project_ids(args: &Map) -> Option> { handed(args, PROJECT_IDS) } fn handed(args: &Map, key: &str) -> Option> { args.get(key).and_then(Value::as_array).map(|ids| { ids.iter().filter_map(Value::as_str).map(str::to_string).collect() }) } #[cfg(test)] #[path = "scope_tests.rs"] mod tests;