Cotton code
996 lines · 41.1 KB · RustRaw
//! `list_projects` and `get_project` — the two reads.//!//! `get_project` is the ONE session-start call: the whole working context in//! one answer, compact rows with counts so the assistant drills in with the//! per-kind tools rather than pulling payloads it may not need.use crate::mcp::handlers::projects::kinds::{extras_of, kind_source, title_of};use std::collections::{BTreeMap, HashSet};use cotton_core::constants::{ProjectLinkKind, SummaryKind};use cotton_core::rules::memory_briefing::procedure_trigger;use cotton_core::rules::project_page::{default_order, present_sections, Holding};use cotton_core::rules::summaries::{staleness_of, summary_source};use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{in_chunks, js_number, or_null, put, quoted, read_rows, rows, text};use crate::mcp::handlers::projects::brand::{    brand_kit_holds, is_brand_asset_role, BRAND_ASSET_ROLES,};use crate::mcp::handlers::projects::engine_shim::project_journal_rows;use crate::mcp::handlers::projects::sections::{holding, member_group, SectionFigures};use crate::mcp::handlers::projects::validate::validate_get_project;use crate::mcp::handlers::projects::{    links_of, memory_projects, project_by_slug, project_out, read_linked_rows, KindRef, LinkRow,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query, ReadDb};/// Per response group, at most this many rows travel; the group's `count`/// always states the whole membership.const GROUP_CAP: usize = 50;/// How many of a project's journal pages travel in one `get_project`. A week is/// the working-context read the per-project journal exists to feed.const JOURNAL_RECENT: i64 = 7;// ── the brand kit's logo files ──────────────────────────────────────────────/// One brand asset as `brand_assets_of` gathers it: the document's id, the/// role its link note named, and the row itself.type BrandAsset = (String, &'static str, Map<String, Value>);/// A member a linked PERSON brings in without a link row of their own.type DerivedMember = (ProjectLinkKind, Map<String, Value>);/// The logo FILES of a project: the documents linked to it whose link NOTE is/// one of `BRAND_ASSET_ROLES`.////// No new table, no new link kind and no second copy of the bytes — a brand/// asset is an ordinary document with an ordinary membership, which is why/// `link_to_project` needed no change to file one and why a logo still appears/// under the project's documents where its owner put it. The role is CASE/// SENSITIVE: it is a value the surfaces write, and guessing at "Logo" would/// make one field mean two things.pub(crate) fn brand_assets_of(read: &ReadDb<'_>, links: &[LinkRow]) -> Result<Vec<BrandAsset>, ToolFailure> {    let mut by_id: Vec<(String, &'static str)> = Vec::new();    for link in links {        if link.record_kind != "document" {            continue;        }        let Some(note) = link            .note            .as_deref()            .filter(|note| is_brand_asset_role(note))        else {            continue;        };        let role = BRAND_ASSET_ROLES            .iter()            .find(|role| **role == note)            .copied()            .expect("is_brand_asset_role just matched it");        if !by_id.iter().any(|(id, _)| id == &link.record_id) {            by_id.push((link.record_id.clone(), role));        }    }    if by_id.is_empty() {        return Ok(Vec::new());    }    let ids: Vec<String> = by_id.iter().map(|(id, _)| id.clone()).collect();    let found = in_chunks(&ids, |batch| {        read_rows(            read,            &Query::on("cotton_documents")                .columns(&["id", "original_name", "title", "mime"])                .filter(Filter::In(                    "id".to_string(),                    batch.iter().map(|id| id.clone().into()).collect(),                ))                // A document in the bin is no brand file of any project.                .filter(Filter::IsNull("trashed_at".to_string())),        )    })?;    let documents: BTreeMap<String, Map<String, Value>> = found        .into_iter()        .filter_map(|row| text(&row, "id").map(|id| (id, row)))        .collect();    // In the ROLES' own order — the order the app draws its slots in — rather    // than the order the links happen to have been created. A brand kit reads    // as a set of slots, not as a history of filing.    let mut out = Vec::new();    for role in BRAND_ASSET_ROLES {        for (id, assigned) in &by_id {            if assigned != role {                continue;            }            // The document was deleted; the link is dangling.            let Some(row) = documents.get(id) else {                continue;            };            let mut asset = Map::new();            asset.insert("id".to_string(), Value::from(id.clone()));            asset.insert("role".to_string(), Value::from(*role));            asset.insert(                "filename".to_string(),                Value::from(                    text(row, "title")                        .or_else(|| text(row, "original_name"))                        .unwrap_or_else(|| "(untitled)".to_string()),                ),            );            asset.insert("mime".to_string(), or_null(text(row, "mime")));            out.push((id.clone(), *role, asset));        }    }    Ok(out)}fn brand_asset_values(assets: &[(String, &'static str, Map<String, Value>)]) -> Vec<Value> {    assets        .iter()        .map(|(_, _, asset)| Value::Object(asset.clone()))        .collect()}// ── list_projects ───────────────────────────────────────────────────────────pub fn list_projects(ctx: &mut Ctx<'_>, _args: &Map<String, Value>) -> ToolResult {    let projects = memory_projects(ctx)?;    let ids: Vec<String> = projects        .iter()        .filter_map(|project| text(project, "id"))        .collect();    let links = links_of(&ctx.read, &ids)?;    let mut counts_by_project: BTreeMap<String, Map<String, Value>> = BTreeMap::new();    for link in &links {        let counts = counts_by_project            .entry(link.project_id.clone())            .or_default();        let next = counts            .get(&link.record_kind)            .and_then(Value::as_i64)            .unwrap_or(0)            + 1;        counts.insert(link.record_kind.clone(), Value::from(next));    }    // The brand assets of every project in ONE extra read: `links` is already    // in hand, so this costs one query for the whole list rather than one per    // project. No urls here — a listing is not the place to mint credentials.    let brand_links: Vec<LinkRow> = links        .iter()        .filter(|link| {            link.record_kind == "document" && link.note.as_deref().is_some_and(is_brand_asset_role)        })        .cloned()        .collect();    let all_assets = brand_assets_of(&ctx.read, &brand_links)?;    let project_of_document: BTreeMap<String, String> = brand_links        .iter()        .map(|link| (link.record_id.clone(), link.project_id.clone()))        .collect();    let mut assets_by_project: BTreeMap<String, Vec<Value>> = BTreeMap::new();    for (id, _, asset) in &all_assets {        let Some(project_id) = project_of_document.get(id) else {            continue;        };        assets_by_project            .entry(project_id.clone())            .or_default()            .push(Value::Object(asset.clone()));    }    let listed: Vec<Value> = projects        .iter()        .map(|project| {            let id = text(project, "id").unwrap_or_default();            let mut out = project_out(project);            out.insert(                "linked".to_string(),                Value::Object(counts_by_project.get(&id).cloned().unwrap_or_default()),            );            if let Some(assets) = assets_by_project.get(&id).filter(|a| !a.is_empty()) {                out.insert("brandAssets".to_string(), Value::Array(assets.clone()));            }            Value::Object(out)        })        .collect();    let mut out = Map::new();    out.insert("projects".to_string(), Value::Array(listed));    Ok(Value::Object(out))}// ── get_project ─────────────────────────────────────────────────────────────/// DM threads have no title of their own — their name is their contact's.fn contact_names(    read: &ReadDb<'_>,    thread_rows: &[Map<String, Value>],) -> Result<BTreeMap<String, String>, ToolFailure> {    let mut ids: Vec<String> = Vec::new();    let mut seen: HashSet<String> = HashSet::new();    for row in thread_rows {        if let Some(contact_id) = text(row, "contact_id") {            if seen.insert(contact_id.clone()) {                ids.push(contact_id);            }        }    }    if ids.is_empty() {        return Ok(BTreeMap::new());    }    let contacts = in_chunks(&ids, |batch| {        read_rows(            read,            &Query::on("cotton_msg_contacts")                .columns(&["id", "display_name", "phone_e164"])                .filter(Filter::In(                    "id".to_string(),                    batch.iter().map(|id| id.clone().into()).collect(),                )),        )    })?;    Ok(contacts        .into_iter()        .filter_map(|contact| {            let id = text(&contact, "id")?;            let name = text(&contact, "display_name").unwrap_or_else(|| {                format!("+{}", text(&contact, "phone_e164").unwrap_or_default())            });            Some((id, name))        })        .collect())}/// The DM conversations and the calls a project's linked PEOPLE bring with them.////// Two reads, both reaching the person://////   - a DM thread whose contact resolves to a linked person. GROUPS never come///     in this way: a group chat is not "a conversation with Ravi", and pulling///     one in because one member is linked would put a room full of other///     people's words on a page they were never part of.///   - a call whose `person_id` is a linked person.////// Nothing here writes anything. Derived rows are not link rows, so a person in/// two projects shows their calls in both, which is the truth of it.pub(crate) fn derived_members_for_people(    read: &ReadDb<'_>,    person_ids: &[String],) -> Result<Vec<DerivedMember>, ToolFailure> {    if person_ids.is_empty() {        return Ok(Vec::new());    }    let contacts = in_chunks(person_ids, |batch| {        read_rows(            read,            &Query::on("cotton_msg_contacts")                .columns(&["id"])                .filter(Filter::In(                    "person_id".to_string(),                    batch.iter().map(|id| id.clone().into()).collect(),                )),        )    })?;    let mut contact_ids: Vec<String> = Vec::new();    let mut seen: HashSet<String> = HashSet::new();    for contact in contacts {        if let Some(id) = text(&contact, "id") {            if seen.insert(id.clone()) {                contact_ids.push(id);            }        }    }    let threads = if contact_ids.is_empty() {        Vec::new()    } else {        in_chunks(&contact_ids, |batch| {            read_rows(            read,            &Query::on("cotton_msg_threads")                    .columns(kind_source(ProjectLinkKind::Thread).columns)                    .eq("kind", "dm".to_string())                    .filter(Filter::In(                        "contact_id".to_string(),                        batch.iter().map(|id| id.clone().into()).collect(),                    ))                    .order_by("last_message_at", Order::Desc),            )        })?    };    let calls = crate::mcp::handlers::calls::read_calls(read.driver(),read.workspace_id())        .map_err(|e|ToolFailure::new(e.to_string()))?.into_iter()        .filter(|row|person_ids.iter().any(|person|crate::mcp::handlers::calls::has_person(row,person)))        .collect::<Vec<_>>();    let mut out: Vec<(ProjectLinkKind, Map<String, Value>)> = Vec::new();    out.extend(        threads            .into_iter()            .map(|row| (ProjectLinkKind::Thread, row)),    );    out.extend(calls.into_iter().map(|row| (ProjectLinkKind::Call, row)));    Ok(out)}// ── what orders a section ───────────────────────────────────────────────────/// The moment a member of this kind is ORDERED BY on a project page.////// One declaration, exhaustive on the kind, for the reason every other kind map/// in this reader is: a kind with no answer here would sort by whatever order/// its links happened to be filed in, silently, for ever. Each arm names the/// column the kind's own section already surfaces — a walkthrough is known by/// when it was published, a call by when it rang, a note by when it was last/// written — so the page's order and the row's own line say the same thing.////// `filed_at` is the LINK's `created_at`, and it is the answer for the kind/// whose projection surfaces no moment at all (a person is not an event). "Newest" for those is when they joined/// the project, which is the only date the page holds about them.////// `None` is a row whose own moment is empty — an unpublished walkthrough, a/// document with no date on it. It sorts LAST, never to the top, the rule/// `cotton_core::rules::project_sections` keeps for the same question.////// TODOS answer their DUE date, and are the one section [`get_project`] sorts/// the other way round — soonest first — because a list of work is read by what/// is owed next, never by what was written last.fn ordering_moment(    kind: ProjectLinkKind,    row: &Map<String, Value>,    filed_at: &str,) -> Option<String> {    use ProjectLinkKind::*;    let at = |column: &str| text(row, column).filter(|value| !value.is_empty());    let filed = || Some(filed_at.to_string()).filter(|value| !value.is_empty());    match kind {        Thread => at("last_message_at"),        EmailThread => at("last_at"),        Call => at("started_at"),        Event | Album => at("starts_at"),        Note | Secret | Memory => at("updated_at"),        // A journal page is known by the DAY it covers, widened to midday so it        // compares against the date-times the other kinds carry.        Journal => at("journal_date")            .map(|day| format!("{day}T12:00:00.000Z"))            .or_else(|| at("updated_at")),        Document => at("document_date"),        Transaction => at("occurred_on"),        Photo | Video => at("taken_at"),        Todo => at("due_at"),        // A repository is the ONE kind here whose moment is `created_at` and        // not its own `updated_at`, and the reason is the `repos` worker: it        // REWRITES the row on every pass, so `updated_at` is the instant of        // the last poll rather than the instant something happened. Ordered by        // it, one repository would hold the top of the project's Code section        // for ever while the events a person came to read fell off the end.        // `created_at` is when the repository arrived, which is a moment that        // happened.        Repository => at("created_at"),        Person => filed(),    }}/// Newest first, a member with no moment last.fn newest_first(a: &Option<String>, b: &Option<String>) -> std::cmp::Ordering {    use std::cmp::Ordering;    match (a, b) {        (Some(a), Some(b)) => b.cmp(a),        (Some(_), None) => Ordering::Less,        (None, Some(_)) => Ordering::Greater,        (None, None) => Ordering::Equal,    }}/// Soonest first, a member with no date last — the todos' order, and only/// theirs: a list of work is read by what is owed next, not by what was written/// last.fn soonest_first(a: &Option<String>, b: &Option<String>) -> std::cmp::Ordering {    use std::cmp::Ordering;    match (a, b) {        (Some(a), Some(b)) => a.cmp(b),        (Some(_), None) => Ordering::Less,        (None, Some(_)) => Ordering::Greater,        (None, None) => Ordering::Equal,    }}pub fn get_project(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_get_project(args)?;    let projects = memory_projects(ctx)?;    let project = project_by_slug(&projects, &args.slug)?.clone();    let project_id = text(&project, "id").unwrap_or_default();    let all_links = links_of(&ctx.read, std::slice::from_ref(&project_id))?;    let links: Vec<LinkRow> = all_links        .iter()        .filter(|link| ProjectLinkKind::parse(&link.record_kind).is_some())        .cloned()        .collect();    let refs: Vec<KindRef> = 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(&ctx.read, &refs)?;    // The DERIVED half (§D8): the DM conversations and calls of every PERSON    // linked here. Read before the loop below so the two kinds of membership go    // through one projection and one cap — and deduped against the explicit    // links, which are appended FIRST and keep their notes.    let mut linked_people: Vec<String> = Vec::new();    let mut seen_people: HashSet<String> = HashSet::new();    for link in &links {        if link.record_kind == "person" && seen_people.insert(link.record_id.clone()) {            linked_people.push(link.record_id.clone());        }    }    let explicit_keys: HashSet<String> = links        .iter()        .map(|link| format!("{}:{}", link.record_kind, link.record_id))        .collect();    let all_derived = derived_members_for_people(&ctx.read, &linked_people)?;    // DEDUPED AGAINST THE EXPLICIT LINKS, which are appended first and keep    // their notes — a person's own DM thread that was ALSO filed here is one    // thread, not two lines.    let derived: Vec<(ProjectLinkKind, Map<String, Value>)> = all_derived        .into_iter()        .filter(|(kind, row)| {            !explicit_keys.contains(&format!("{kind}:{}", text(row, "id").unwrap_or_default()))        })        .collect();    let mut thread_rows: Vec<Map<String, Value>> = links        .iter()        .filter(|link| link.record_kind == "thread")        .filter_map(|link| {            row_by_key                .get(&format!("thread:{}", link.record_id))                .cloned()        })        .collect();    thread_rows.extend(        derived            .iter()            .filter(|(kind, _)| *kind == ProjectLinkKind::Thread)            .map(|(_, row)| row.clone()),    );    let dm_names = contact_names(&ctx.read, &thread_rows)?;    // Insertion-ordered groups: the response object's key order is the order    // the first member of each group arrived, exactly as the TypeScript's `Map`    // gives it.    //    // Each line travels beside the MOMENT its section is ordered by    // ([`ordering_moment`]), because the cap falls AFTER the sort: a page that    // capped on arrival order and then sorted would show "3 of 40" newest-first    // rows drawn from the forty oldest — which is exactly what the owner read    // as "the walkthroughs are upside down".    type Line = (Option<String>, Value);    let mut groups: Vec<(&'static str, Vec<Line>)> = Vec::new();    let mut group_counts: Vec<(&'static str, i64)> = Vec::new();    let whole_groups = args.whole_groups;    let bump = |groups: &mut Vec<(&'static str, Vec<Line>)>,                counts: &mut Vec<(&'static str, i64)>,                group: &'static str,                at: Option<String>,                line: Value| {        match counts.iter_mut().find(|(name, _)| *name == group) {            Some(entry) => entry.1 += 1,            None => counts.push((group, 1)),        }        match groups.iter_mut().find(|(name, _)| *name == group) {            Some(entry) => entry.1.push((at, line)),            None => groups.push((group, vec![(at, line)])),        }    };    for link in &links {        let Some(kind) = ProjectLinkKind::parse(&link.record_kind) else {            continue;        };        let source = kind_source(kind);        // The record was deleted; the link is dangling.        let Some(row) = row_by_key.get(&format!("{kind}:{}", link.record_id)) else {            continue;        };        // An ARCHIVED page of the project's own is gone from the project, and        // this is where it leaves. Archiving is how a project page is taken off        // a project (`unlink_from_project` refuses to remove a LIVE mirror), so        // if the mirror kept reporting afterwards the entry would sit in the        // buckets and the counts for ever with no act left that could remove        // it. Only a project-scoped mirror is dropped: an archived OWNER page        // somebody linked with a `#` chip is a deliberate membership and still        // renders, marked `archived`.        let Some(group) = member_group(kind, row) else {            continue;        };        let mut title = title_of(kind, row);        if kind == ProjectLinkKind::Thread && text(row, "title").is_none() {            if let Some(contact_id) = text(row, "contact_id") {                if let Some(name) = dm_names.get(&contact_id) {                    title = name.clone();                }            }        }        // A PROCEDURE IS A NOTE WHOSE FIRST LINE NAMES ITS TRIGGER, and it        // leaves the `notes` bucket for its own — a session scanning the project        // for the procedure that fits the task in front of it should not have to        // read every note to find them. The rule is        // `cotton_core::rules::memory_briefing::procedure_trigger`, the same        // function `brief` uses, so the project page and the briefing cannot        // disagree about what a procedure is.        let trigger = (kind == ProjectLinkKind::Note)            .then(|| procedure_trigger(text(row, "body").unwrap_or_default().as_str()))            .flatten();        let mut line = Map::new();        line.insert("id".to_string(), Value::from(link.record_id.clone()));        line.insert(            if source.group == "people" || source.group == "locations" {                "name".to_string()            } else {                "title".to_string()            },            Value::from(title),        );        if let Some(trigger) = trigger {            line.insert("trigger".to_string(), Value::from(trigger));        }        for (key, value) in extras_of(kind, row) {            line.insert(key, value);        }        if kind == ProjectLinkKind::Memory {            line.insert("pinned".to_string(), Value::Bool(link.pinned));            line.insert(                "position".to_string(),                link.position.map_or(Value::Null, js_number),            );        }        if let Some(note) = link.note.clone().filter(|note| !note.is_empty()) {            line.insert("note".to_string(), Value::from(note));        }        let at = ordering_moment(kind, row, &link.created_at);        bump(            &mut groups,            &mut group_counts,            group,            at,            Value::Object(line),        );    }    // …then the derived rows, after every explicit one, through the SAME    // projection. A derived member has no link row, so it has no note and    // cannot be unlinked — the way to remove one is to unlink the PERSON — and    // it says so with `derived: true` rather than looking like a membership    // somebody chose. Counted like any other member: the counts and the    // sections have to agree, or a reader is told there is more than it can see.    for (kind, row) in &derived {        let source = kind_source(*kind);        let mut title = title_of(*kind, row);        if *kind == ProjectLinkKind::Thread && text(row, "title").is_none() {            if let Some(contact_id) = text(row, "contact_id") {                if let Some(name) = dm_names.get(&contact_id) {                    title = name.clone();                }            }        }        let mut line = Map::new();        line.insert("id".to_string(), or_null(text(row, "id")));        line.insert("title".to_string(), Value::from(title));        for (key, value) in extras_of(*kind, row) {            line.insert(key, value);        }        line.insert("derived".to_string(), Value::Bool(true));        // A derived member has no link row, so it has no filing date — which        // costs nothing, because the two kinds that derive (a conversation, a        // call) both carry a moment of their own.        let at = ordering_moment(*kind, row, "");        bump(            &mut groups,            &mut group_counts,            source.group,            at,            Value::Object(line),        );    }    // Memory reads in THIS project's arrangement — pinned first, then position    // (D9) — the ONE section that is not newest-first, because "what order is my    // memory in" has exactly one answer and recency is not it.    if let Some((_, memory)) = groups.iter_mut().find(|(name, _)| *name == "memory") {        memory.sort_by(|(_, a), (_, b)| {            let pinned = |value: &Value| {                u8::from(                    value                        .get("pinned")                        .and_then(Value::as_bool)                        .unwrap_or(false),                )            };            let position =                |value: &Value| value.get("position").and_then(Value::as_f64).unwrap_or(0.0);            let slug = |value: &Value| {                value                    .get("slug")                    .and_then(Value::as_str)                    .unwrap_or("")                    .to_string()            };            pinned(b)                .cmp(&pinned(a))                .then(                    position(a)                        .partial_cmp(&position(b))                        .unwrap_or(std::cmp::Ordering::Equal),                )                .then(slug(a).cmp(&slug(b)))        });    }    // EVERY OTHER SECTION READS NEWEST FIRST, off the moment its own kind is    // known by ([`ordering_moment`]) — the walkthroughs the owner read upside    // down, and the rest with them, because "the newest is at the bottom" is    // not a question anybody asks a section one at a time. Todos are the one    // exception: work is read by what is owed NEXT.    //    // `sort_by` is stable, so members that share a moment keep the order they    // were filed in.    for (group, lines) in groups.iter_mut() {        if *group == "memory" {            continue;        }        if *group == "procedures" {            // Procedures are the second exception: a procedure is looked up by            // NAME, so the section reads alphabetically — the same order `brief`            // prints them in, so the page and the briefing agree.            let procedure_title = |line: &Value| {                line.get("title")                    .and_then(Value::as_str)                    .unwrap_or("")                    .to_string()            };            lines.sort_by_key(|(_, a)| procedure_title(a));        } else if *group == "todos" {            lines.sort_by(|(a, _), (b, _)| soonest_first(a, b));        } else {            lines.sort_by(|(a, _), (b, _)| newest_first(a, b));        }    }    // Todos split by what is still open, and SPLIT BEFORE THE CAP: `openCount`    // is the figure a person reads as work remaining (the owner's rule, from    // seeing "120 to-dos" on a project whose todos were nearly all finished),    // and a cap is a decision about how many rows TRAVEL. Counting after it    // made both figures a statement about the fifty soonest-due rows instead of    // about the project. The cap then falls on the open list alone — the closed    // ones never travel.    let todos_out = match groups.iter().position(|(name, _)| *name == "todos") {        None => None,        Some(index) => {            let (_, todos) = groups.remove(index);            let mut open: Vec<Value> = todos                .iter()                .map(|(_, todo)| todo)                .filter(|todo| todo.get("status").and_then(Value::as_str) == Some("open"))                .cloned()                .collect();            let mut out = Map::new();            out.insert("openCount".to_string(), Value::from(open.len() as i64));            out.insert(                "closedCount".to_string(),                Value::from((todos.len() - open.len()) as i64),            );            // A cap that does not SAY it is one reads as the whole list, and a            // project with 150 open todos then plans off fifty. `openCount` is            // already the true figure; these two say what to call for the rest,            // by name, so a reader never has to infer the walk.            if !whole_groups && open.len() > GROUP_CAP {                open.truncate(GROUP_CAP);                out.insert("moreOpenTodos".to_string(), Value::Bool(true));                out.insert(                    "note".to_string(),                    Value::from(format!(                        "openCount is the whole figure; the {GROUP_CAP} soonest-due open todos \                         travel here. list_todos {{ project: {} }} pages through all of them.",                        quoted(&args.slug)                    )),                );            }            out.insert("open".to_string(), Value::Array(open));            Some(out)        }    };    // …and ONLY THEN the cap. A group's `count` still states the whole    // membership, so what travels is the first `GROUP_CAP` of the section's own    // order rather than of whatever order the links were created in.    if !whole_groups {        for (_, lines) in groups.iter_mut() {            lines.truncate(GROUP_CAP);        }    }    // Sessions and the project's own journal pages bind by project_id, not by    // link rows. (Memory did too until the memory-home change; it is in `linked.memory`    // now, in the project's own order.)    let sessions = project_sessions(ctx, &project_id)?;    let journal = project_journal(ctx, &project_id)?;    // The project's summary, with its provenance and how much has been linked    // since it was written. The arrivals are HANDED to the cue rather than    // re-queried: this read already holds every link row, `created_at` included.    let arrivals: Vec<String> = all_links        .iter()        .map(|link| link.created_at.clone())        .collect();    let summary = project_summary(&project, &arrivals);    let transaction_ids: Vec<String> = links        .iter()        .filter(|link| link.record_kind == "transaction")        .map(|link| link.record_id.clone())        .collect();    let money = project_money(ctx, &transaction_ids)?;    // The brand kit's logo files. ALWAYS present (as `[]` when there are none),    // unlike `brand` itself: an empty array is the honest answer to "which slots    // are filled", while an absent `brand` key means "nobody wrote one".    //    // `include_brand_asset_urls` mints nothing here: this server has no    // presigner on the tool `Ctx` (design S3 owns the object store), so the    // facts travel and the urls do not — which is what the TypeScript answers    // on a server with no store, rather than losing the whole page over a link    // it cannot mint.    let assets = brand_assets_of(&ctx.read, &links)?;    let _ = args.include_brand_asset_urls;    // THE PROJECT'S SECTIONS, each with what it holds — computed HERE, off the    // figures this read has already counted, through the same rules Home's    // catalogue reads them by (`sections::holding`).    let open_todos = todos_out        .as_ref()        .and_then(|todos| todos.get("openCount"))        .and_then(Value::as_u64)        .unwrap_or(0);    let figures = SectionFigures {        groups: group_counts            .iter()            .map(|(group, count)| (*group, u64::try_from(*count).unwrap_or(0)))            .collect(),        open_todos,        sessions: project_session_count(&ctx.read, &project_id)?,        has_summary: text(&project, "description").is_some_and(|d| !d.trim().is_empty()),        brand_holds: brand_kit_holds(project.get("brand"), assets.len()),    };    let sections: Vec<Value> = present_sections(&default_order(), |section| holding(&figures, section))    .into_iter()    .map(|present| {        let mut line = Map::new();        line.insert("key".to_string(), Value::from(present.section.as_str()));        if let Holding::Count(count) = present.holding {            line.insert("count".to_string(), Value::from(count));        }        Value::Object(line)    })    .collect();    let mut project_answer = project_out(&project);    if let Some(summary) = summary {        project_answer.insert("summary".to_string(), summary);    }    project_answer.insert("money".to_string(), money);    let mut linked = Map::new();    for (group, lines) in groups {        linked.insert(            group.to_string(),            Value::Array(lines.into_iter().map(|(_, line)| line).collect()),        );    }    if let Some(todos) = todos_out {        linked.insert("todos".to_string(), Value::Object(todos));    }    let mut counts = Map::new();    for (group, count) in group_counts {        counts.insert(group.to_string(), Value::from(count));    }    let mut out = Map::new();    out.insert("project".to_string(), Value::Object(project_answer));    out.insert(        "brandAssets".to_string(),        Value::Array(brand_asset_values(&assets)),    );    out.insert("linked".to_string(), Value::Object(linked));    out.insert("counts".to_string(), Value::Object(counts));    out.insert("sessions".to_string(), sessions);    out.insert("journal".to_string(), journal);    // `sections` is what the page draws, top first: `{key, count}` for a list,    // `{key}` for a single thing, and nothing for a section that holds    // nothing — in the default order; the app draws each as a tile on Home,    // in the board's order.    out.insert("sections".to_string(), Value::Array(sections));    Ok(Value::Object(out))}/// How many coding sessions the project holds — its THREADS, bound by/// `project_id`. The standing conversation is not one of them: it is the top/// of the project's page, not a row in its Sessions section.pub(crate) fn project_session_count(read: &ReadDb<'_>, project_id: &str) -> Result<u64, ToolFailure> {    Ok(read_rows(            read,            &Query::on("cotton_sessions")            .columns(&["id"])            .eq("project_id", project_id.to_string())            .eq("kind", "thread".to_string()),    )?    .len() as u64)}/// The project's own summary object, built from the row already in hand.////// Not [`crate::mcp::handlers::common::summary_out`]: that one COUNTS arrivals/// in SQL, and this caller already holds every link row. Two ways to count,/// deliberately — one way to say what the count MEANS.fn project_summary(project: &Map<String, Value>, arrivals: &[String]) -> Option<Value> {    let source = summary_source(SummaryKind::Project);    let prose = text(project, source.column).filter(|text| !text.is_empty())?;    let updated_at = text(project, source.provenance.updated_at);    let since = staleness_of(SummaryKind::Project, updated_at.as_deref(), arrivals);    let mut out = Map::new();    out.insert("text".to_string(), Value::from(prose));    out.insert(        "by".to_string(),        or_null(text(project, source.provenance.by)),    );    out.insert("updatedAt".to_string(), or_null(updated_at));    if let Some(since) = since {        let mut cue = Map::new();        cue.insert("count".to_string(), Value::from(since.count));        cue.insert("noun".to_string(), Value::from(since.noun.as_str()));        out.insert("since".to_string(), Value::Object(cue));    }    Some(Value::Object(out))}/// What a project cost — folded over its own linked, POSTED transactions'/// category lines only, the same convention `monthFlows` uses: a transfer/// between the owner's own accounts touches no category and so never reads as/// money in or out.////// Signed against the user's own money: out is negative, in is positive, so/// `netMinor` reads the way a person would say it. One total per currency in/// `totals`, never summed across currencies; always present with `count`, an/// empty `totals` when nothing is filed.fn project_money(ctx: &Ctx<'_>, transaction_ids: &[String]) -> Result<Value, ToolFailure> {    // One figure per currency, never summed across them: a euro spend and a    // rupee one are two totals.    let answer = |totals: &BTreeMap<String, (i64, i64)>, count: i64| {        let totals: Vec<Value> = totals            .iter()            .map(|(currency, (in_minor, out_minor))| {                serde_json::json!({                    "currency": currency,                    "inMinor": in_minor,                    "outMinor": out_minor,                    "netMinor": in_minor - out_minor,                })            })            .collect();        let mut money = Map::new();        money.insert("totals".to_string(), Value::Array(totals));        money.insert("count".to_string(), Value::from(count));        Value::Object(money)    };    if transaction_ids.is_empty() {        return Ok(answer(&BTreeMap::new(), 0));    }    let actual = in_chunks(transaction_ids, |batch| {        rows(            ctx,            &Query::on("cotton_money_transactions")                .columns(&["id", "amount_minor", "direction", "currency"])                .eq("status", "actual".to_string())                .eq("amount_known", true)                .eq("moves_money", true)                .filter(Filter::IsNull("trashed_at".into()))                .filter(Filter::SoftAbsent("transfer_of".into()))                .filter(Filter::In(                    "id".into(),                    batch.iter().map(|id| id.clone().into()).collect(),                )),        )    })?;    let mut totals: BTreeMap<String, (i64, i64)> = BTreeMap::new();    for row in &actual {        let amount = row            .get("amount_minor")            .and_then(Value::as_i64)            .ok_or_else(|| ToolFailure::new("A known money row has no amount"))?;        let total = totals            .entry(text(row, "currency").unwrap_or_default())            .or_default();        let value = if text(row, "direction").as_deref() == Some("in") {            &mut total.0        } else {            &mut total.1        };        *value = value            .checked_add(amount)            .ok_or_else(|| ToolFailure::new("Money total exceeds a whole amount"))?;    }    Ok(answer(&totals, actual.len() as i64))}/// What happened lately, in full.////// Read by the IDENTITY COLUMN, not by the links table (§3.2): these are the/// project's OWN pages. An owner page he linked with a `#` chip is a page of/// HIS day that is relevant here — it belongs in the linked groups, and putting/// it in this list would read as progress somebody wrote for the project.////// Bodies travel whole, unlike every other group's compact row: a dated title/// is exactly what this read already gave and could not be used for.fn project_journal(ctx: &Ctx<'_>, project_id: &str) -> Result<Value, ToolFailure> {    let pages = project_journal_rows(ctx, project_id, JOURNAL_RECENT)?;    let recent: Vec<Value> = pages        .into_iter()        .map(|row| {            let mut entry = Map::new();            entry.insert("id".to_string(), or_null(text(&row, "id")));            entry.insert("date".to_string(), or_null(text(&row, "journal_date")));            entry.insert("text".to_string(), or_null(text(&row, "body")));            entry.insert("author".to_string(), or_null(text(&row, "author_label")));            Value::Object(entry)        })        .collect();    let mut out = Map::new();    out.insert("recent".to_string(), Value::Array(recent));    Ok(Value::Object(out))}fn project_sessions(ctx: &Ctx<'_>, project_id: &str) -> Result<Value, ToolFailure> {    let found = rows(        ctx,        &Query::on("cotton_sessions")            .columns(&["tool", "machine", "last_active_at", "title", "summary"])            .eq("project_id", project_id.to_string())            .order_by("last_active_at", Order::Desc)            .limit(3),    )?;    Ok(Value::Array(        found            .into_iter()            .map(|row| {                let mut session = Map::new();                session.insert("tool".to_string(), or_null(text(&row, "tool")));                session.insert("machine".to_string(), or_null(text(&row, "machine")));                session.insert(                    "lastActiveAt".to_string(),                    or_null(text(&row, "last_active_at")),                );                put(&mut session, "title", text(&row, "title").map(Value::from));                put(                    &mut session,                    "summary",                    text(&row, "summary").map(Value::from),                );                Value::Object(session)            })            .collect(),    ))}