Cotton code
1558 lines · 61.7 KB · RustRaw
//! `create_event`, `list_events`, `update_event`, `update_events`,//! `delete_event`, `delete_events` — the events block of//! `packages/server/src/mcp/records.ts`.//!//! Nothing here decides what an edit to a repeating event MEANS: the planners//! are `cotton_core::rules::event_edits` and the expansion is//! `cotton_core::rules::series`, because the phone's service layer carries out//! the same plans and two implementations of "editing this Tuesday means a new//! row that claims Tuesday's instant" would eventually disagree — an//! appointment that exists on one device and not on the other.//!//! The one thing this file DOES own is the candidate read, and it is three//! reads rather than one on purpose: what happens inside the window, the//! repeating masters that started before it, and the moved occurrences whose//! CLAIM is inside it. Miss the second and a weekly meeting appears once, ever;//! miss the third and the day an occurrence was moved away from shows it again.use crate::mcp::writer::Retract;use cotton_core::rules::event_edits::{    plan_event_delete, plan_event_untrash, plan_occurrence_cancel, plan_occurrence_edit, plan_series_move,    EventRowForPlan, FieldChange, OccurrenceEdit, OccurrencePatch,};use cotton_core::transforms::rrule::DateRange;use cotton_core::rules::series::{expand_calendar, SeriesRow};use cotton_store::protocol::derived_id::{link_id_for, LinkRow};use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    calendars, flag, insert_row, is_known_zone, iso_of_ms,    maybe_row, now_iso, now_ms, optional_enum, or_null, parse_ms, put, quoted, require_uuid, rows,    start_of_day_in, text, today_in, update_row, workspace_timezone, workspace_timezone_or_null,    Clearable, Valid, DAY_MS,};use crate::mcp::handlers::records_1::validate::{    validate_create_event, validate_delete_event, validate_delete_events, validate_list_events,    validate_update_event, validate_update_events, EventPatch,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};/// The guest rows of an event. Its own table, keyed by `event_id` alone — no/// workspace column: the file is the database.const ATTENDEES: &str = "cotton_event_attendees";/// Every column an edit plan, an expansion and a reply need — ONE list,/// because a read that fetched four of them and handed the planner a row/// missing `exdates` would cancel an occurrence by writing a list with one/// entry in it.const EVENT_COLUMNS: &[&str] = &[    "id",    "collection_id",    "title",    "notes",    "location",    "starts_at",    "ends_at",    "all_day",    "rrule",    "exdates",    "series_id",    "original_starts_at",    "gcal_id",    "gcal_etag",    "sync_state",    "trashed_at",];/// How wide a candidate read may go before it is a scan of the whole calendar.const EVENT_CANDIDATE_CAP: i64 = 1000;// ── rows ────────────────────────────────────────────────────────────────────fn event_row(row: &Map<String, Value>) -> EventRowForPlan {    EventRowForPlan {        id: text(row, "id").unwrap_or_default(),        collection_id: text(row, "collection_id"),        title: text(row, "title").unwrap_or_default(),        notes: text(row, "notes"),        location: text(row, "location"),        starts_at: text(row, "starts_at").unwrap_or_default(),        ends_at: text(row, "ends_at"),        all_day: flag(row, "all_day"),        rrule: text(row, "rrule"),        exdates: row.get("exdates").and_then(Value::as_array).map(|items| {            items                .iter()                .filter_map(Value::as_str)                .map(str::to_string)                .collect()        }),        series_id: text(row, "series_id"),        original_starts_at: text(row, "original_starts_at"),        gcal_id: text(row, "gcal_id"),        sync_state: text(row, "sync_state"),        trashed_at: text(row, "trashed_at"),    }}/// A stored row → what the expansion reads off it.pub fn series_row_of(row: &EventRowForPlan) -> SeriesRow {    SeriesRow {        id: row.id.clone(),        starts_at: row.starts_at.clone(),        ends_at: row.ends_at.clone(),        rrule: row.rrule.clone(),        exdates: row.exdates.clone(),        series_id: row.series_id.clone(),        original_starts_at: row.original_starts_at.clone(),        trashed_at: row.trashed_at.clone(),    }}/// The read every event query starts from: every event of the database. An/// event is the database's, never reached through a calendar — the object/// keeps none, and a copy held out every event that named one it did not/// hold (27 Oct 2026). The calendar an event names is a word about it, read/// where it is said (`list_events`' `calendar`), never a scope.fn event_query() -> Query {    Query::on("cotton_events").columns(EVENT_COLUMNS)}fn event_rows(ctx: &Ctx<'_>, query: &Query) -> Valid<Vec<EventRowForPlan>> {    Ok(rows(ctx, query)?.iter().map(event_row).collect())}/// How far ahead a repeating event's next occurrence is looked for: a year/// and a day, so a yearly series that fell yesterday is still found.const NEXT_OCCURRENCE_DAYS: i64 = 367;/// Every occurrence of every repeating event from `from` (an instant) to a/// year and a day on, soonest first: `(master id, starts_at, ends_at)`. The/// Calendar stands a weekly swim under each day it happens, not only the/// next (`day_plan`). An occurrence moved away is its own row and is skipped.pub fn occurrences_from(ctx: &Ctx<'_>, from: i64) -> Valid<Vec<(String, String, Option<String>)>> {    let next = Vec::new();    let masters = event_rows(        ctx,        &event_query()            .filter(Filter::NotBlank("rrule".to_string()))            .filter(Filter::IsNull("series_id".to_string()))            .filter(Filter::IsNull("trashed_at".to_string()))            .limit(EVENT_CANDIDATE_CAP),    )?;    if masters.is_empty() {        return Ok(next);    }    let master_ids: Vec<SqlValue> = masters.iter().map(|row| SqlValue::Text(row.id.clone())).collect();    let exceptions = event_rows(        ctx,        &event_query().filter(Filter::In("series_id".to_string(), master_ids)),    )?;    let series: Vec<SeriesRow> = masters.iter().chain(&exceptions).map(series_row_of).collect();    let range = DateRange { from, to: from + NEXT_OCCURRENCE_DAYS * DAY_MS };    let zone = workspace_timezone(ctx)?;    let occurrences =        expand_calendar(&series, range, &zone).map_err(|error| ToolFailure::new(error.to_string()))?;    let mut all: Vec<(String, String, Option<String>)> = occurrences        .into_iter()        .filter(|occurrence| !occurrence.is_exception)        .map(|occurrence| (occurrence.event_id, occurrence.starts_at, occurrence.ends_at))        .collect();    // An all-day occurrence starts on a bare day: its midnight, for order.    let at = |starts: &str| parse_ms(starts).or_else(|| parse_ms(&format!("{starts}T00:00:00Z")));    all.sort_by_key(|(_, starts, _)| at(starts).unwrap_or(i64::MAX));    Ok(all)}/// One fetch events' writes share — the event of that id in this database.fn event_scoped(ctx: &Ctx<'_>, id: &str) -> Valid<EventRowForPlan> {    let query = event_query().eq("id", id.to_string());    event_rows(ctx, &query)?        .into_iter()        .next()        .ok_or_else(|| ToolFailure::new(format!("no event with id {id}")))}/// The exception row standing on one instant of a series, if there is one.////// Matched by INSTANT, not by string: `…T06:30:00Z` and `…T06:30:00.000Z` are/// the same moment, and an assistant that re-typed the instant it was given/// must reach the row it already made rather than mint a second one claiming/// the same occurrence.fn exception_claiming(    ctx: &Ctx<'_>,    series_id: &str,    occurrence_at: &str,) -> Valid<Option<EventRowForPlan>> {    let query = event_query().eq("series_id", series_id.to_string());    let at = parse_ms(occurrence_at);    Ok(event_rows(ctx, &query)?.into_iter().find(|row| {        row.original_starts_at            .as_deref()            .and_then(parse_ms)            .is_some_and(|claim| Some(claim) == at)    }))}/// Every row that could DRAW an occurrence inside a window.////// Nothing filters `trashed_at` in SQL, deliberately: a trashed master must/// arrive WITH its exceptions or the expansion reads them as orphans and draws/// them as ordinary events, and a trashed EXCEPTION still claims its instant./// `expand_calendar` is the one place that knows a row in the trash draws/// nothing.pub fn occurrence_candidates(    ctx: &Ctx<'_>,    from: &str,    to: &str,) -> Valid<Vec<EventRowForPlan>> {    let mut candidates: Vec<EventRowForPlan> = Vec::new();    let collect = |found: Vec<EventRowForPlan>, into: &mut Vec<EventRowForPlan>| {        for row in found {            if let Some(slot) = into.iter_mut().find(|held| held.id == row.id) {                *slot = row;            } else {                into.push(row);            }        }    };    collect(        event_rows(            ctx,            &event_query()                .filter(Filter::Gte(                    "starts_at".to_string(),                    SqlValue::Text(from.to_string()),                ))                .filter(Filter::Lte(                    "starts_at".to_string(),                    SqlValue::Text(to.to_string()),                ))                .limit(EVENT_CANDIDATE_CAP),        )?,        &mut candidates,    );    collect(        event_rows(            ctx,            &event_query()                .filter(Filter::NotNull("rrule".to_string()))                .filter(Filter::Lt(                    "starts_at".to_string(),                    SqlValue::Text(from.to_string()),                ))                .limit(EVENT_CANDIDATE_CAP),        )?,        &mut candidates,    );    collect(        event_rows(            ctx,            &event_query()                .filter(Filter::NotNull("original_starts_at".to_string()))                .filter(Filter::Gte(                    "original_starts_at".to_string(),                    SqlValue::Text(from.to_string()),                ))                .filter(Filter::Lte(                    "original_starts_at".to_string(),                    SqlValue::Text(to.to_string()),                ))                .limit(EVENT_CANDIDATE_CAP),        )?,        &mut candidates,    );    Ok(candidates)}/// How many live exceptions each of these masters has.fn exception_counts(    ctx: &Ctx<'_>,    master_ids: &[String],) -> Valid<std::collections::HashMap<String, i64>> {    let mut counts = std::collections::HashMap::new();    if master_ids.is_empty() {        return Ok(counts);    }    let query = Query::on("cotton_events")        .columns(&["series_id"])        .filter(Filter::In(            "series_id".to_string(),            master_ids                .iter()                .map(|id| SqlValue::Text(id.clone()))                .collect(),        ))        .filter(Filter::IsNull("trashed_at".to_string()));    for row in rows(ctx, &query)? {        if let Some(series_id) = text(&row, "series_id") {            *counts.entry(series_id).or_insert(0) += 1;        }    }    Ok(counts)}// ── the zone a WRITE resolves a day in ──────────────────────────────────────/// Never UTC. The host runs `TZ=UTC`, so a fallback here would put a whole-day/// event on the wrong day for everyone east or west of Greenwich — and an/// appointment on the wrong day is not a thing the owner notices until they/// miss it.fn event_writer_zone(ctx: &Ctx<'_>, named: Option<&str>) -> Valid<String> {    let zone = match named {        Some(zone) => zone.to_string(),        None => workspace_timezone_or_null(ctx)?.ok_or_else(|| {            ToolFailure::new(                "Cotton does not know which timezone this database lives in, and which day an \                 all-day event covers cannot be guessed — pass timezone (an IANA zone like \                 Asia/Kolkata), or set it once in the app.",            )        })?,    };    if !is_known_zone(&zone) {        return Err(ToolFailure::new(format!(            "unknown timezone {}",            quoted(&zone)        )));    }    Ok(zone)}/// A whole-day event's instants, in the zone that decides which day it is.////// The start is midnight local on the first day; the end is the last/// millisecond of the LAST INCLUDED day, derived from the next day's midnight/// rather than by adding 24 hours, so a day that is 23 or 25 hours long still/// ends where it ends.fn all_day_window(zone: &str, starts_at: &str, ends_at: Option<&str>) -> Valid<(String, String)> {    let start_ms = parse_ms(starts_at)        .ok_or_else(|| ToolFailure::new("startsAt must be an ISO 8601 timestamp"))?;    let start = start_of_day_in(&today_in(zone, start_ms)?, zone)?;    let last_ms = match ends_at {        Some(ends_at) => parse_ms(ends_at)            .ok_or_else(|| ToolFailure::new("endsAt must be an ISO 8601 timestamp"))?,        None => start_ms,    };    let last_start = start_of_day_in(&today_in(zone, last_ms)?, zone)?;    // Noon of the following day, then that day's own midnight: a DST-safe way    // to ask for "the day after this one".    let day_after = today_in(zone, last_start + DAY_MS + DAY_MS / 2)?;    Ok((        iso_of_ms(start),        iso_of_ms(start_of_day_in(&day_after, zone)? - 1),    ))}// ── create_event ────────────────────────────────────────────────────────────pub fn create_event(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let on_google = on_google_arg(args)?.unwrap_or(false);    let guests = args.get("attendees").filter(|list| list.as_array().is_some_and(|list| !list.is_empty())).cloned();    let args = validate_create_event(args)?;    let mut starts_at = args.starts_at;    let mut ends_at = args.ends_at;    if args.all_day == Some(true) {        let zone = event_writer_zone(ctx, args.timezone.as_deref())?;        // A bare day is that day in the zone, not UTC midnight read back        // there (the day before, anywhere west of Greenwich).        let noon_of = |day: &str| -> Valid<String> { Ok(iso_of_ms(start_of_day_in(day, &zone)? + DAY_MS / 2)) };        if let Some(day) = &args.days.0 {            starts_at = noon_of(day)?;        }        if let Some(day) = &args.days.1 {            ends_at = Some(noon_of(day)?);        }        let window = all_day_window(&zone, &starts_at, ends_at.as_deref())?;        starts_at = window.0;        ends_at = Some(window.1);    }    let id = ctx.new_uuid();    let mut patch = Map::new();    patch.insert("title".to_string(), Value::from(args.title));    patch.insert("starts_at".to_string(), Value::from(starts_at));    patch.insert(        "ends_at".to_string(),        ends_at.map_or(Value::Null, Value::from),    );    patch.insert(        "location".to_string(),        args.location.map_or(Value::Null, Value::from),    );    patch.insert(        "notes".to_string(),        args.notes.map_or(Value::Null, Value::from),    );    patch.insert(        "all_day".to_string(),        Value::Bool(args.all_day.unwrap_or(false)),    );    patch.insert(        "rrule".to_string(),        args.rrule.clone().map_or(Value::Null, Value::from),    );    patch.insert("on_google".to_string(), Value::Bool(on_google));    insert_row(ctx, "cotton_events", &id, patch)?;    ctx.commit()?;    // Guests make it Google's to carry: the serving Mac's next pass inserts it    // there, and that one insert is the invitation (`gcal_sync`).    if let Some(attendees) = guests {        let mut guest_args = Map::new();        guest_args.insert("eventId".to_string(), Value::from(id.clone()));        guest_args.insert("attendees".to_string(), attendees);        update_attendees(ctx, &guest_args)?;    }    let row = maybe_row(        ctx,        &Query::on("cotton_events")            .columns(&["id", "title", "starts_at", "ends_at", "all_day", "rrule"])            .eq("id", id.clone()),    )?    .ok_or_else(|| ToolFailure::new(format!("no event with id {id}")))?;    let mut out = row;    out.insert("onGoogle".to_string(), Value::Bool(on_google));    if let Some(rrule) = args.rrule {        out.insert("repeats".to_string(), Value::from(rrule));        out.insert(            "note".to_string(),            Value::from(                "a repeating event — list_events {expand:true} draws its occurrences, and \                 update_event / delete_event change one of them with occurrenceAt",            ),        );    }    Ok(Value::Object(out))}// ── list_events ─────────────────────────────────────────────────────────────pub fn list_events(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_list_events(args, now_ms(ctx))?;    // The calendar an event names, where this file holds it: a word about    // the event, never what lists it.    let named = calendars(ctx)?;    let name_of = |id: Option<&str>| -> Value {        named            .iter()            .find(|calendar| Some(calendar.id.as_str()) == id)            .map_or(Value::Null, |calendar| Value::from(calendar.name.clone()))    };    if !args.expand {        // The SERIES-ROW form. An exception is not listed on its own — it        // belongs to its master's expansion, and a row of its own here is the        // moved occurrence on two days again. It is counted on the master.        let found = event_rows(            ctx,            &event_query()                .filter(Filter::Gte(                    "starts_at".to_string(),                    SqlValue::Text(args.from.clone()),                ))                .filter(Filter::Lt(                    "starts_at".to_string(),                    SqlValue::Text(args.to.clone()),                ))                .filter(Filter::IsNull("series_id".to_string()))                .filter(Filter::IsNull("trashed_at".to_string()))                .order_by("starts_at", Order::Asc)                .limit(args.limit + 1),        )?;        let more = found.len() as i64 > args.limit;        let page: Vec<EventRowForPlan> = found.into_iter().take(args.limit as usize).collect();        let master_ids: Vec<String> = page            .iter()            .filter(|row| row.rrule.is_some())            .map(|row| row.id.clone())            .collect();        let exceptions = exception_counts(ctx, &master_ids)?;        let events: Vec<Value> = page            .iter()            .map(|row| {                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(row.starts_at.clone()));                item.insert(                    "endsAt".to_string(),                    row.ends_at.clone().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),                );                item.insert("calendar".to_string(), name_of(row.collection_id.as_deref()));                put(&mut item, "repeats", row.rrule.clone().map(Value::from));                let skips = row.exdates.clone().unwrap_or_default();                if !skips.is_empty() {                    item.insert(                        "skips".to_string(),                        Value::Array(skips.into_iter().map(Value::from).collect()),                    );                }                if let Some(count) = exceptions.get(&row.id).copied().filter(|count| *count > 0) {                    item.insert("exceptions".to_string(), Value::from(count));                }                if row.gcal_id.is_some() {                    item.insert("synced".to_string(), Value::Bool(true));                }                Value::Object(item)            })            .collect();        let mut out = Map::new();        out.insert("from".to_string(), Value::from(args.from));        out.insert("to".to_string(), Value::from(args.to));        out.insert("more".to_string(), Value::Bool(more));        out.insert("expanded".to_string(), Value::Bool(false));        out.insert("events".to_string(), Value::Array(events));        return Ok(Value::Object(out));    }    // The OCCURRENCE form.    let candidates = occurrence_candidates(ctx, &args.from, &args.to)?;    let series: Vec<SeriesRow> = candidates.iter().map(series_row_of).collect();    let range = DateRange {        from: parse_ms(&args.from).unwrap_or_default(),        to: parse_ms(&args.to).unwrap_or_default(),    };    // A READER, so the UTC floor is the honest "we were not told" rather than a    // guess — the refusal belongs to the writers.    let zone = workspace_timezone(ctx)?;    let occurrences = expand_calendar(&series, range, &zone)        .map_err(|error| ToolFailure::new(error.to_string()))?;    let more = occurrences.len() as i64 > args.limit;    let events: Vec<Value> = occurrences        .into_iter()        .take(args.limit as usize)        .filter_map(|occurrence| {            let row = candidates                .iter()                .find(|candidate| candidate.id == occurrence.event_id)?;            let master = occurrence                .series_id                .as_ref()                .and_then(|id| candidates.iter().find(|candidate| candidate.id == *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),            );            item.insert("calendar".to_string(), name_of(row.collection_id.as_deref()));            item.insert(                "occurrenceAt".to_string(),                Value::from(occurrence.occurrence_at),            );            item.insert(                "seriesId".to_string(),                occurrence.series_id.map_or(Value::Null, Value::from),            );            item.insert(                "isException".to_string(),                Value::Bool(occurrence.is_exception),            );            put(                &mut item,                "repeats",                master                    .and_then(|master| master.rrule.clone())                    .map(Value::from),            );            if row.gcal_id.is_some() {                item.insert("synced".to_string(), Value::Bool(true));            }            Some(Value::Object(item))        })        .collect();    let mut out = Map::new();    out.insert("from".to_string(), Value::from(args.from));    out.insert("to".to_string(), Value::from(args.to));    out.insert("more".to_string(), Value::Bool(more));    out.insert("expanded".to_string(), Value::Bool(true));    out.insert("events".to_string(), Value::Array(events));    Ok(Value::Object(out))}// ── the writes ──────────────────────────────────────────────────────────────/// A repeating event, and a call that named one of its occurrences.fn require_repeating(row: &EventRowForPlan, occurrence_at: &str) -> Valid<()> {    if row.rrule.is_some() {        return Ok(());    }    Err(ToolFailure::new(format!(        "event {} does not repeat, so it has no occurrence at {occurrence_at} — drop occurrenceAt \         and scope, and the whole event is what changes",        row.id    )))}/// A series whose START has moved takes its cancellations and its claims with/// it — `plan_series_move` decides, this carries it out.////// The zone is resolved LAZILY, only where there is something to re-key: an/// ordinary series with no cancellations and no moved occurrences must not/// start refusing to move because nobody has named a zone yet.fn rekey_series(    ctx: &mut Ctx<'_>,    master: &EventRowForPlan,    new_starts_at: &str,    timezone: Option<&str>,) -> Valid<()> {    if master.rrule.is_none() {        return Ok(());    }    if parse_ms(new_starts_at) == parse_ms(&master.starts_at) {        return Ok(());    }    let exceptions = event_rows(        ctx,        &event_query().eq("series_id", master.id.clone()),    )?;    if master.exdates.as_deref().unwrap_or(&[]).is_empty() && exceptions.is_empty() {        return Ok(());    }    let zone = event_writer_zone(ctx, timezone)?;    let plan = plan_series_move(master, &exceptions, new_starts_at, &zone)        .map_err(|error| ToolFailure::new(error.to_string()))?;    if !plan.master_patch.is_empty() {        update_row(ctx, "cotton_events", &master.id, plan.master_patch)?;    }    for entry in plan.exception_patches {        update_row(ctx, "cotton_events", &entry.id, entry.patch)?;    }    ctx.commit()?;    Ok(())}fn field_change(value: &Clearable<String>) -> FieldChange<String> {    match value {        Clearable::Unchanged => FieldChange::Unchanged,        Clearable::Cleared => FieldChange::Cleared,        Clearable::Set(value) => FieldChange::Set(value.clone()),    }}/// Whether a start given to a whole-day event names a time of day: neither a/// bare day nor its day's own midnight in the writer's zone (the instant a/// whole day is stored at). One that does makes the event timed.pub fn names_a_time_of_day(ctx: &Ctx<'_>, start: &str, timezone: Option<&str>) -> Valid<bool> {    if start.len() == 10 {        return Ok(false);    }    let zone = event_writer_zone(ctx, timezone)?;    let at = parse_ms(start).ok_or_else(|| ToolFailure::new("startsAt must be an ISO 8601 timestamp"))?;    Ok(start_of_day_in(&today_in(&zone, at)?, &zone)? != at)}/// An ordinary edit to a whole event — `update_event` with no occurrence named,/// `scope: "all"`, and every row of `update_events`'s patch form.////// ONE implementation, because the batch form is exactly where a second one/// would quietly accept something the single form refuses.fn apply_event_patch(    ctx: &mut Ctx<'_>,    existing: &EventRowForPlan,    patch: &EventPatch,    timezone: Option<&str>,) -> Valid<Map<String, Value>> {    let mut starts_at = patch        .starts_at        .clone()        .unwrap_or_else(|| existing.starts_at.clone());    let mut ends_at = match &patch.ends_at {        Clearable::Unchanged => existing.ends_at.clone(),        Clearable::Cleared => None,        Clearable::Set(value) => Some(value.clone()),    };    // A whole day given a time of day becomes timed (When → 9 am on its card),    // where its window would otherwise swallow the hour; its own midnight in    // the writer's zone, or a bare day, leaves it whole.    let all_day = match (patch.all_day, &patch.starts_at) {        (Some(said), _) => said,        (None, Some(start)) if existing.all_day && !patch.starts_bare => !names_a_time_of_day(ctx, start, timezone)?,        (None, _) => existing.all_day,    };    let moved_or_flipped =        patch.all_day.is_some() || patch.starts_at.is_some() || !patch.ends_at.is_unchanged();    if all_day && moved_or_flipped {        let zone = event_writer_zone(ctx, timezone)?;        let window = all_day_window(&zone, &starts_at, ends_at.as_deref())?;        starts_at = window.0;        ends_at = Some(window.1);    }    // A whole day given a time keeps no end of its day's window: it is a    // timed event with no end, as create makes one, until an end is given.    let timed_now = existing.all_day && !all_day;    if timed_now && patch.ends_at.is_unchanged() {        ends_at = None;    }    // The window has to make sense AFTER the patch, so the check runs against    // the merged values, not the arguments alone.    if let (Some(ends), Some(starts)) =        (ends_at.as_deref().and_then(parse_ms), parse_ms(&starts_at))    {        if ends < starts {            return Err(ToolFailure::new("endsAt must not be before startsAt"));        }    }    let mut row_patch = Map::new();    row_patch.insert("updated_at".to_string(), Value::from(now_iso(ctx)));    if let Some(title) = &patch.title {        row_patch.insert("title".to_string(), Value::from(title.clone()));    }    if patch.starts_at.is_some() || (all_day && moved_or_flipped) {        row_patch.insert("starts_at".to_string(), Value::from(starts_at.clone()));    }    if !patch.ends_at.is_unchanged() || (all_day && moved_or_flipped) || timed_now {        row_patch.insert(            "ends_at".to_string(),            ends_at.clone().map_or(Value::Null, Value::from),        );    }    if patch.all_day.is_some() || timed_now {        row_patch.insert("all_day".to_string(), Value::Bool(all_day));    }    if let Some(value) = patch.location.patch_value() {        row_patch.insert("location".to_string(), value);    }    if let Some(value) = patch.notes.patch_value() {        row_patch.insert("notes".to_string(), value);    }    if let Some(value) = patch.rrule.patch_value() {        row_patch.insert("rrule".to_string(), value);    }    // The phone's rule, from the one place both writers read it: a local edit    // to a Google-linked event is marked pending so the sync pushes it back.    for (key, value) in        cotton_core::rules::event_edits::pending_mark_patch(existing.sync_identity())    {        row_patch.insert(key, value);    }    update_row(ctx, "cotton_events", &existing.id, row_patch)?;    ctx.commit()?;    let row = maybe_row(        ctx,        &Query::on("cotton_events")            .columns(&[                "id",                "title",                "starts_at",                "ends_at",                "all_day",                "location",                "notes",                "rrule",            ])            .eq("id", existing.id.clone()),    )?    .ok_or_else(|| ToolFailure::new(format!("no event with id {}", existing.id)))?;    rekey_series(ctx, existing, &starts_at, timezone)?;    Ok(row)}/// "This event" on a repeating event: the occurrence becomes a row of its own/// that claims `occurrenceAt` out of the master's expansion. The DECISION is/// core's (`plan_occurrence_edit`); this only carries it out.fn update_one_occurrence(    ctx: &mut Ctx<'_>,    master: &EventRowForPlan,    patch: &EventPatch,    timezone: Option<&str>,    occurrence_at: &str,) -> Valid<Map<String, Value>> {    let existing = exception_claiming(ctx, &master.id, occurrence_at)?;    let mut starts_at = patch.starts_at.clone();    let mut ends_at = patch.ends_at.clone();    if patch.all_day == Some(true) {        let base = starts_at            .clone()            .or_else(|| existing.as_ref().map(|row| row.starts_at.clone()))            .unwrap_or_else(|| occurrence_at.to_string());        let base_end = match &ends_at {            Clearable::Unchanged => existing.as_ref().and_then(|row| row.ends_at.clone()),            Clearable::Cleared => None,            Clearable::Set(value) => Some(value.clone()),        };        let zone = event_writer_zone(ctx, timezone)?;        let window = all_day_window(&zone, &base, base_end.as_deref())?;        starts_at = Some(window.0);        ends_at = Clearable::Set(window.1);    }    if let (Some(starts), Clearable::Set(ends)) = (&starts_at, &ends_at) {        if let (Some(starts), Some(ends)) = (parse_ms(starts), parse_ms(ends)) {            if ends < starts {                return Err(ToolFailure::new("endsAt must not be before startsAt"));            }        }    }    let new_id = ctx.new_uuid();    let now = now_iso(ctx);    let occurrence_patch = OccurrencePatch {        title: patch.title.clone(),        starts_at: starts_at.clone(),        ends_at: field_change(&ends_at),        all_day: patch.all_day,        location: field_change(&patch.location),        notes: field_change(&patch.notes),    };    let plan = plan_occurrence_edit(OccurrenceEdit {        master,        existing: existing.as_ref(),        occurrence_at,        patch: &occurrence_patch,        new_id: &new_id,        now: &now,    })    .map_err(|error| ToolFailure::new(error.to_string()))?;    if plan.created {        ctx.writer()?            .upsert("cotton_events", &plan.exception_id, plan.patch);    } else {        update_row(ctx, "cotton_events", &plan.exception_id, plan.patch)?;    }    if !plan.master_patch.is_empty() {        update_row(ctx, "cotton_events", &master.id, plan.master_patch)?;    }    ctx.commit()?;    let written = maybe_row(        ctx,        &Query::on("cotton_events")            .columns(&[                "id",                "title",                "starts_at",                "ends_at",                "all_day",                "location",                "notes",            ])            .eq("id", plan.exception_id.clone()),    )?    .ok_or_else(|| ToolFailure::new(format!("no event with id {}", plan.exception_id)))?;    let mut out = written;    out.insert("seriesId".to_string(), Value::from(master.id.clone()));    out.insert("occurrenceAt".to_string(), Value::from(occurrence_at));    out.insert("scope".to_string(), Value::from("this"));    out.insert("created".to_string(), Value::Bool(plan.created));    out.insert(        "note".to_string(),        Value::from("one occurrence of a repeating event — the rest of the series is unchanged"),    );    Ok(out)}pub fn update_event(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    update_event_held(ctx, args, true)}/// The same change made from Days on the phone, which sends a Google event's/// change to Google itself (the edit marks the row pending and Days' send/// pass carries it, assets/design/days/CONTRACT.md section 16): Google's time/// and title are not refused here. The person's assistant over MCP still goes/// through [`update_event`], which refuses them.pub fn update_event_from_days(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    update_event_held(ctx, args, false)}fn update_event_held(ctx: &mut Ctx<'_>, args: &Map<String, Value>, google_guard: bool) -> ToolResult {    let on_google = on_google_arg(args)?;    // On Google alone is a whole change: the switch, and nothing else moves.    if let Some(on) = on_google {        let rest = args.keys().filter(|key| key.as_str() != "id" && key.as_str() != "onGoogle").count();        if rest == 0 {            let id = require_uuid(args, "id")?;            let existing = event_scoped(ctx, &id)?;            set_on_google(ctx, &existing.id, on)?;            ctx.commit()?;            let mut out = Map::new();            out.insert("id".to_string(), Value::from(existing.id));            out.insert("title".to_string(), Value::from(existing.title));            out.insert("onGoogle".to_string(), Value::Bool(on));            return Ok(Value::Object(out));        }    }    let args = validate_update_event(args)?;    let existing = event_scoped(ctx, &args.id)?;    if google_guard && !args.patch.is_empty() {        google_holds(&existing)?;    }    if let Some(on) = on_google {        set_on_google(ctx, &existing.id, on)?;    }    if let Some(occurrence_at) = &args.occurrence_at {        require_repeating(&existing, occurrence_at)?;        if args.scope.as_deref() == Some("this") {            return Ok(Value::Object(update_one_occurrence(                ctx,                &existing,                &args.patch,                args.timezone.as_deref(),                occurrence_at,            )?));        }    }    Ok(Value::Object(apply_event_patch(        ctx,        &existing,        &args.patch,        args.timezone.as_deref(),    )?))}/// Google's time and title are Google's: nothing writes to Google today/// (the Worker only pulls, read-only), so an edit here would be undone by the/// next pull and saying it was made would be a quiet lie (Days, 20 Nov 2026)./// Refused with the sentence a phone shows as it is. The person's own mark,/// note (`your_note`), group and alert are not Google's and are written as on/// any event.pub const GOOGLE_READ_ONLY: &str = "This event is from Google Calendar. Change its time and title in Google.";pub fn google_holds(existing: &EventRowForPlan) -> Valid<()> {    if existing.gcal_id.is_some() {        return Err(ToolFailure::new(GOOGLE_READ_ONLY));    }    Ok(())}/// [`google_holds`] for the event `id` names, or its series' master.pub fn google_holds_id(ctx: &Ctx<'_>, id: &str) -> Valid<()> {    let existing = event_scoped(ctx, id)?;    google_holds(&existing)?;    if let Some(master) = existing.series_id.as_deref() {        if let Ok(master) = event_scoped(ctx, master) {            google_holds(&master)?;        }    }    Ok(())}/// `onGoogle`: the owner's switch that puts a Cotton event on Google (owner,/// 11 Oct 2026 — Cotton is the calendar, Google the wire to other people). A/// solo event stays in Cotton unless it is on; one with guests goes anyway.fn on_google_arg(args: &Map<String, Value>) -> Result<Option<bool>, ToolFailure> {    match args.get("onGoogle") {        None | Some(Value::Null) => Ok(None),        Some(Value::Bool(on)) => Ok(Some(*on)),        Some(_) => Err(ToolFailure::new("onGoogle is true or false")),    }}/// Writes the switch on the event (a series' master carries it for every/// occurrence). The serving Mac's next pass puts a Cotton event on Google;/// one Google already holds keeps syncing whatever the switch says.fn set_on_google(ctx: &mut Ctx<'_>, id: &str, on: bool) -> Result<(), ToolFailure> {    let mut patch = Map::new();    patch.insert("on_google".to_string(), Value::Bool(on));    update_row(ctx, "cotton_events", id, patch)}/// "This event" on a DELETE — core decides, this carries it out.fn cancel_one_occurrence(    ctx: &mut Ctx<'_>,    master: &EventRowForPlan,    occurrence_at: &str,) -> Valid<Map<String, Value>> {    let exception = exception_claiming(ctx, &master.id, occurrence_at)?;    let now = now_iso(ctx);    let plan = plan_occurrence_cancel(master, exception.as_ref(), occurrence_at, &now)        .map_err(|error| ToolFailure::new(error.to_string()))?;    if !plan.master_patch.is_empty() {        update_row(ctx, "cotton_events", &master.id, plan.master_patch)?;    }    if let (Some(trash_id), Some(exception)) = (&plan.trash_exception_id, &exception) {        let mut patch = Map::new();        patch.insert("trashed_at".to_string(), Value::from(now.clone()));        patch.insert("updated_at".to_string(), Value::from(now.clone()));        for (key, value) in            cotton_core::rules::event_edits::pending_mark_patch(exception.sync_identity())        {            patch.insert(key, value);        }        update_row(ctx, "cotton_events", trash_id, patch)?;    }    if let Some(remove_id) = &plan.remove_exception_id {        ctx.writer()?.retract("cotton_events", remove_id, Retract::Relation);    }    ctx.commit()?;    let mut out = Map::new();    out.insert("cancelled".to_string(), Value::Bool(true));    out.insert("id".to_string(), Value::from(master.id.clone()));    out.insert("title".to_string(), Value::from(master.title.clone()));    out.insert("occurrenceAt".to_string(), Value::from(occurrence_at));    out.insert("scope".to_string(), Value::from("this"));    out.insert(        "alreadyCancelled".to_string(),        Value::Bool(plan.already_cancelled),    );    if master.gcal_id.is_some() {        out.insert("synced".to_string(), Value::Bool(true));        out.insert(            "note".to_string(),            Value::from(                "the rest of the series is unchanged; it is removed here only, and Google Calendar still shows it",            ),        );    } else {        out.insert(            "note".to_string(),            Value::from("the rest of the series is unchanged"),        );    }    Ok(out)}/// A whole event out, into the bin — the plan is core's `plan_event_delete`.fn remove_whole_event(ctx: &mut Ctx<'_>, existing: &EventRowForPlan) -> Valid<Map<String, Value>> {    let now = now_iso(ctx);    let plan = plan_event_delete(existing, &now);    for id in &plan.trash {        update_row(ctx, "cotton_events", id, plan.trash_patch.clone())?;    }    ctx.commit()?;    let synced = existing.gcal_id.is_some();    let mut out = Map::new();    out.insert("deleted".to_string(), Value::Bool(true));    out.insert("id".to_string(), Value::from(existing.id.clone()));    out.insert("title".to_string(), Value::from(existing.title.clone()));    out.insert("trashed".to_string(), Value::Bool(true));    if synced {        out.insert("synced".to_string(), Value::Bool(true));    }    let mut note = String::from("in the bin, hidden from every read here; restore_from_bin brings it back");    if synced {        note.push_str("; it is removed here only, and Google Calendar still has it");    }    if existing.rrule.is_some() {        note.push_str("; the whole series, moved occurrences included");    }    out.insert("note".to_string(), Value::from(note));    Ok(out)}pub fn delete_event(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_delete_event(args)?;    let existing = event_scoped(ctx, &args.id)?;    if let Some(occurrence_at) = &args.occurrence_at {        require_repeating(&existing, occurrence_at)?;        if args.scope.as_deref() == Some("this") {            return Ok(Value::Object(cancel_one_occurrence(                ctx,                &existing,                occurrence_at,            )?));        }    }    Ok(Value::Object(remove_whole_event(ctx, &existing)?))}/// A trashed event back out of the bin — the Undo of deleting one; the plan/// is core's `plan_event_untrash`.pub fn untrash_event(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> {    let existing = event_scoped(ctx, id)?;    if existing.trashed_at.is_none() {        return Ok(());    }    let now = now_iso(ctx);    let mut patch = plan_event_untrash(&existing, &now);    // Back out of the bin is back from an erase asked of it too.    patch.insert("erase_requested_at".to_string(), Value::Null);    update_row(ctx, "cotton_events", id, patch)?;    ctx.commit()}/// An erase from the bin of a moved occurrence deleted on its own leaves its/// instant cancelled on the series: the binned row was what claimed it, so/// with the row gone the series would draw that day again. The cancel is/// core's (`plan_occurrence_cancel`), the one a "this event" delete writes./// Nothing to do for any other event, or one whose series is gone.pub(crate) fn keep_occurrence_cancelled(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> {    let one = |ctx: &Ctx<'_>, id: &str| -> Valid<Option<EventRowForPlan>> {        let query = event_query().eq("id", id.to_string());        Ok(event_rows(ctx, &query)?.into_iter().next())    };    let Some(occurrence) = one(ctx, id)? else {        return Ok(());    };    let (Some(series_id), Some(claims)) = (&occurrence.series_id, &occurrence.original_starts_at) else {        return Ok(());    };    let Some(series) = one(ctx, series_id)? else {        return Ok(());    };    let plan = plan_occurrence_cancel(&series, None, claims, &now_iso(ctx))        .map_err(|error| ToolFailure::new(error.to_string()))?;    if !plan.master_patch.is_empty() {        update_row(ctx, "cotton_events", &series.id, plan.master_patch)?;    }    Ok(())}// ── the batch verbs ─────────────────────────────────────────────────────────/// Per-id outcomes, never a failed batch.////// An assistant asking for fifty events has a list it assembled from a read,/// and one id that has since gone is not a reason to leave the other/// forty-nine unchanged — nor to leave the caller guessing which landed.struct BulkOutcome {    ok: i64,    failed: i64,    results: Vec<Value>,}fn per_id(    ctx: &mut Ctx<'_>,    ids: &[String],    mut act: impl FnMut(&mut Ctx<'_>, &str) -> Valid<()>,) -> BulkOutcome {    let mut results = Vec::new();    let mut ok = 0;    let mut failed = 0;    for id in ids {        let mut entry = Map::new();        entry.insert("id".to_string(), Value::from(id.clone()));        match act(ctx, id) {            Ok(()) => {                entry.insert("ok".to_string(), Value::Bool(true));                ok += 1;            }            Err(failure) => {                entry.insert("ok".to_string(), Value::Bool(false));                entry.insert("error".to_string(), Value::from(failure.message()));                failed += 1;            }        }        results.push(Value::Object(entry));    }    BulkOutcome {        ok,        failed,        results,    }}pub fn update_events(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_update_events(args)?;    // Resolved ONCE, before anything is written: a zone that cannot be resolved    // must refuse the whole call rather than fail fifty times in a row and read    // as fifty separate problems.    let needs_zone = args.move_to.is_some()        || args            .patch            .as_ref()            .is_some_and(|patch| patch.all_day == Some(true));    let zone = if needs_zone {        Some(event_writer_zone(            ctx,            args.move_to                .as_ref()                .and_then(|move_to| move_to.timezone.as_deref())                .or(args.timezone.as_deref()),        )?)    } else {        None    };    let target_day_start = match (&args.move_to, &zone) {        (Some(move_to), Some(zone)) => Some(start_of_day_in(&move_to.date, zone)?),        _ => None,    };    let write_zone = zone.clone().or_else(|| args.timezone.clone());    let outcome = per_id(ctx, &args.ids, |ctx, id| {        let existing = event_scoped(ctx, id)?;        google_holds(&existing)?;        if let Some(patch) = &args.patch {            apply_event_patch(ctx, &existing, patch, write_zone.as_deref())?;            return Ok(());        }        let from = parse_ms(&existing.starts_at)            .ok_or_else(|| ToolFailure::new(format!("no event with id {id}")))?;        let delta = match args.shift_minutes {            Some(minutes) => minutes * 60_000,            None => {                // moveTo: the event keeps the time it happens AT and lands on                // another day. Measured from the start of its own day in the                // same zone, so a 09:30 meeting is 09:30 on the new date                // whatever either day's offset is.                let zone = zone.as_deref().unwrap_or("UTC");                let own_day_start = start_of_day_in(&today_in(zone, from)?, zone)?;                target_day_start.unwrap_or(from) + (from - own_day_start) - from            }        };        if delta == 0 {            return Ok(());        }        let starts_at = iso_of_ms(from + delta);        let mut patch = Map::new();        patch.insert("starts_at".to_string(), Value::from(starts_at.clone()));        patch.insert("updated_at".to_string(), Value::from(now_iso(ctx)));        for (key, value) in            cotton_core::rules::event_edits::pending_mark_patch(existing.sync_identity())        {            patch.insert(key, value);        }        if let Some(ends_at) = existing.ends_at.as_deref().and_then(parse_ms) {            patch.insert(                "ends_at".to_string(),                Value::from(iso_of_ms(ends_at + delta)),            );        }        update_row(ctx, "cotton_events", id, patch)?;        ctx.commit()?;        rekey_series(            ctx,            &existing,            &starts_at,            write_zone.as_deref(),        )    });    let mut out = Map::new();    out.insert("updated".to_string(), Value::from(outcome.ok));    out.insert("failed".to_string(), Value::from(outcome.failed));    out.insert("results".to_string(), Value::Array(outcome.results));    Ok(Value::Object(out))}pub fn delete_events(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let ids = validate_delete_events(args)?;    let outcome = per_id(ctx, &ids, |ctx, id| {        let existing = event_scoped(ctx, id)?;        remove_whole_event(ctx, &existing)?;        Ok(())    });    let mut out = Map::new();    out.insert("deleted".to_string(), Value::from(outcome.ok));    out.insert("failed".to_string(), Value::from(outcome.failed));    out.insert("results".to_string(), Value::Array(outcome.results));    Ok(Value::Object(out))}// ── the owner's own verb (4e) ───────────────────────────────────────────────/// `respond_to_invite` — accept, decline or hold an invitation.////// `packages/core/src/services/events.service.ts::respondToInvite`. It sets the/// LOCAL `my_response`; a Google-linked event is additionally marked/// `sync_state = 'pending'` so the sync PATCHes the response back to Google on/// its next tick (its push loop reads pending rows and nothing else). The mark/// rides in the SAME write as the response, which is what makes "an event can/// never be answered without being marked" a property rather than a habit.////// WHY IT IS THE OWNER'S AND NOT AN ASSISTANT'S. `update_event` carries no/// `response` field and no attendee surface at all, and that is not an/// oversight: saying yes to somebody's invitation is a commitment made in a/// person's own name. So this is [`crate::mcp::protocol::McpScope::Owner`] —/// the app's invite card reaches it and no token can — and an assistant's/// vocabulary is unchanged.pub fn respond_to_invite(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_uuid(args, "id")?;    let Some(response) = optional_enum(        args,        "response",        &["accepted", "declined", "tentative", "needs_action"],    )?    else {        return Err(ToolFailure::new(            "response is one of accepted, declined, tentative or needs_action",        ));    };    let existing = event_scoped(ctx, &id)?;    let mut patch = Map::new();    patch.insert("my_response".to_string(), Value::from(response.clone()));    for (column, value) in        cotton_core::rules::event_edits::pending_mark_patch(existing.sync_identity())    {        patch.insert(column, value);    }    update_row(ctx, "cotton_events", &id, patch)?;    ctx.commit()?;    let mut out = Map::new();    out.insert("id".to_string(), Value::from(id));    out.insert("title".to_string(), Value::from(existing.title.clone()));    out.insert("response".to_string(), Value::from(response));    if existing.gcal_id.is_some() {        out.insert("synced".to_string(), Value::Bool(true));        out.insert(            "note".to_string(),            Value::from("your answer is kept here only; Google Calendar still shows your earlier reply until you answer there"),        );    }    Ok(Value::Object(out))}/// One guest as the caller names them. `phone` is deliberately absent — see/// [`update_attendees`].struct AttendeeInput {    email: Option<String>,    display_name: Option<String>,    person_id: Option<String>,}/// The guest list, as the schema admits it.////// Every field is optional INDIVIDUALLY and an all-empty entry is refused: a/// chip with no email, no name and no person is a row nothing can draw and a/// link nothing can follow, and it would come back from the read as a blank.fn attendee_inputs(args: &Map<String, Value>) -> Valid<Vec<AttendeeInput>> {    let Some(raw) = args.get("attendees") else {        return Err(ToolFailure::new(            "attendees is the whole guest list — pass [] to remove everyone",        ));    };    let Some(list) = raw.as_array() else {        return Err(ToolFailure::new(            "attendees is a list of guests — pass [] to remove everyone",        ));    };    let mut out = Vec::with_capacity(list.len());    for entry in list {        let Some(object) = entry.as_object() else {            return Err(ToolFailure::new(                "each guest is an object with email, displayName or personId",            ));        };        let field = |key: &str| -> Valid<Option<String>> {            match object.get(key) {                None | Some(Value::Null) => Ok(None),                Some(Value::String(value)) => {                    let trimmed = value.trim();                    Ok((!trimmed.is_empty()).then(|| trimmed.to_string()))                }                Some(_) => Err(ToolFailure::new(format!("{key} is text"))),            }        };        let guest = AttendeeInput {            email: field("email")?,            display_name: field("displayName")?,            person_id: field("personId")?,        };        if guest.email.is_none() && guest.display_name.is_none() && guest.person_id.is_none() {            return Err(ToolFailure::new(                "a guest needs at least one of email, displayName or personId",            ));        }        out.push(guest);    }    Ok(out)}/// `update_attendees` — replace an event's whole guest list.////// `packages/core/src/services/events.service.ts::updateAttendees`, ported/// clause for clause: the existing `cotton_event_attendees` rows and the/// existing `event → person` edges are DELETED, then the fresh set is written/// by the same shape `attendeeChanges` builds — `response: 'needs_action'` on/// every row, and one link per DISTINCT `personId`. Reconcile is delete +/// reinsert rather than a diff because a response on a local event is/// informational only: the list rewritten is a list nobody has answered yet.////// GOOGLE-SYNCED EVENTS ARE REFUSED. The phone's editor renders the guest list/// read-only when `editing?.gcalId != nil` and skips this write entirely/// (`syncedWithGoogle` in/// `apps/cotton/Sources/CottonUI/Screens/Day/Calendar/CalendarModel.swift`,/// read by `.../EventEditScreen.swift`); the column that records it is/// `cotton_events.gcal_id`, so the guard is expressible here and is written/// here rather than left to the screen — Google owns that event's invite/// fan-out, and a local rewrite would be silently undone by the next pull.////// TWO DELIBERATE NARROWINGS OF THE INPUT, both because no editor sends them./// `phone` is a column on the row and no surface writes it, so the tool's/// schema has no `phone` and this writes `null`. And the workspace is not an/// argument: it is the writer's own knowledge and it stamps the column, so the/// links are skipped only for the empty-workspace case.////// WHY IT IS THE OWNER'S AND NOT AN ASSISTANT'S. Same sentence as/// `respond_to_invite`: `update_event` carries no attendee field on purpose,/// because inviting somebody is a commitment made in a person's own name. So it/// lands on [`crate::mcp::protocol::McpScope::Owner`] and an assistant's/// vocabulary is unchanged.pub fn update_attendees(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let event_id = require_uuid(args, "eventId")?;    let guests = attendee_inputs(args)?;    let existing = event_scoped(ctx, &event_id)?;    if existing.gcal_id.is_some() {        return Err(ToolFailure::new(format!(            "the guests of {} belong to Google Calendar — answer an invitation with \             respond_to_invite, or change the guest list in Google",            quoted(&existing.title)        )));    }    // Read BOTH old sets before anything is written: the deletes and the    // inserts ride in one batch, applied in order, so the reinsert of a guest    // who is still on the list cannot collide with the row it replaces.    let old_attendees = rows(        ctx,        &Query::on(ATTENDEES)            .columns(&["id"])            .eq("event_id", event_id.clone()),    )?;    let old_links = rows(        ctx,        &Query::on("cotton_links")            .columns(&["id"])            .eq("from_kind", "event".to_string())            .eq("from_id", event_id.clone())            .eq("to_kind", "person".to_string()),    )?;    for row in &old_attendees {        if let Some(id) = text(row, "id") {            ctx.writer()?.retract(ATTENDEES, &id, Retract::Relation);        }    }    for row in &old_links {        if let Some(id) = text(row, "id") {            ctx.writer()?.retract("cotton_links", &id, Retract::Relation);        }    }    let mut fresh_ids: Vec<String> = Vec::with_capacity(guests.len());    for guest in &guests {        let id = ctx.new_uuid();        let mut patch = Map::new();        patch.insert("event_id".to_string(), Value::from(event_id.clone()));        patch.insert(            "email".to_string(),            guest.email.clone().map_or(Value::Null, Value::from),        );        // The column exists and no surface writes it — see the doc comment.        patch.insert("phone".to_string(), Value::Null);        patch.insert(            "display_name".to_string(),            guest.display_name.clone().map_or(Value::Null, Value::from),        );        patch.insert("response".to_string(), Value::from("needs_action"));        insert_row(ctx, ATTENDEES, &id, patch)?;        fresh_ids.push(id);    }    // De-duplicated, in first-named order: two chips for one person are two    // guests and ONE edge, and a `BTreeSet` would reorder the links against the    // list the caller sent.    let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();    let mut person_ids: Vec<String> = Vec::new();    for guest in &guests {        if let Some(person_id) = &guest.person_id {            if seen.insert(person_id.clone()) {                person_ids.push(person_id.clone());            }        }    }    // An edge names a person in THIS database: a guest whose person this    // database does not hold (one from another database) keeps their guest    // row and gets no edge, and the answer says how many were left out.    let held: std::collections::BTreeSet<String> = if person_ids.is_empty() {        std::collections::BTreeSet::new()    } else {        rows(            ctx,            &Query::on("cotton_people")                .columns(&["id"])                .filter(Filter::In(                    "id".to_string(),                    person_ids.iter().cloned().map(SqlValue::Text).collect(),                )),        )?        .iter()        .filter_map(|row| text(row, "id"))        .collect()    };    let before = person_ids.len();    person_ids.retain(|id| held.contains(id));    let dropped_person_links = before - person_ids.len();    if !ctx.workspace_id.is_empty() {        for person_id in &person_ids {            // DERIVED, not random: every writer of `cotton_links` derives the            // edge's id from its ends (`uq_cotton_links_ends`), so the same            // pair is the same row however often it is rewritten.            let link_id = link_id_for(                &LinkRow {                    from_kind: "event",                    from_id: &event_id,                    to_kind: "person",                    to_id: person_id,                    to_database: None,                },                ctx.file.id(),            );            let mut patch = Map::new();            patch.insert("from_kind".to_string(), Value::from("event"));            patch.insert("from_id".to_string(), Value::from(event_id.clone()));            patch.insert("to_kind".to_string(), Value::from("person"));            patch.insert("to_id".to_string(), Value::from(person_id.clone()));            insert_row(ctx, "cotton_links", &link_id, patch)?;        }    }    ctx.commit()?;    // Read back what was written, in the order it was written — the TS answers    // `ids.map(selectById).map(toIEventAttendee)`, and a row that failed to    // land is left out rather than invented. CAMEL CASE, like `toIEventAttendee`    // and like `read.event`'s own attendee rows: the same guest read two ways    // would be two shapes for one thing.    let mut attendees: Vec<Value> = Vec::with_capacity(fresh_ids.len());    for id in &fresh_ids {        let row = maybe_row(            ctx,            &Query::on(ATTENDEES)                .columns(&["id", "event_id", "email", "phone", "display_name", "response"])                .eq("id", id.clone()),        )?;        let Some(row) = row else { continue };        let mut out = Map::new();        out.insert("id".to_string(), or_null(text(&row, "id")));        out.insert("eventId".to_string(), or_null(text(&row, "event_id")));        out.insert("email".to_string(), or_null(text(&row, "email")));        out.insert("phone".to_string(), or_null(text(&row, "phone")));        out.insert("displayName".to_string(), or_null(text(&row, "display_name")));        out.insert("response".to_string(), or_null(text(&row, "response")));        attendees.push(Value::Object(out));    }    let mut out = Map::new();    out.insert("eventId".to_string(), Value::from(event_id));    out.insert("attendees".to_string(), Value::Array(attendees));    out.insert(        "linkedPeople".to_string(),        Value::Array(person_ids.into_iter().map(Value::from).collect()),    );    if dropped_person_links > 0 {        out.insert("droppedPersonLinks".to_string(), Value::from(dropped_person_links));    }    Ok(Value::Object(out))}