//! A project's sections and what each holds — ONE reading, for `get_project` //! (the assistant's answer) and for Home's catalogue (a section that holds //! something is a tile, `cotton_core::rules::project_page::section_view`). //! //! The two callers count the same members by the same rules: which group a //! linked record belongs to ([`member_group`]) and what a section holds given //! those figures ([`holding`]). `get_project` already has the rows in hand for //! its answer; [`project_sections`] reads the file for a caller that has //! nothing but a project id. use std::collections::{BTreeMap, BTreeSet, HashSet}; use cotton_core::constants::{ProjectLinkKind, ProjectSectionKey}; use cotton_core::rules::memory_briefing::procedure_trigger; use cotton_core::rules::project_page::{ briefing_holds, default_order, present_sections, Holding, PageSection, PresentSection, }; use cotton_core::rules::project_sections::section_of_kind; use cotton_store::driver::Driver; use serde_json::{Map, Value}; use crate::mcp::handlers::common::{read_rows, text}; use crate::mcp::handlers::projects::brand::brand_kit_holds; use crate::mcp::handlers::projects::kinds::kind_source; use crate::mcp::handlers::projects::read::{ brand_assets_of, derived_members_for_people, project_session_count, }; use crate::mcp::handlers::projects::{links_of, read_linked_rows, KindRef}; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Query, ReadDb}; /// The group a linked record counts under, or `None` when it is no longer /// one of the project's: an ARCHIVED page of the project's own is gone from /// it (archiving is how a project page is taken off), while an archived owner /// page somebody linked with a `#` chip stays a deliberate membership. A /// procedure — a note whose first line names its trigger /// (`memory_briefing::procedure_trigger`, the rule `brief` uses) — leaves /// `notes` for its own group. pub fn member_group(kind: ProjectLinkKind, row: &Map) -> Option<&'static str> { if kind == ProjectLinkKind::Journal && !matches!(row.get("project_id"), None | Some(Value::Null)) && !matches!(row.get("archived_at"), None | Some(Value::Null)) { return None; } if kind == ProjectLinkKind::Note && procedure_trigger(text(row, "body").unwrap_or_default().as_str()).is_some() { return Some("procedures"); } Some(kind_source(kind).group) } /// What a project's sections are drawn from: each group's whole membership, /// and the figures of the sections that are not link groups. #[derive(Debug, Clone, Default)] pub struct SectionFigures { /// Members per group (`kind_source(..).group`, `procedures`), derived /// conversations and calls included. pub groups: BTreeMap<&'static str, u64>, /// The OPEN todos — the Todos figure (owner's rule: "120 to-dos" over a /// finished list is a number nobody can act on). pub open_todos: u64, /// The project's coding sessions (threads bound by `project_id`). pub sessions: u64, pub has_summary: bool, pub brand_holds: bool, } impl SectionFigures { fn group(&self, group: &str) -> u64 { self.groups.get(group).copied().unwrap_or(0) } } /// What one section holds, from the figures. pub fn holding(figures: &SectionFigures, section: PageSection) -> Holding { match section { PageSection::Linked(ProjectSectionKey::Todos) => Holding::Count(figures.open_todos), PageSection::Linked(key) => Holding::Count( ProjectLinkKind::ALL .into_iter() .filter(|kind| section_of_kind(*kind) == key) .map(|kind| kind_source(kind).group) .collect::>() .into_iter() .map(|group| figures.group(group)) .sum(), ), PageSection::Sessions => Holding::Count(figures.sessions), PageSection::Procedures => Holding::Count(figures.group("procedures")), PageSection::Briefing if briefing_holds(figures.has_summary, figures.group("memory")) => Holding::One, PageSection::Brand if figures.brand_holds => Holding::One, PageSection::Briefing | PageSection::Brand => Holding::Nothing, } } /// The sections of a project that hold something, in the page's default /// order, read from the file — what Home's catalogue offers as tiles. `None` /// when the project is not in this database. pub fn project_sections( db: &Driver, workspace_id: &str, project_id: &str, ) -> Result>, ToolFailure> { let read = ReadDb::new(db, workspace_id); let Some(project) = read_rows( &read, &Query::on("cotton_memory_projects") .columns(&["id", "description", "brand"]) .eq("id", project_id.to_string()), )? .into_iter() .next() else { return Ok(None); }; let links = links_of(&read, &[project_id.to_string()])?; let refs: Vec = links .iter() .filter_map(|link| { Some(KindRef { kind: ProjectLinkKind::parse(&link.record_kind)?, id: link.record_id.clone() }) }) .collect(); let row_by_key = read_linked_rows(&read, &refs)?; let mut figures = SectionFigures::default(); let mut people: Vec = Vec::new(); let mut explicit: HashSet = HashSet::new(); for entry in &refs { explicit.insert(format!("{}:{}", entry.kind, entry.id)); // The record was deleted; the link is dangling. let Some(row) = row_by_key.get(&format!("{}:{}", entry.kind, entry.id)) else { continue; }; let Some(group) = member_group(entry.kind, row) else { continue; }; *figures.groups.entry(group).or_default() += 1; if entry.kind == ProjectLinkKind::Todo && text(row, "status").as_deref() == Some("open") { figures.open_todos += 1; } if entry.kind == ProjectLinkKind::Person && !people.contains(&entry.id) { people.push(entry.id.clone()); } } // The DM conversations and calls a linked person brings, deduped against // the explicit links — counted like any other member, as the page does. for (kind, row) in derived_members_for_people(&read, &people)? { if explicit.contains(&format!("{kind}:{}", text(&row, "id").unwrap_or_default())) { continue; } *figures.groups.entry(kind_source(kind).group).or_default() += 1; } figures.sessions = project_session_count(&read, project_id)?; figures.has_summary = text(&project, "description").is_some_and(|d| !d.trim().is_empty()); figures.brand_holds = brand_kit_holds(project.get("brand"), brand_assets_of(&read, &links)?.len()); Ok(Some(present_sections(&default_order(), |section| holding(&figures, section)))) }