//! The `validateX` half of `packages/server/src/mcp/protocol.ts`, for this//! group's 28 tools.//!//! HAND-PORTED, with the refusal sentences character for character (design S5)://! they are what an assistant reads to correct itself, and a paraphrase makes//! the next turn a guess. The catalogue's `inputSchema` is advice to a client;//! this file is the gate, and it is why a call carrying `howWeMet` or `tags` is//! told which verb replaced it rather than having the argument silently//! dropped.//!//! One shape difference from the TypeScript and nothing else: a three-state//! field (`undefined` / `null` / a value) is [`Clearable`], because//! `Option<Option<T>>` reads as nothing at a call site.use cotton_core::rules::people::handles::HandleKind;use cotton_core::transforms::rrule::parse_rrule;use cotton_core::transforms::moment_split::is_clock_time;use serde_json::{Map, Value};usecrate::mcp::handlers::common::{ bounded_limit, clearable_calendar_date, clearable_string, clearable_timestamp, fail, is_calendar_date, is_true, is_uuid, iso_timestamp, optional_boolean, optional_enum, optional_string, optional_string_list, optional_zone, quoted, require_string, require_uuid,Clearable, Valid,};// ── shared vocabularies ─────────────────────────────────────────────────────/// What a note may carry a picture of — the `record_kind` CHECK on/// `cotton_note_attachments`, spelled here because this file is the gate the/// store's CHECK is never allowed to become (a fragment that trips a CHECK is/// an op parked for ever; a refusal here is a sentence an assistant can act/// on).pubconst ATTACHMENT_KINDS: &[&str] = &["photo", "video", "document"];/// The most pictures one note may name.////// Not a storage limit — the rows are tiny — but a READING one: `get_record`/// expands every attachment into a paragraph of facts, and a note naming two/// hundred would answer with more picture than note.////// Fifty was that reading limit until version 33 of the store's ladder converted/// every walkthrough into a note: a published walkthrough carried a screen per/// screen of the app and the longest of them ran to hundreds, so a cap of fifty/// would have made a converted note unsavable from the app the moment anyone/// edited it — the picture of how the app used to look, lost to a number. The/// reading concern is real and is answered where reading happens (`get_record`/// pages its attachments); the WRITE cap is the ceiling of a real note.pubconst MAX_ATTACHMENTS: usize = 500;const TODO_LIST_STATUSES: &[&str] = &["open", "done", "dropped", "missed", "all"];const TODO_SET_STATUSES: &[&str] = &["open", "done", "dropped"];const TODO_PRIORITIES: &[&str] = &["high", "none"];const GOAL_STATUSES: &[&str] = &["active", "paused", "achieved", "dropped"];const CONTACT_SOURCES: &[&str] = &["import", "manual", "apple_library"];const EVENT_SCOPES: &[&str] = &["this", "all"];const TODO_BATCH_MAX: usize = 100;const EVENT_BATCH_MAX: usize = 50;const LIST_EVENTS_WINDOW_DAYS: i64 = 14;const HOW_WE_MET_RETIRED_REFUSAL: &str = "howWeMet was retired — it is the person's summary now, \ which carries who wrote it and when. Write it with update_summary { kind: \"person\", id, \ summary }.";const TAGS_RETIRED_REFUSAL: &str = "tags were retired — a note belongs to a project now. File it \ with link_to_project { project, records: [{ kind: \"note\", id }] } after this call returns \ the note's id.";const DAYS_IN_MONTH: [i64; 12] = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];// ── todos ───────────────────────────────────────────────────────────────────/// The due half of a todo change. `None` is "leave it alone", `Some(None)` is/// "clear it", `Some(Some(x))` is "set it".#[derive(Debug, Clone, Default)]pubstructTodoDueChange {pub due_at: Option<Option<String>>,pub due_date: Option<Option<String>>,pub due_time: Option<Option<String>>,pub timezone: Option<String>,}implTodoDueChange {/// True when the change touches the due at all, in either spelling.pubfn changes_due(&self) -> bool {self.due_at.is_some() || self.due_date.is_some() || self.due_time.is_some() }fn is_empty(&self) -> bool { !self.changes_due() }}fn clearable_to_option(value: Clearable<String>) -> Option<Option<String>> {match value {Clearable::Unchanged => None,Clearable::Cleared => Some(None),Clearable::Set(value) => Some(Some(value)), }}/// `dueAt` and the day/time pair are two spellings of the same fact, so a call/// carrying both is refused rather than having one silently win.fn todo_due_change(args: &Map<String, Value>) -> Valid<TodoDueChange> {let due_at = clearable_to_option(clearable_timestamp(args, "dueAt")?);let due_date = clearable_to_option(clearable_calendar_date(args, "dueDate")?);let due_time = match args.get("dueTime") {None => None,Some(Value::Null) => Some(None),Some(Value::String(raw)) => {let trimmed = raw.trim();if !is_clock_time(trimmed) {return fail("dueTime must be HH:mm (24-hour), or null to drop the time"); }Some(Some(trimmed.to_string())) }Some(_) => None, };let timezone = optional_zone(args)?;let pair_given = due_date.is_some() || due_time.is_some();if due_at.is_some() && pair_given {return fail("pass dueAt OR dueDate/dueTime, not both — they name the same moment"); }Ok(TodoDueChange { due_at, due_date, due_time, timezone, })}/// What a todo call that still names `label` is told. Todos lost labels on/// 5 Oct 2026: groups do that job now (`crate::todo_labels`).pubconst TODO_LABEL_GONE: &str = "Todos have no label any more; groups do that job. \ Put the todo in a group instead: create_group { table: \"todo\", name, records } or \ update_group { id, add }.";/// A todo call naming `label` at all is refused in plain words, never quietly/// dropped: a caller who meant to sort the todo would otherwise think it had.fn refuse_todo_label(args: &Map<String, Value>) -> Valid<()> {if args.contains_key("label") {return fail(TODO_LABEL_GONE); }Ok(())}#[derive(Debug, Clone)]pubstructCreateTodoArgs {pub title: String,pub notes: Option<String>,pub due: TodoDueChange,pub rrule: Option<String>,}pubfn validate_create_todo(args: &Map<String, Value>) -> Valid<CreateTodoArgs> {letSome(title) = require_string(args, "title") else {return fail("title is required"); };let notes = optional_string(args, "notes"); refuse_todo_label(args)?;// Shallow shape check only — the data layer runs the real RRULE parser.let rrule = optional_string(args, "rrule");let due = todo_due_change(args)?;// A creation has nothing to clear: a null here is a call that meant nothing.if due.due_at == Some(None) || due.due_date == Some(None) {return fail("omit the due to create an undated todo — null clears nothing here"); }if due.due_time == Some(None) {return fail("omit dueTime for a date-only todo — null drops nothing here"); }if due.due_time.is_some() && due.due_date.is_none() {return fail("dueTime needs dueDate — a time is a time on a day"); }let has_due = due.due_at.is_some() || due.due_date.is_some();if rrule.is_some() && !has_due {return fail("a repeating todo needs a due — it anchors the series' first occurrence"); }Ok(CreateTodoArgs { title, notes, due, rrule, })}pubfn validate_complete_todo(args: &Map<String, Value>) -> Valid<String> {match require_string(args, "id") {Some(id) if is_uuid(&id) => Ok(id), _ => fail("id must be a uuid"), }}#[derive(Debug, Clone)]pubstructListTodosArgs {pub status: String,pub include_undated: bool,pub limit: i64,pub due_after: Option<String>,pub due_before: Option<String>,/// A project's slug, or `"none"` — the spelling every other list verb takes/// for "filed under no project" ([`crate::mcp::handlers::common::NO_PROJECT_FILTER`]).pub project: Option<String>,/// `unfiled: true` — the same question as `project: "none"`, spelled the way/// somebody asks it. Both are accepted; asking for a project AND unfiled is/// a contradiction and is refused rather than silently answering one of them.pub unfiled: bool,/// The opaque handle the previous page answered with, decoded.pub cursor: Option<TodoCursor>,}/// Where a page stopped: the sort key of the last todo that travelled.////// `list_todos` walks TWO orders in one list — the dated todos by what is owed/// next, then the undated by when they were filed — so a cursor has to say/// which of the two it is in. A caller never reads this: it travels as the/// base64url of its JSON, so the day the ordering changes an old handle is/// refused rather than quietly returning the wrong page.#[derive(Debug, Clone, PartialEq, Eq)]pubenumTodoCursor {/// Dated: `due_at` ascending, `id` ascending as the tiebreak.Dated { due_at: String, id: String },/// Undated: `created_at` descending, `id` descending as the tiebreak.Undated { created_at: String, id: String },}implTodoCursor {/// The handle a caller passes back as `cursor`.pubfn encode(&self) -> String {use base64::Engine;let payload = matchself {TodoCursor::Dated { due_at, id } => { serde_json::json!({ "v": 1, "phase": "dated", "key": due_at, "id": id }) }TodoCursor::Undated { created_at, id } => { serde_json::json!({ "v": 1, "phase": "undated", "key": created_at, "id": id }) } }; base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload.to_string()) }fn decode(raw: &str) -> Option<TodoCursor> {use base64::Engine;let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD .decode(raw) .ok()?;let payload: Value = serde_json::from_slice(&bytes).ok()?;if payload.get("v").and_then(Value::as_i64) != Some(1) {returnNone; }let key = payload.get("key")?.as_str()?.to_string();let id = payload.get("id")?.as_str()?.to_string();match payload.get("phase")?.as_str()? {"dated" => Some(TodoCursor::Dated { due_at: key, id }),"undated" => Some(TodoCursor::Undated { created_at: key, id, }), _ => None, } }}pubfn validate_list_todos(args: &Map<String, Value>) -> Valid<ListTodosArgs> {let status = optional_enum(args, "status", TODO_LIST_STATUSES)?;letmut window: [Option<String>; 2] = [None, None];for (index, key) in ["dueAfter", "dueBefore"].iter().enumerate() {letSome(raw) = optional_string(args, key) else {continue; };letSome(parsed) = iso_timestamp(&raw) else {return fail(format!("{key} must be an ISO 8601 timestamp")); }; window[index] = Some(parsed); }let [due_after, due_before] = window;iflet (Some(after), Some(before)) = (&due_after, &due_before) {if after >= before {return fail("dueAfter must be before dueBefore"); } }// A due window is a question about SCHEDULED todos, so it excludes the// undated unless the caller insisted — an undated todo is in no window.let include_undated = match args.get("includeUndated") {Some(Value::Bool(value)) => *value, _ => due_after.is_none() && due_before.is_none(), };let project = optional_string(args, "project");let unfiled = is_true(args, "unfiled");if unfiled {ifletSome(slug) = project .as_deref() .filter(|slug| *slug != crate::mcp::handlers::common::NO_PROJECT_FILTER) {return fail(format!("unfiled asks for the todos in no project and project {} asks for one project's — \ pass one of them, not both", quoted(slug) )); } }let cursor = match optional_string(args, "cursor") {None => None,Some(raw) => matchTodoCursor::decode(&raw) {Some(cursor) => Some(cursor),// A cursor is this tool's own handle, so a bad one is a caller// error and never a silently-restarted list: paging from page one// again would read the same rows for ever without saying so.None => {return fail("cursor is not one list_todos handed out — pass nextCursor from the previous \ page exactly as it came, or drop it to start the list again", ) } }, };Ok(ListTodosArgs { status: status.unwrap_or_else(|| "open".to_string()), include_undated, limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST), due_after, due_before, project, unfiled, cursor, })}/// The patch half of `update_todo` / `update_todos` — one reader, so a field/// the single form accepts is a field the batch form accepts, by construction.#[derive(Debug, Clone, Default)]pubstructTodoPatch {pub notes: Option<Value>,pub due: TodoDueChange,pub priority: Option<String>,pub snoozed_until: Option<Value>,pub status: Option<String>,}implTodoPatch {fn is_empty(&self) -> bool {self.notes.is_none() && self.due.is_empty() && self.priority.is_none() && self.snoozed_until.is_none() && self.status.is_none() }}fn todo_patch(args: &Map<String, Value>) -> Valid<TodoPatch> {let notes = clearable_string(args, "notes").patch_value(); refuse_todo_label(args)?;let due = todo_due_change(args)?;let priority = optional_enum(args, "priority", TODO_PRIORITIES)?;let snoozed_until = clearable_timestamp(args, "snoozedUntil")?.patch_value();let status = optional_enum(args, "status", TODO_SET_STATUSES)?;Ok(TodoPatch { notes, due, priority, snoozed_until, status, })}#[derive(Debug, Clone)]pubstructUpdateTodoArgs {pub id: String,pub title: Option<String>,pub patch: TodoPatch,}pubfn validate_update_todo(args: &Map<String, Value>) -> Valid<UpdateTodoArgs> {let id = require_uuid(args, "id")?;let title = optional_string(args, "title");let patch = todo_patch(args)?;if title.is_none() && patch.is_empty() {return fail("nothing to change — pass a field to change"); }Ok(UpdateTodoArgs { id, title, patch })}#[derive(Debug, Clone)]pubstructUpdateTodosArgs {pub ids: Vec<String>,pub patch: TodoPatch,}pubfn validate_update_todos(args: &Map<String, Value>) -> Valid<UpdateTodosArgs> {letSome(raw) = args.get("ids").and_then(Value::as_array) else {return fail(format!("ids must be an array of 1 to {TODO_BATCH_MAX} todo uuids" )); };if raw.is_empty() || raw.len() > TODO_BATCH_MAX {return fail(format!("ids must be an array of 1 to {TODO_BATCH_MAX} todo uuids" )); }letmut ids: Vec<String> = Vec::new();for item in raw {match item.as_str() {Some(value) if is_uuid(value) => {if !ids.iter().any(|id| id == value) { ids.push(value.to_string()); } } _ => {return fail(format!("ids must be todo uuids — {} is not one", cotton_store::protocol::js::json_stringify(item) )) } } }// A title names ONE todo; the same title on a batch is a mistake worth// refusing out loud rather than a patch quietly applied.if args.contains_key("title") {return fail("update_todos takes no title — a title names one todo; use update_todo"); }let patch = todo_patch(args)?;if patch.is_empty() {return fail("nothing to change — pass a field to change"); }Ok(UpdateTodosArgs { ids, patch })}// ── notes and the journal ───────────────────────────────────────────────────#[derive(Debug, Clone)]pubstructCreateNoteArgs {pub body: String,pub title: Option<String>,pub attachments: Option<Vec<AttachmentArg>>,}pubfn validate_create_note(args: &Map<String, Value>) -> Valid<CreateNoteArgs> {letSome(body) = require_string(args, "body") else {return fail("body is required"); };Ok(CreateNoteArgs { body, title: optional_string(args, "title"), attachments: validate_attachments(args.get("attachments"), "note")?, })}/// The note table's create (`create_record { table: "note" }`), where a/// TITLE alone is a note: the one input on the board and a new note's blank/// page both write the words they have into the definition's title column,/// and the body comes later — or never, for a one-line note. The note/// definition holds no column required, so refusing "body is required" here/// made every note the app's one input sent a "Nothing was saved". An/// assistant's `create_note` still needs its body (above).pubfn validate_create_table_note(args: &Map<String, Value>) -> Valid<CreateNoteArgs> {let title = optional_string(args, "title");let body = optional_string(args, "body");if title.is_none() && body.is_none() {return fail("a note needs a title or a body"); }Ok(CreateNoteArgs { body: body.unwrap_or_default(), title, attachments: validate_attachments(args.get("attachments"), "note")?, })}#[derive(Debug, Clone)]pubstructUpdateNoteArgs {pub id: String,pub title: Option<String>,pub body: Option<String>,/// Pinned on its page (board 11's Pin): `None` leaves it as it is.pub pinned: Option<bool>,/// THE WHOLE LIST OR NOTHING. `None` is "leave the pictures alone";/// `Some(list)` REPLACES what the note carries, and `Some(vec![])` takes/// them all off. A partial list would make "remove one" impossible to say/// without a second verb, and a note's pictures are ordered — an order is/// only ever expressible whole.pub attachments: Option<Vec<AttachmentArg>>,}pubfn validate_update_note(args: &Map<String, Value>) -> Valid<UpdateNoteArgs> {letSome(id) = require_string(args, "id").filter(|id| is_uuid(id)) else {return fail("id must be a uuid"); };let title = optional_string(args, "title");// An empty-string body is a legitimate edit (clearing a note), so it cannot// go through `optionalString`, which reads blank as absent.let body = args.get("body").and_then(Value::as_str).map(str::to_string);let attachments = validate_attachments(args.get("attachments"), "note")?;let pinned = match args.get("pinned") {None | Some(Value::Null) => None,Some(Value::Bool(pinned)) => Some(*pinned),Some(_) => return fail("pinned must be true or false"), };if title.is_none() && body.is_none() && attachments.is_none() && pinned.is_none() {return fail("give a title, a body, attachments, pinned, or any of them"); }Ok(UpdateNoteArgs { id, title, body, pinned, attachments, })}/// One picture a note names — the record's kind and id, plus the note's own/// words for it.#[derive(Debug, Clone, PartialEq, Eq)]pubstructAttachmentArg {pub kind: String,pub id: String,/// The note's OVERRIDE, and the three states a caption has.////// `Unchanged` is the CAPTION KEY LEFT OUT, and it leaves whatever the note/// already said alone — because a phone re-sending the list to reorder it/// sends `{ kind, id }` and nothing else, and reading that as "clear the/// caption" wiped every one the owner had written. `Cleared` is an explicit/// `caption: null` (or a blank string), which is how a caption is taken/// back off. `Set` is the note's own words. On a NEW attachment `Unchanged`/// and `Cleared` are the same thing: no caption of the note's own, so the/// picture's own is what reads.pub caption: Clearable<String>,}/// `attachments` — absent, or the whole ordered list.////// Every refusal here names what is wrong and what would be right, because the/// alternative is a fragment that trips the store's own CHECK and parks an op:/// the id shapes in particular (`photo:` plus a 64-character hash, a uuid for a/// document) are what the caller has in hand from `list_photos` or/// `list_documents` and nowhere else./// `noun` is the owner the refusals name — "note" or "thought" — because the/// same list is filed onto either and a thought told about "the note" would be/// a sentence about a record it is not.pubfn validate_attachments( value: Option<&Value>, noun: &str,) -> Valid<Option<Vec<AttachmentArg>>> {letSome(value) = value else {returnOk(None); };// `null` is an assistant that templated the argument and had no value for// it — never an instruction to clear, which is `[]`.if value.is_null() {return fail(format!("attachments must be an array — pass [] to take every picture off the {noun}" )); }letSome(list) = value.as_array() else {return fail("attachments must be an array of { kind, id, caption? }"); };if list.len() > MAX_ATTACHMENTS {return fail(format!("a {noun} carries at most {MAX_ATTACHMENTS} attachments; that list has {}", list.len() )); }letmut out: Vec<AttachmentArg> = Vec::with_capacity(list.len());for entry in list {letSome(entry) = entry.as_object() else {return fail("each attachment must be an object of { kind, id, caption? }"); };let attachment = validate_attachment_ref(entry, "attachment")?;if out .iter() .any(|held| held.kind == attachment.kind && held.id == attachment.id) {return fail(format!("{} {} is in the list twice — a {noun} names a picture once, and its place in the \ list is its order", attachment.kind, quoted(&attachment.id) )); }let caption = clearable_string(entry, "caption");ifletClearable::Set(caption) = &caption {if caption.chars().count() > 500 {return fail("an attachment caption is at most 500 characters"); } } out.push(AttachmentArg { caption, ..attachment }); }Ok(Some(out))}/// `{ kind, id }` — read by the attachments list and by a comment's image/// anchor, so the two cannot drift on what a picture is called.fn validate_attachment_ref(raw: &Map<String, Value>, what: &str) -> Valid<AttachmentArg> {let kind = raw.get("kind").and_then(Value::as_str);letSome(kind) = kind.filter(|kind| ATTACHMENT_KINDS.contains(kind)) else {return fail(format!("{what}.kind must be one of: {}", ATTACHMENT_KINDS.join(", ") )); };letSome(id) = require_string(raw, "id") else {return fail(format!("{what}.id is required")); };let shaped = match kind {"document" => is_uuid(&id), media => crate::mcp::handlers::media_tools::is_media_id(&id, media), };if !shaped {return fail(match kind {"document" => format!("{what}.id must be a document's uuid, from list_documents"), media => format!("{what}.id must be a {media}'s id — \"{media}:\" followed by its 64-character \ content hash" ), }); }Ok(AttachmentArg { kind: kind.to_string(), id, caption: Clearable::Unchanged, })}/// `validateArchiveNote` — the loose id reading, deliberately not `requireUuid`.pubfn validate_note_id(args: &Map<String, Value>) -> Valid<String> {match require_string(args, "id") {Some(id) if is_uuid(&id) => Ok(id), _ => fail("id must be a uuid"), }}#[derive(Debug, Clone)]pubstructAppendJournalArgs {pub text: String,pub date: Option<String>,pub project: Option<String>,}pubfn validate_append_journal(args: &Map<String, Value>) -> Valid<AppendJournalArgs> {letSome(text) = require_string(args, "text") else {return fail("text is required"); };// The CONTEXT, before the date. A blank slug — and `null`, which an// assistant emits the moment it templates the argument and has no value for// it — is a caller that meant to name a project and lost the value.let project =match args.get("project") {None => None,Some(Value::String(raw)) if !raw.trim().is_empty() => Some(raw.trim().to_string()),Some(_) => return fail("project must be named by its slug, from list_projects — to write the owner's own \ page, omit project entirely", ), };letSome(raw) = optional_string(args, "date") else {returnOk(AppendJournalArgs { text, date: None, project, }); };if !is_calendar_date(&raw) {return fail("date must be YYYY-MM-DD"); }Ok(AppendJournalArgs { text, date: Some(raw), project, })}#[derive(Debug, Clone)]pubstructUpsertManagedNoteArgs {pub external_id: String,pub managed_by: String,pub body: String,pub title: Option<String>,pub source_hash: Option<String>,}pubfn validate_upsert_managed_note(args: &Map<String, Value>) -> Valid<UpsertManagedNoteArgs> {if args.contains_key("tags") {return fail(TAGS_RETIRED_REFUSAL); }ifletSome(key) = args.keys().find(|key| !matches!(key.as_str(), "externalId" | "managedBy" | "body" | "title" | "sourceHash")) {return fail(format!("unknown argument {key}")); }letSome(external_id) = require_string(args, "externalId") else {return fail("externalId is required"); };letSome(managed_by) = require_string(args, "managedBy") else {return fail("managedBy is required"); };letSome(body) = args.get("body").and_then(Value::as_str) else {return fail("body is required"); };Ok(UpsertManagedNoteArgs { external_id, managed_by, body: body.to_string(), title: optional_string(args, "title"), source_hash: optional_string(args, "sourceHash"), })}#[derive(Debug, Clone)]pubstructListManagedNotesArgs {pub managed_by: String,pub limit: i64,}pubfn validate_list_managed_notes(args: &Map<String, Value>) -> Valid<ListManagedNotesArgs> {letSome(managed_by) = require_string(args, "managedBy") else {return fail("managedBy is required"); };Ok(ListManagedNotesArgs { managed_by, limit: bounded_limit(args, 500, 1000), })}// ── goals ───────────────────────────────────────────────────────────────────#[derive(Debug, Clone)]pubstructListGoalsArgs {pub include_all: bool,pub limit: i64,}pubfn validate_list_goals(args: &Map<String, Value>) -> Valid<ListGoalsArgs> {Ok(ListGoalsArgs { include_all: is_true(args, "includeAll"), limit: bounded_limit(args, 50, 100), })}#[derive(Debug, Clone)]pubstructCreateGoalArgs {pub title: String,pub why: Option<String>,pub target_date: Option<String>,}pubfn validate_create_goal(args: &Map<String, Value>) -> Valid<CreateGoalArgs> {letSome(title) = require_string(args, "title") else {return fail("title is required"); };let why = optional_string(args, "why");let target_date = optional_string(args, "targetDate");ifletSome(date) = &target_date {if !is_calendar_date(date) {return fail("targetDate must be YYYY-MM-DD"); } }Ok(CreateGoalArgs { title, why, target_date, })}#[derive(Debug, Clone)]pubstructUpdateGoalArgs {pub id: String,pub title: Option<String>,pub why: Clearable<String>,pub target_date: Clearable<String>,pub status: Option<String>,}pubfn validate_update_goal(args: &Map<String, Value>) -> Valid<UpdateGoalArgs> {let id = require_uuid(args, "id")?;let title = optional_string(args, "title");let why = clearable_string(args, "why");let target_date = clearable_calendar_date(args, "targetDate")?;let status = optional_enum(args, "status", GOAL_STATUSES)?;if title.is_none() && why.is_unchanged() && target_date.is_unchanged() && status.is_none() {return fail("nothing to change — pass a field to change"); }Ok(UpdateGoalArgs { id, title, why, target_date, status, })}// ── people ──────────────────────────────────────────────────────────────────#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructBirthday {pub month: i64,pub day: i64,pub year: Option<i64>,}fn parse_birthday(raw: &Value) -> Valid<Birthday> {letSome(object) = raw.as_object() else {return fail("birthday must be an object with month and day"); };let whole = |key: &str| -> Option<i64> { object .get(key) .and_then(Value::as_f64) .filter(|value| value.fract() == 0.0 && value.is_finite()) .map(|value| value as i64) };let (Some(month), Some(day)) = (whole("month"), whole("day")) else {return fail("birthday needs a real month (1-12) and day"); };if !(1..=12).contains(&month) || day < 1 || day > DAYS_IN_MONTH[(month - 1) as usize] {return fail("birthday needs a real month (1-12) and day"); }// No year, or a year said as null (a record's yearless "--MM-DD" read// into its parts): the day alone.let year = match object.get("year") {None | Some(Value::Null) => None,Some(_) => match whole("year") {Some(year) => Some(year),None => return fail("birthday year must be a whole number"), }, };Ok(Birthday { month, day, year })}#[derive(Debug, Clone)]pubstructListPeopleArgs {pub q: Option<String>,pub include_archived: bool,pub source: Option<String>,pub limit: i64,pub offset: i64,}pubfn validate_list_people(args: &Map<String, Value>) -> Valid<ListPeopleArgs> {let q = optional_string(args, "q");let source = optional_enum(args, "source", CONTACT_SOURCES)?;let offset = match args.get("offset") {None => 0,Some(value) => match value.as_f64() {Some(number) if number.is_finite() && number >= 0.0 => number.trunc() as i64, _ => return fail("offset must be a non-negative integer"), }, };Ok(ListPeopleArgs { q, include_archived: is_true(args, "includeArchived"), source, limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST), offset, })}/// The handle lists a person write names, each the WHOLE list of its kind:/// `phones`, `emails`, and since v90 `instagram`, `facebook`, `linkedin`.fn handle_lists(args: &Map<String, Value>) -> Valid<Vec<(HandleKind, Vec<String>)>> {letmut out = Vec::new();for (key, kind) in [ ("phones", HandleKind::Phone), ("emails", HandleKind::Email), ("instagram", HandleKind::Instagram), ("facebook", HandleKind::Facebook), ("linkedin", HandleKind::Linkedin), ] {ifletSome(values) = optional_string_list(args, key)? { out.push((kind, values)); } }Ok(out)}#[derive(Debug, Clone)]pubstructCreatePersonArgs {pub full_name: String,/// Each kind the caller named, and the whole list it should hold.pub handles: Vec<(HandleKind, Vec<String>)>,pub org: Option<String>,pub role_title: Option<String>,pub city: Option<String>,pub language: Option<String>,pub timezone: Option<String>,pub birthday: Option<Birthday>,pub allow_duplicate_name: bool,}fn person_language(args: &Map<String, Value>) -> Valid<Option<String>> {letSome(value) = args.get("language") else { returnOk(None); };letSome(language) = value.as_str() else { return fail("language is one language code"); };if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_lowercase()) {return fail("language is one language code, without a region or another language"); }Ok(Some(language.to_string()))}pubfn validate_create_person(args: &Map<String, Value>) -> Valid<CreatePersonArgs> {if args.contains_key("howWeMet") {return fail(HOW_WE_MET_RETIRED_REFUSAL); }letSome(full_name) = require_string(args, "fullName") else {return fail("fullName is required"); };let handles = handle_lists(args)?;let birthday = match args.get("birthday") {None => None,Some(raw) => Some(parse_birthday(raw)?), };Ok(CreatePersonArgs { full_name, handles, org: optional_string(args, "org"), role_title: optional_string(args, "roleTitle"), city: optional_string(args, "city"), language: person_language(args)?, timezone: optional_string(args, "timezone"), birthday, allow_duplicate_name: is_true(args, "allowDuplicateName"), })}#[derive(Debug, Clone)]pubstructUpdatePersonArgs {pub id: String,pub full_name: Option<String>,/// Each kind the caller named, and the whole list it should now hold.pub handles: Vec<(HandleKind, Vec<String>)>,/// `addPhones` / `addEmails`: handles appended after what the person/// holds when the write runs — never a replacement, so a list read a/// minute ago cannot take away one added since (the contacts tidy).pub adds: Vec<(HandleKind, Vec<String>)>,pub org: Clearable<String>,pub role_title: Clearable<String>,pub city: Clearable<String>,pub language: Option<String>,pub timezone: Clearable<String>,/// `None` leaves it alone, `Some(None)` clears the whole trio.pub birthday: Option<Option<Birthday>>,/// **Only ever a REMOVAL.** `true` means the caller passed `avatarKey:/// null` and the photograph comes off; there is no way to SET one here,/// because setting one means bytes, and bytes are `capture.avatar`'s. A/// tool that could write the column would let an assistant point a person/// at any object key in the file.pub clear_avatar: bool,pub allow_duplicate_name: bool,}pubfn validate_update_person(args: &Map<String, Value>) -> Valid<UpdatePersonArgs> {if args.contains_key("howWeMet") {return fail(HOW_WE_MET_RETIRED_REFUSAL); }let id = require_uuid(args, "id")?;let full_name = optional_string(args, "fullName");let handles = handle_lists(args)?;letmut adds = Vec::new();for (key, kind, whole) in [("addPhones", HandleKind::Phone, "phones"), ("addEmails", HandleKind::Email, "emails")] {ifletSome(values) = optional_string_list(args, key)? {if args.contains_key(whole) {return fail(format!("pass {whole} (the whole list) or {key} (added to it), not both")); } adds.push((kind, values)); } }let birthday = match args.get("birthday") {None => None,Some(Value::Null) => Some(None),Some(raw) => Some(Some(parse_birthday(raw)?)), };let org = clearable_string(args, "org");let role_title = clearable_string(args, "roleTitle");let city = clearable_string(args, "city");let language = person_language(args)?;let timezone = clearable_string(args, "timezone");// ONE DIRECTION ONLY. A photograph arrives with bytes, and bytes arrive// through `capture.avatar` on the owner's own phone — so this tool can take// one OFF and can never put one on. A non-null value is refused by name// rather than ignored, because an assistant that thought it had set a face// would go on to say so.let clear_avatar = match args.get("avatarKey") {None => false,Some(Value::Null) => true,Some(_) => {return fail("`avatarKey` can only be null here — that removes the photograph. Setting one \ means bytes, which the owner's own app writes through capture.avatar", ) } };if full_name.is_none() && handles.is_empty() && adds.iter().all(|(_, values)| values.is_empty()) && birthday.is_none() && org.is_unchanged() && role_title.is_unchanged() && city.is_unchanged() && language.is_none() && timezone.is_unchanged() && !clear_avatar {return fail("nothing to change — pass a field to change"); }Ok(UpdatePersonArgs { id, full_name, handles, adds, org, role_title, city, language, timezone, birthday, clear_avatar, allow_duplicate_name: is_true(args, "allowDuplicateName"), })}pubfn validate_merge_people(args: &Map<String, Value>) -> Valid<(String, String)> {let survivor_id = require_uuid(args, "survivorId")?;let duplicate_id = require_uuid(args, "duplicateId")?;if survivor_id == duplicate_id {return fail("survivorId and duplicateId are the same person"); }Ok((survivor_id, duplicate_id))}/// `validateArchivePerson` / `validateUnarchivePerson` / `validateUnarchiveNote`.pubfn validate_id(args: &Map<String, Value>) -> Valid<String> { require_uuid(args, "id")}// ── places ──────────────────────────────────────────────────────────────────fn finite_in_range(value: Option<&Value>, min: f64, max: f64) -> Option<f64> { value .and_then(Value::as_f64) .filter(|number| number.is_finite() && *number >= min && *number <= max)}/// What `lat` and `lng` say together: `None` when neither is sent,/// `Some(None)` when both are null (no pin, or the pin taken off), and the/// pair when both are numbers. Half a coordinate is no place, so one number/// beside a null or missing other is refused, naming the one missing.fn coordinate_pair(args: &Map<String, Value>) -> Valid<Option<Option<(f64, f64)>>> {let raw_lat = args.get("lat");let raw_lng = args.get("lng");if raw_lat.is_none() && raw_lng.is_none() {returnOk(None); }let given = |value: Option<&Value>| value.is_some_and(|value| !value.is_null());match (given(raw_lat), given(raw_lng)) { (false, false) => Ok(Some(None)), (true, false) => fail("A place needs both a latitude and a longitude; this one has no longitude"), (false, true) => fail("A place needs both a latitude and a longitude; this one has no latitude"), (true, true) => match ( finite_in_range(raw_lat, -90.0, 90.0), finite_in_range(raw_lng, -180.0, 180.0), ) { (Some(lat), Some(lng)) => Ok(Some(Some((lat, lng)))), _ => fail("lat must be -90..90 and lng -180..180"), }, }}#[derive(Debug, Clone)]pubstructCreateLocationArgs {pub name: String,pub address: Option<String>,pub note: Option<String>,pub coordinate: Option<(f64, f64)>,}pubfn validate_create_location(args: &Map<String, Value>) -> Valid<CreateLocationArgs> {letSome(name) = require_string(args, "name") else {return fail("name is required"); };// A blank place page sends the coordinates it has not been given as// null: a place with neither is a place without a pin.let coordinate = coordinate_pair(args)?.flatten();Ok(CreateLocationArgs { name, address: optional_string(args, "address"), note: optional_string(args, "note"), coordinate, })}#[derive(Debug, Clone)]pubstructUpdateLocationArgs {pub id: String,pub name: Option<String>,pub address: Clearable<String>,pub note: Clearable<String>,/// `None` leaves the pair alone; `Some(None)` clears both.pub coordinate: Option<Option<(f64, f64)>>,}pubfn validate_update_location(args: &Map<String, Value>) -> Valid<UpdateLocationArgs> {let id = require_uuid(args, "id")?;let name = optional_string(args, "name");let address = clearable_string(args, "address");let note = clearable_string(args, "note");let coordinate = coordinate_pair(args)?;if name.is_none() && address.is_unchanged() && note.is_unchanged() && coordinate.is_none() {return fail("nothing to change — pass a field to change"); }Ok(UpdateLocationArgs { id, name, address, note, coordinate, })}// ── events ──────────────────────────────────────────────────────────────────/// A repeat rule as the file stores it: the VALUE, never the `RRULE:` line.fn event_rrule(raw: &str) -> Valid<String> {let value = raw .strip_prefix("RRULE:") .or_else(|| raw.strip_prefix("rrule:")) .unwrap_or(raw) .trim();if value.is_empty() {return fail("rrule must be a repeat rule, or null to clear it"); }match parse_rrule(value) {Ok(_) => Ok(value.to_string()),Err(error) => fail(format!("rrule is not a repeat rule Cotton can expand: {error}" )), }}/// The fields an event edit carries, read once for `update_event` and for/// `update_events`. Two readers of the same six fields would eventually accept/// different things, and the batch form is where that goes unnoticed.#[derive(Debug, Clone, Default)]pubstructEventPatch {pub title: Option<String>,pub starts_at: Option<String>,/// The start was given as a bare day (`YYYY-MM-DD`), naming no time.pub starts_bare: bool,pub ends_at: Clearable<String>,pub all_day: Option<bool>,pub location: Clearable<String>,pub notes: Clearable<String>,pub rrule: Clearable<String>,}implEventPatch {pubfn is_empty(&self) -> bool {self.title.is_none() && self.starts_at.is_none() && self.ends_at.is_unchanged() && self.all_day.is_none() && self.location.is_unchanged() && self.notes.is_unchanged() && self.rrule.is_unchanged() }}fn event_patch_from(args: &Map<String, Value>) -> Valid<EventPatch> {let title = optional_string(args, "title");let starts_at = match optional_string(args, "startsAt") {None => None,Some(raw) => match iso_timestamp(&raw) {Some(parsed) => Some(parsed),None => return fail("startsAt must be an ISO 8601 timestamp"), }, };let ends_at = clearable_timestamp(args, "endsAt")?;let all_day = optional_boolean(args, "allDay")?;let location = clearable_string(args, "location");let notes = clearable_string(args, "notes");let rrule = match args.get("rrule") {None => Clearable::Unchanged,Some(Value::Null) => Clearable::Cleared,Some(Value::String(raw)) => Clearable::Set(event_rrule(raw)?),Some(_) => return fail("rrule must be a repeat rule, or null to clear it"), };Ok(EventPatch { title, starts_bare: bare_day(optional_string(args, "startsAt").as_deref()).is_some(), starts_at, ends_at, all_day, location, notes, rrule, })}/// `occurrenceAt` + `scope`, read the same way by the edit and the delete.////// `scope` is REQUIRED beside an occurrence rather than defaulting, because the/// two answers differ by an entire series.fn event_occurrence_from(args: &Map<String, Value>) -> Valid<(Option<String>, Option<String>)> {let occurrence_at =match optional_string(args, "occurrenceAt") {None => None,Some(raw) => match iso_timestamp(&raw) {Some(parsed) => Some(parsed),None => return fail("occurrenceAt must be an ISO 8601 timestamp — the occurrenceAt list_events \ {expand:true} returned", ), }, };let scope = optional_enum(args, "scope", EVENT_SCOPES)?;if occurrence_at.is_some() && scope.is_none() {return fail("scope is required with occurrenceAt: \"this\" for that one occurrence, \"all\" for \ the whole series", ); }if occurrence_at.is_none() && scope.as_deref() == Some("this") {return fail("scope \"this\" needs occurrenceAt — the instant of the occurrence, from list_events \ {expand:true}", ); }Ok((occurrence_at, scope))}/// 1–50 event uuids — the batch verbs' one shared argument.fn event_id_list(args: &Map<String, Value>) -> Valid<Vec<String>> {letSome(raw) = args.get("ids").and_then(Value::as_array) else {return fail("ids must be an array of 1 to 50 event uuids"); };if raw.is_empty() || raw.len() > EVENT_BATCH_MAX {return fail("ids must be an array of 1 to 50 event uuids"); }letmut seen: Vec<String> = Vec::new();for item in raw {match item.as_str().map(str::trim) {Some(value) if is_uuid(value) => {// Deduplicated rather than refused: the same id twice is a// caller listing what it found.if !seen.iter().any(|id| id == value) { seen.push(value.to_string()); } } _ => {return fail(format!("ids entries must be event uuids, got {}", cotton_store::protocol::js::json_stringify(item) )) } } }Ok(seen)}#[derive(Debug, Clone)]pubstructCreateEventArgs {pub title: String,pub starts_at: String,pub ends_at: Option<String>,pub location: Option<String>,pub notes: Option<String>,pub all_day: Option<bool>,pub rrule: Option<String>,pub timezone: Option<String>,/// The days `startsAt` / `endsAt` were given as, when they were bare/// `YYYY-MM-DD`: a day said with no time is a whole day, in the writer's/// zone — never UTC midnight, which is 5:30 am in Kolkata.pub days: (Option<String>, Option<String>),}/// A bare `YYYY-MM-DD` — a day said with no time.fn bare_day(raw: Option<&str>) -> Option<String> { raw.filter(|raw| raw.len() == 10 && is_calendar_date(raw)).map(str::to_string)}pubfn validate_create_event(args: &Map<String, Value>) -> Valid<CreateEventArgs> {letSome(title) = require_string(args, "title") else {return fail("title is required"); };letSome(starts_at) = require_string(args, "startsAt") .as_deref() .and_then(iso_timestamp)else {return fail("startsAt must be an ISO 8601 timestamp"); };let ends_at = match optional_string(args, "endsAt") {None => None,Some(raw) => match iso_timestamp(&raw) {None => return fail("endsAt must be an ISO 8601 timestamp"),Some(parsed) => {if parsed < starts_at {return fail("endsAt must not be before startsAt"); }Some(parsed) } }, };let days = ( bare_day(optional_string(args, "startsAt").as_deref()), bare_day(optional_string(args, "endsAt").as_deref()), );let all_day = match (optional_boolean(args, "allDay")?, &days.0) { (Some(false), Some(_)) => {return fail("startsAt names a day with no time — give it a time, or leave allDay out for a whole-day event"); } (None, Some(_)) => Some(true), (said, _) => said, };let rrule = match optional_string(args, "rrule") {None => None,Some(raw) => Some(event_rrule(&raw)?), };Ok(CreateEventArgs { title, starts_at, ends_at, location: optional_string(args, "location"), notes: optional_string(args, "notes"), all_day, rrule, timezone: optional_string(args, "timezone"), days, })}#[derive(Debug, Clone)]pubstructListEventsArgs {pub from: String,pub to: String,pub limit: i64,pub expand: bool,}pubfn validate_list_events(args: &Map<String, Value>, now_ms: i64) -> Valid<ListEventsArgs> {usecrate::mcp::handlers::common::{iso_of_ms, parse_ms};let from = match optional_string(args, "from") {None => iso_of_ms(now_ms),Some(raw) => match iso_timestamp(&raw) {Some(parsed) => parsed,None => return fail("from must be an ISO 8601 timestamp"), }, };let to = match optional_string(args, "to") {None => {let start = parse_ms(&from).unwrap_or(now_ms); iso_of_ms(start + LIST_EVENTS_WINDOW_DAYS * 86_400_000) }Some(raw) => match iso_timestamp(&raw) {Some(parsed) => parsed,None => return fail("to must be an ISO 8601 timestamp"), }, };if from >= to {return fail("from must be before to"); }let expand = optional_boolean(args, "expand")?;Ok(ListEventsArgs { from, to, limit: bounded_limit(args, 100, crate::mcp::handlers::common::MAX_LIST), expand: expand.unwrap_or(false), })}#[derive(Debug, Clone)]pubstructUpdateEventArgs {pub id: String,pub patch: EventPatch,pub occurrence_at: Option<String>,pub scope: Option<String>,pub timezone: Option<String>,}pubfn validate_update_event(args: &Map<String, Value>) -> Valid<UpdateEventArgs> {let id = require_uuid(args, "id")?;let patch = event_patch_from(args)?;let (occurrence_at, scope) = event_occurrence_from(args)?;if patch.is_empty() {return fail("nothing to change — pass a field to change"); }// A rule belongs to the series, and one occurrence is the opposite of a// series. Accepting both would leave the caller guessing which one won.if scope.as_deref() == Some("this") && !patch.rrule.is_unchanged() {return fail("rrule cannot be set on one occurrence — call update_event again with scope \"all\" to \ change how the series repeats", ); }Ok(UpdateEventArgs { id, patch, occurrence_at, scope, timezone: optional_string(args, "timezone"), })}#[derive(Debug, Clone)]pubstructMoveTo {pub date: String,pub timezone: Option<String>,}#[derive(Debug, Clone)]pubstructUpdateEventsArgs {pub ids: Vec<String>,pub patch: Option<EventPatch>,pub shift_minutes: Option<i64>,pub move_to: Option<MoveTo>,pub timezone: Option<String>,}pubfn validate_update_events(args: &Map<String, Value>) -> Valid<UpdateEventsArgs> {let ids = event_id_list(args)?;let forms = ["patch", "shift", "moveTo"] .iter() .filter(|key| args.contains_key(**key)) .count();if forms != 1 {return fail("pass exactly one of patch, shift or moveTo — they answer three different questions \ and combining them would leave the order between them undefined", ); }letmut patch = None;ifletSome(raw) = args.get("patch") {letSome(object) = raw.as_object() else {return fail("patch must be an object of fields to change"); };let parsed = event_patch_from(object)?;if parsed.is_empty() {return fail("nothing to change — pass a field to change in patch"); } patch = Some(parsed); }letmut shift_minutes = None;ifletSome(raw) = args.get("shift") {let minutes = raw .as_object() .and_then(|object| object.get("minutes")) .and_then(Value::as_f64) .filter(|value| value.is_finite() && value.fract() == 0.0);letSome(minutes) = minutes else {return fail("shift.minutes must be a whole number of minutes"); };if minutes == 0.0 {return fail("shift.minutes of 0 moves nothing"); } shift_minutes = Some(minutes as i64); }letmut move_to = None;ifletSome(raw) = args.get("moveTo") {let object = raw.as_object();let date = object .and_then(|object| object.get("date")) .and_then(Value::as_str) .map(str::trim) .unwrap_or("");if !is_calendar_date(date) {return fail("moveTo.date must be a calendar date, YYYY-MM-DD"); }let zone = object .and_then(|object| object.get("timezone")) .and_then(Value::as_str) .map(str::trim) .filter(|zone| !zone.is_empty()) .map(str::to_string); move_to = Some(MoveTo { date: date.to_string(), timezone: zone, }); }Ok(UpdateEventsArgs { ids, patch, shift_minutes, move_to, timezone: optional_string(args, "timezone"), })}#[derive(Debug, Clone)]pubstructDeleteEventArgs {pub id: String,pub occurrence_at: Option<String>,pub scope: Option<String>,}pubfn validate_delete_event(args: &Map<String, Value>) -> Valid<DeleteEventArgs> {let id = require_uuid(args, "id")?;let (occurrence_at, scope) = event_occurrence_from(args)?;Ok(DeleteEventArgs { id, occurrence_at, scope, })}pubfn validate_delete_events(args: &Map<String, Value>) -> Valid<Vec<String>> { event_id_list(args)}/// `JSON.stringify` of a value a refusal quotes — re-exported so the handler/// modules read one spelling.pubfn quote_value(value: &str) -> String { quoted(value)}