Cotton code
171 lines · 7.3 KB · RustRaw
//! `today_agenda` — the one call an assistant makes at the top of a//! conversation, from `packages/server/src/mcp/records.ts`.//!//! Nothing here decides what "today" is twice. The zone is the call's, else the//! workspace's, else UTC (`common::workspace_timezone`); the window is//! `common::day_window`; the day's occurrences come from the SAME three-part//! candidate read `list_events` uses (`records_1::events::occurrence_candidates`)//! and the SAME expansion (`cotton_core::rules::series::expand_calendar`).//!//! The expansion is the part that is easy to get wrong by leaving out. A read//! that filtered `starts_at` alone only ever matches a series' FIRST day, so a//! weekly meeting was absent from every "what's on today" after the week it was//! created — which is the question this tool exists to answer.use cotton_core::transforms::rrule::DateRange;use cotton_core::rules::series::{expand_calendar, SeriesRow};use cotton_core::transforms::moment_split::split_moment;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    day_window, now_ms, optional_zone, parse_ms, rows, text, workspace_timezone, Valid,};use crate::mcp::handlers::records_1::events::{occurrence_candidates, series_row_of};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};/// How much of the day fits in one answer. Both halves share the cap, as the/// TypeScript's `.limit(50)` and `.slice(0, 50)` do.const AGENDA_CAP: i64 = 50;// ── validation ──────────────────────────────────────────────────────────────#[derive(Debug, Clone, Default)]pub struct TodayArgs {    /// The zone this day is read in, when the caller named one.    pub timezone: Option<String>,}/// `validateToday`.////// No zone named is not an error and not UTC: the workspace's own zone is the/// answer, and it is read from the file at call time. A zone that IS named is/// asked of the runtime, never of a list — tzdata moves, and the only question/// that matters is whether THIS runtime can format a clock in it.pub fn validate_today(args: &Map<String, Value>) -> Valid<TodayArgs> {    Ok(TodayArgs {        timezone: optional_zone(args)?,    })}// ── the tool ────────────────────────────────────────────────────────────────/// The day and clock a due instant reads as — present only when there is a/// zone to read them in, and dropped when the instant does not parse.////// A reading that threw would take the whole list with it, and the raw instant/// is already in the answer.fn todo_due_fields(item: &mut Map<String, Value>, due_at: Option<&str>, timezone: &str) {    let Some(due_at) = due_at else { return };    let Ok(due) = split_moment(due_at, timezone) else {        return;    };    item.insert("dueDate".to_string(), Value::from(due.date));    item.insert(        "dueTime".to_string(),        due.time.map_or(Value::Null, Value::from),    );}pub fn today_agenda(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_today(args)?;    let timezone = match args.timezone {        Some(named) => named,        None => workspace_timezone(ctx)?,    };    let window = day_window(&timezone, now_ms(ctx))?;    let todos = rows(        ctx,        &Query::on("cotton_todos")            .columns(&["id", "title", "due_at", "status"])            .eq("status", "open".to_string())            .filter(Filter::IsNull("trashed_at".to_string()))            // Overdue counts as today's problem — that is what "what's left"            // means.            .filter(Filter::Lt(                "due_at".to_string(),                SqlValue::Text(window.end.clone()),            ))            .order_by("due_at", Order::Asc)            .limit(AGENDA_CAP),    )?;    let todos: Vec<Value> = todos        .iter()        .map(|row| {            let due_at = text(row, "due_at");            let mut item = Map::new();            item.insert("id".to_string(), Value::from(text(row, "id")));            item.insert("title".to_string(), Value::from(text(row, "title")));            item.insert(                "dueAt".to_string(),                due_at.clone().map_or(Value::Null, Value::from),            );            todo_due_fields(&mut item, due_at.as_deref(), &timezone);            item.insert(                "overdue".to_string(),                Value::Bool(due_at.is_some_and(|due| due < window.start)),            );            Value::Object(item)        })        .collect();    // Today's calendar is EXPANDED, exactly as `list_events {expand:true}` is.    let candidates = occurrence_candidates(ctx, &window.start, &window.end)?;    let series: Vec<SeriesRow> = candidates.iter().map(series_row_of).collect();    let range = DateRange {        from: parse_ms(&window.start).unwrap_or_default(),        // The window is half-open on the day boundary, and an occurrence        // starting at exactly midnight tomorrow belongs to tomorrow: a        // millisecond back keeps `expand_calendar`'s inclusive range honest        // about that.        to: parse_ms(&window.end).unwrap_or_default() - 1,    };    let occurrences = expand_calendar(&series, range, &timezone)        .map_err(|error| ToolFailure::new(error.to_string()))?;    let events: Vec<Value> = occurrences        .into_iter()        .take(AGENDA_CAP as usize)        .filter_map(|occurrence| {            let row = candidates                .iter()                .find(|candidate| candidate.id == occurrence.event_id)?;            let mut item = Map::new();            item.insert("id".to_string(), Value::from(row.id.clone()));            item.insert("title".to_string(), Value::from(row.title.clone()));            item.insert("startsAt".to_string(), Value::from(occurrence.starts_at));            item.insert(                "endsAt".to_string(),                occurrence.ends_at.map_or(Value::Null, Value::from),            );            item.insert("allDay".to_string(), Value::Bool(row.all_day));            item.insert(                "location".to_string(),                row.location.clone().map_or(Value::Null, Value::from),            );            // Only where there IS a series: an ordinary event carrying a null            // seriesId would read as "this belongs to nothing", which is noise            // on the one call an assistant makes at the top of every            // conversation.            if let Some(series_id) = occurrence.series_id {                item.insert("seriesId".to_string(), Value::from(series_id));                item.insert(                    "occurrenceAt".to_string(),                    Value::from(occurrence.occurrence_at),                );            }            Some(Value::Object(item))        })        .collect();    let mut out = Map::new();    out.insert("date".to_string(), Value::from(window.date));    out.insert("timezone".to_string(), Value::from(timezone));    out.insert("todos".to_string(), Value::Array(todos));    out.insert("events".to_string(), Value::Array(events));    Ok(Value::Object(out))}