//! `create_todo`, `complete_todo`, `list_todos`, `update_todo`,//! `update_todos` — the todos block of `packages/server/src/mcp/records.ts`.//!//! The one idea worth naming here: a due is TWO spellings of one fact. A raw//! instant (`dueAt`) and a day-plus-optional-clock (`dueDate` / `dueTime`) name//! the same moment, and turning the pair into the instant needs a ZONE — which//! is why a file that has never been told one refuses rather than falling back//! to UTC. A day in the wrong zone is a todo on the wrong day, silently.use std::collections::{HashMap, HashSet};use cotton_core::transforms::moment_split::{ join_moment, next_moment, split_moment, MomentSplit, MomentSplitError, PartChange,};use cotton_core::transforms::rrule::parse_todo_rule;use cotton_core::rules::shell_lines;use cotton_core::transforms::zoned_clock::ZoneError;use serde_json::{Map, Value};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ insert_row, int, maybe_row, now_iso, project_filter, project_slug_of, projects, put, rows, text, update_row, workspace_timezone_or_null, ProjectFilter, ProjectRef, Valid,};usecrate::mcp::handlers::records_1::engine_shim::{ materialize_template, RecurrenceTemplate, RECURRENCE_TEMPLATE_COLUMNS,};usecrate::mcp::handlers::records_1::validate::{ validate_complete_todo, validate_create_todo, validate_list_todos, validate_update_todo, validate_update_todos, TodoCursor, TodoDueChange, TodoPatch,};usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Order, Query};use rusqlite::types::ValueasSqlValue;/// The columns `list_todos` reads.const TODO_LIST_COLUMNS: &[&str] = &["id","title","notes","status","due_at","snoozed_until","priority","completed_at","recurrence_id","created_at",];/// The columns the update verbs read and answer with.const TODO_UPDATE_COLUMNS: &[&str] = &["id","title","notes","status","due_at","snoozed_until","priority","completed_at",];/// The day and clock a due instant reads as — present only when a zone is/// known to read them in.////// Without one the instant alone is the honest answer: a day derived in UTC/// would be the wrong day for most of the planet, most evenings. A row whose/// `due_at` does not parse answers nothing rather than taking the whole list/// down with it.pubfn todo_due_fields(out: &mutMap<String, Value>, due_at: Option<&str>, timezone: Option<&str>) {let (Some(due_at), Some(timezone)) = (due_at, timezone) else {return; };letOk(due) = split_moment(due_at, timezone) else {return; }; out.insert("dueDate".to_string(), Value::from(due.date)); out.insert("dueTime".to_string(), due.time.map_or(Value::Null, Value::from), );}/// The zone a due pair is read in: the call's, else the workspace's, else a/// refusal that says what to do. NEVER UTC.fn due_zone(ctx: &Ctx<'_>, named: Option<&str>) -> Valid<String> {match named {Some(zone) => Ok(zone.to_string()),None => workspace_timezone_or_null(ctx)?.ok_or_else(|| ToolFailure::new(due_line(ctx, "no_zone", &[]))), }}/// One `refusal.due.*` line, said with this database's rows (the kit's words/// where it holds none).fn due_line(ctx: &Ctx<'_>, line: &str, fills: &[(&str, &str)]) -> String {let rows = crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); shell_lines::resolve("refusal", &format!("due.{line}"), &rows, fills).unwrap_or_default()}/// A moment the call could not place, said from the `refusal` set.fn due_sentence(ctx: &Ctx<'_>, error: &MomentSplitError) -> String {match error {MomentSplitError::NotAnInstant(value) => due_line(ctx, "not_an_instant", &[("value", value)]),MomentSplitError::NotACalendarDay(value) => due_line(ctx, "not_a_calendar_day", &[("value", value)]),MomentSplitError::NotAClockTime(value) => due_line(ctx, "not_a_clock_time", &[("value", value)]),MomentSplitError::TimeNeedsADay => due_line(ctx, "time_needs_a_day", &[]),MomentSplitError::Zone(ZoneError::UnknownTimeZone(zone)) => due_line(ctx, "unknown_zone", &[("zone", zone)]),MomentSplitError::Zone(ZoneError::UnreadableInstant(at)) => { due_line(ctx, "unreadable_instant", &[("value", &at.to_string())]) } }}/// The next `due_at` for a row after a due change — the raw instant when the/// call held one, otherwise the day/time pair resolved against the row's own/// current day in the zone.fn resolve_due( ctx: &Ctx<'_>, current: Option<&str>, change: &TodoDueChange, zone: Option<&str>,) -> Valid<Option<String>> {ifletSome(due_at) = &change.due_at {returnOk(due_at.clone()); }letSome(zone) = zone else {// `dueZone` refused before any row was read; this is the type's guard.returnErr(ToolFailure::new(due_line(ctx, "needs_a_zone", &[]))); };let date = match &change.due_date {None => PartChange::Unchanged,Some(None) => PartChange::Cleared,Some(Some(date)) => PartChange::Set(date.as_str()), };let time = match &change.due_time {None => PartChange::Unchanged,Some(None) => PartChange::Cleared,Some(Some(time)) => PartChange::Set(time.as_str()), }; next_moment(current, date, time, zone).map_err(|error| ToolFailure::new(due_sentence(ctx, &error)))}// ── create_todo ─────────────────────────────────────────────────────────────pubfn create_todo(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {letmut args = validate_create_todo(args)?;// The day/time pair becomes the instant here, ONCE, so the rrule branch and// the plain insert below see one `dueAt` whichever spelling the call used.ifletSome(Some(date)) = args.due.due_date.clone() {let zone = due_zone(ctx, args.due.timezone.as_deref())?;let due = MomentSplit { date, time: args.due.due_time.clone().flatten(), };let instant = join_moment(&due, &zone) .map_err(|error| ToolFailure::new(due_sentence(ctx, &error)))?; args.due.due_at = Some(Some(instant)); }let due_at = args.due.due_at.clone().flatten();ifletSome(rrule) = args.rrule.clone() {return create_repeating_todo(ctx, &args.title, args.notes.as_deref(), &rrule, &due_at); }let id = ctx.new_uuid();letmut patch = Map::new(); patch.insert("title".to_string(), Value::from(args.title.clone())); patch.insert("due_at".to_string(), due_at.clone().map_or(Value::Null, Value::from), ); patch.insert("notes".to_string(), args.notes.clone().map_or(Value::Null, Value::from), ); insert_row(ctx, "cotton_todos", &id, patch)?; ctx.commit()?;let zone = match args.due.timezone.clone() {Some(zone) => Some(zone),None => workspace_timezone_or_null(ctx)?, };letmut out = Map::new(); out.insert("id".to_string(), Value::from(id)); out.insert("title".to_string(), Value::from(args.title)); out.insert("due_at".to_string(), due_at.clone().map_or(Value::Null, Value::from), ); out.insert("status".to_string(), Value::from("open")); todo_due_fields(&mut out, due_at.as_deref(), zone.as_deref());Ok(Value::Object(out))}/// A repeating todo is a TEMPLATE whose occurrences materialize as rows — the/// same planner the app and the hourly tick run.fn create_repeating_todo( ctx: &mutCtx<'_>, title: &str, notes: Option<&str>, rrule: &str, due_at: &Option<String>,) -> ToolResult { parse_todo_rule(rrule).map_err(ToolFailure::new)?;let template_id = ctx.new_uuid();letmut patch = Map::new(); patch.insert("title".to_string(), Value::from(title)); patch.insert("notes".to_string(), notes.map_or(Value::Null, Value::from)); patch.insert("rrule".to_string(), Value::from(rrule));// The validator guarantees dueAt rides with rrule. patch.insert("dtstart".to_string(), due_at.clone().map_or(Value::Null, Value::from), ); insert_row(ctx, "cotton_todo_recurrences", &template_id, patch)?; ctx.commit()?;// NO UTC FLOOR. Without a recorded workspace zone there is no honest answer// to "when does this happen", and inventing one here would make this half a// SECOND producer disagreeing with the phone — which falls back to the// device's zone and then writes it down. The series is created either way;// the rows appear on the phone's next pass, moments later, in the right// zone.letSome(timezone) = workspace_timezone_or_null(ctx)? else {letmut out = Map::new(); out.insert("id".to_string(), Value::from(template_id)); out.insert("title".to_string(), Value::from(title)); out.insert("due_at".to_string(), due_at.clone().map_or(Value::Null, Value::from), ); out.insert("status".to_string(), Value::from("open")); out.insert("repeats".to_string(), Value::from(rrule)); out.insert("note".to_string(),Value::from("occurrences appear once the app sets the workspace timezone"), );returnOk(Value::Object(out)); };let template = maybe_row( ctx, &Query::on("cotton_todo_recurrences") .columns(RECURRENCE_TEMPLATE_COLUMNS) .eq("id", template_id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no todo series with id {template_id}")))?; materialize_template(ctx, &RecurrenceTemplate::of(&template), &timezone)?;let first = maybe_row( ctx, &Query::on("cotton_todos") .columns(&["id", "title", "due_at", "status"]) .eq("recurrence_id", template_id) .order_by("occurrence_at", Order::Asc), )?;letmut out = first.unwrap_or_default(); out.insert("repeats".to_string(), Value::from(rrule));Ok(Value::Object(out))}// ── complete_todo ───────────────────────────────────────────────────────────pubfn complete_todo(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = validate_complete_todo(args)?;// A todo in the Bin is not here to complete.let live = Query::on("cotton_todos").eq("id", id.clone()).filter(Filter::IsNull("trashed_at".to_string()));letSome(_existing) = maybe_row(ctx, &live)? else {returnErr(ToolFailure::new(format!("no todo with id {id}"))); };let completed_at = now_iso(ctx);letmut patch = Map::new(); patch.insert("status".to_string(), Value::from("done")); patch.insert("completed_at".to_string(),Value::from(completed_at.clone()), ); miss_the_earlier_run(ctx, &id, &patch)?; update_row(ctx, "cotton_todos", &id, patch)?; ctx.commit()?;let row = maybe_row( ctx, &Query::on("cotton_todos") .columns(&["id", "title", "status", "completed_at"]) .eq("id", id.clone()), )? .ok_or_else(|| ToolFailure::new(format!("no todo with id {id}")))?;Ok(Value::Object(row))}// ── list_todos ──────────────────────────────────────────────────────────────/// Which todos a call's `project` / `unfiled` narrows the list to.////// A todo's project is a LINK ROW (`cotton_project_links`), never a column on/// the todo, so neither question is a `WHERE` this query layer can write: the/// link rows are read once and the test is applied to the rows that come back.enumMembership {/// No filter — every todo the other arguments allow.Every,/// `unfiled` / `project: "none"` — the todos in NO project. The set is the/// todos that ARE in one, and the test is the exclusion.Unfiled(HashSet<String>),/// One project's todos, by the ids its link rows name.Under(HashSet<String>),}implMembership {fn holds(&self, id: &str) -> bool {matchself {Membership::Every => true,Membership::Unfiled(filed) => !filed.contains(id),Membership::Under(ids) => ids.contains(id), } }/// Whether the SQL may carry the page's LIMIT.////// Only when nothing is dropped afterwards: a `LIMIT` in front of a test/// the database cannot run answers a short page and calls it the end of/// the list, which is the bug this whole verb is here to stop. With a/// membership filter the read is the cursor's tail and the page is cut in/// Rust — one person's todos, not a table scan of somebody else's.fn bounded(&self) -> bool { matches!(self, Membership::Every) }}/// Every todo's project links, read once: what each todo says about its own/// filing, and the two sets the membership filters are.structTodoLinks {/// Todo id -> the slugs it is filed under, sorted. slugs: HashMap<String, Vec<String>>,/// Every todo that is in at least one project. filed: HashSet<String>,/// The todos in the ONE project a call named, when it named one. under: HashSet<String>,}fn todo_project_links( ctx: &Ctx<'_>, known: &[ProjectRef], wanted: Option<&str>,) -> Result<TodoLinks, ToolFailure> {let links = rows( ctx, &Query::on("cotton_project_links") .columns(&["project_id", "record_id"]) .eq("record_kind", "todo".to_string()), )?;letmut slugs: HashMap<String, Vec<String>> = HashMap::new();letmut filed: HashSet<String> = HashSet::new();letmut under: HashSet<String> = HashSet::new();for link in &links {let (Some(project_id), Some(record_id)) = (text(link, "project_id"), text(link, "record_id"))else {continue; }; filed.insert(record_id.clone());if wanted == Some(project_id.as_str()) { under.insert(record_id.clone()); }// A link to a project this file no longer holds names no slug, and is// still a filing — which is why `filed` is stamped above this.ifletSome(slug) = project_slug_of(known, &project_id) { slugs.entry(record_id).or_default().push(slug); } }for list in slugs.values_mut() { list.sort(); list.dedup(); }Ok(TodoLinks { slugs, filed, under, })}pubfn list_todos(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_list_todos(args)?;let timezone = workspace_timezone_or_null(ctx)?;let known = projects(ctx)?;let wanted = if args.unfiled {ProjectFilter::NoProject } else { project_filter(&known, args.project.as_deref())? };let links = todo_project_links( ctx, &known,match &wanted {ProjectFilter::Project(id) => Some(id.as_str()), _ => None, }, )?;let membership = match wanted {ProjectFilter::Every => Membership::Every,ProjectFilter::NoProject => Membership::Unfiled(links.filed),ProjectFilter::Project(_) => Membership::Under(links.under), };let base = || {// A todo in the Bin is listed by the Bin alone.letmut query = Query::on("cotton_todos") .columns(TODO_LIST_COLUMNS) .filter(Filter::IsNull("trashed_at".to_string()));if args.status != "all" { query = query.eq("status", args.status.clone()); } query };let kept = |rows: Vec<Map<String, Value>>| -> Vec<Map<String, Value>> { rows.into_iter() .filter(|row| membership.holds(&text(row, "id").unwrap_or_default())) .collect() };// Dated and undated are two reads because a due-window comparison silently// drops NULLs — the undated todos are fetched by name, never by accident.// They are also two ORDERS, which is what the cursor has to name: the// dated by what is owed NEXT, the undated by when they were filed. Each// order ends in `id`, because a cursor over a key several rows share is a// page that repeats rows or skips them.letmut all: Vec<Map<String, Value>> = Vec::new();if !matches!(args.cursor, Some(TodoCursor::Undated { .. })) {letmut dated = base() .filter(Filter::NotNull("due_at".to_string())) .order_by("due_at", Order::Asc) .order_by("id", Order::Asc);if membership.bounded() { dated = dated.limit(args.limit + 1); }ifletSome(after) = &args.due_after { dated = dated.filter(Filter::Gte("due_at".to_string(),SqlValue::Text(after.clone()), )); }ifletSome(before) = &args.due_before { dated = dated.filter(Filter::Lt("due_at".to_string(),SqlValue::Text(before.clone()), )); }ifletSome(TodoCursor::Dated { due_at, id }) = &args.cursor { dated = dated.filter(Filter::KeysetAfter { column: "due_at".to_string(), value: SqlValue::Text(due_at.clone()), tie_column: "id".to_string(), tie: SqlValue::Text(id.clone()), }); } all = kept(rows(ctx, &dated)?); }if args.include_undated && (all.len() as i64) <= args.limit {letmut undated = base() .filter(Filter::IsNull("due_at".to_string())) .order_by("created_at", Order::Desc) .order_by("id", Order::Desc);if membership.bounded() { undated = undated.limit(args.limit + 1 - all.len() as i64); }ifletSome(TodoCursor::Undated { created_at, id }) = &args.cursor { undated = undated.filter(Filter::KeysetBefore { column: "created_at".to_string(), value: SqlValue::Text(created_at.clone()), tie_column: "id".to_string(), tie: SqlValue::Text(id.clone()), }); } all.extend(kept(rows(ctx, &undated)?)); }let more = all.len() as i64 > args.limit;letmut out = Map::new(); out.insert("more".to_string(), Value::Bool(more));// The zone the day/time fields were read in — absent when the file has// none yet, in which case only the raw instants are answered. put(&mut out, "timezone", timezone.clone().map(Value::from));let page: Vec<Map<String, Value>> = all.into_iter().take(args.limit as usize).collect();// The handle for the next page, off the LAST row that travels — present// only when there IS a next page, so "more with no way to ask for it" is// not a state this tool can be in.if more {ifletSome(last) = page.last() {let id = text(last, "id").unwrap_or_default();let cursor = match text(last, "due_at") {Some(due_at) => TodoCursor::Dated { due_at, id },None => TodoCursor::Undated { created_at: text(last, "created_at").unwrap_or_default(), id, }, }; out.insert("nextCursor".to_string(), Value::from(cursor.encode())); } }let todos: Vec<Value> = page .into_iter() .map(|row| {let due_at = text(&row, "due_at");let id = text(&row, "id").unwrap_or_default();letmut item = Map::new(); item.insert("id".to_string(), Value::from(id.clone())); item.insert("title".to_string(), Value::from(text(&row, "title"))); item.insert("status".to_string(), Value::from(text(&row, "status"))); item.insert("dueAt".to_string(), due_at.clone().map_or(Value::Null, Value::from), ); todo_due_fields(&mut item, due_at.as_deref(), timezone.as_deref()); put(&mut item, "notes", text(&row, "notes").map(Value::from));if int(&row, "priority") > 0 { item.insert("priority".to_string(), Value::from("high")); } put( &mut item,"snoozedUntil", text(&row, "snoozed_until").map(Value::from), ); put( &mut item,"completedAt", text(&row, "completed_at").map(Value::from), );if text(&row, "recurrence_id").is_some() { item.insert("repeating".to_string(), Value::Bool(true)); }// Which projects this todo is in — ALWAYS present, as `[]` when it// is in none. A reader planning a week needs to see the filing// without a second call per todo. item.insert("projects".to_string(),Value::Array( links .slugs .get(&id) .cloned() .unwrap_or_default() .into_iter() .map(Value::from) .collect(), ), );Value::Object(item) }) .collect(); out.insert("todos".to_string(), Value::Array(todos));Ok(Value::Object(out))}// ── update_todo / update_todos ──────────────────────────────────────────────/// The patch a todo change means, for ONE row — the due resolved against that/// row's current day. Everything but the due is row-independent, which is what/// lets the batch verb share it.fn todo_column_patch( ctx: &Ctx<'_>, title: Option<&str>, fields: &TodoPatch, current: &Map<String, Value>, zone: Option<&str>,) -> Valid<Map<String, Value>> {letmut patch = Map::new();ifletSome(title) = title { patch.insert("title".to_string(), Value::from(title)); }ifletSome(notes) = fields.notes.as_ref() { patch.insert("notes".to_string(), notes.clone()); }if fields.due.changes_due() {let next = resolve_due(ctx, text(current, "due_at").as_deref(), &fields.due, zone)?; patch.insert("due_at".to_string(), next.map_or(Value::Null, Value::from)); }ifletSome(priority) = fields.priority.as_deref() { patch.insert("priority".to_string(),Value::from(i64::from(priority == "high")), ); }ifletSome(snoozed) = fields.snoozed_until.as_ref() { patch.insert("snoozed_until".to_string(), snoozed.clone()); }ifletSome(status) = fields.status.as_deref() { patch.insert("status".to_string(), Value::from(status));// The pair moves together: `completed_at` is what "done" MEANS, so// reopening or dropping clears it and completing stamps it. patch.insert("completed_at".to_string(),if status == "done" {Value::from(now_iso(ctx)) } else {Value::Null }, ); }Ok(patch)}/// The zone a due change is placed in, or `None` when the change needs none./// Asked BEFORE any row is read, so a file with no zone refuses the whole call/// rather than half a batch.fn zone_for_change(ctx: &Ctx<'_>, change: &TodoDueChange) -> Valid<Option<String>> {let needs_zone = change.due_at.is_none() && (change.due_date.is_some() || change.due_time.is_some());if needs_zone {Ok(Some(due_zone(ctx, change.timezone.as_deref())?)) } else {Ok(None) }}fn read_todo_rows_query(ids: &[String]) -> Query {Query::on("cotton_todos") .columns(TODO_UPDATE_COLUMNS) .filter(Filter::IsNull("trashed_at".to_string())) .filter(Filter::In("id".to_string(), ids.iter() .map(|id| SqlValue::Text(id.clone())) .collect::<Vec<_>>(), ))}fn read_todo_rows(ctx: &Ctx<'_>, ids: &[String]) -> Valid<Vec<Map<String, Value>>> { rows(ctx, &read_todo_rows_query(ids))}pubfn update_todo(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_update_todo(args)?;let zone = zone_for_change(ctx, &args.patch.due)?;letSome(current) = read_todo_rows(ctx, std::slice::from_ref(&args.id))? .into_iter() .next()else {returnErr(ToolFailure::new(format!("no todo with id {}", args.id))); };let patch = todo_column_patch( ctx, args.title.as_deref(), &args.patch, ¤t, zone.as_deref(), )?; miss_the_earlier_run(ctx, &args.id, &patch)?; update_row(ctx, "cotton_todos", &args.id, patch)?; ctx.commit()?;let read_zone = match zone {Some(zone) => Some(zone),None => workspace_timezone_or_null(ctx)?, };let after = read_todo_rows(ctx, std::slice::from_ref(&args.id))? .into_iter() .next() .ok_or_else(|| ToolFailure::new(format!("no todo with id {}", args.id)))?;Ok(Value::Object(todo_answer(after, read_zone.as_deref())))}// ── the missed run ──────────────────────────────────────────────────────────/// A repeating todo's series and place in it, read only while the series is/// present — a todo whose rule is gone no longer repeats.fn series_of(ctx: &Ctx<'_>, id: &str) -> Valid<Option<(String, String, String)>> {let row = maybe_row( ctx, &Query::on("cotton_todos") .columns(&["status", "recurrence_id", "occurrence_at"]) .eq("id", id.to_string()) .filter(Filter::SoftNames("recurrence_id".to_string())), )?;Ok(row.and_then(|row| {Some(( text(&row, "status")?, text(&row, "recurrence_id")?, text(&row, "occurrence_at")?, )) }))}/// The occurrences of `series` before `at` that hold `status`, by id.fn earlier_in_series(ctx: &Ctx<'_>, series: &str, at: &str, status: &str) -> Valid<Vec<String>> {let query = Query::on("cotton_todos") .columns(&["id"]) .eq("recurrence_id", series.to_string()) .filter(Filter::SoftNames("recurrence_id".to_string())) .filter(Filter::IsNull("trashed_at".to_string())) .eq("status", status.to_string()) .filter(Filter::Lt("occurrence_at".to_string(),SqlValue::Text(at.to_string()), )) .order_by("id", Order::Asc);Ok(rows(ctx, &query)? .iter() .filter_map(|row| text(row, "id")) .collect())}/// One tick clears a repeating todo's missed run. When an occurrence goes/// from open to done, every earlier one of its series still open is MISSED —/// never done, so the history says what really happened — in the same act./// Later ones are untouched, and a todo that does not repeat moves nothing.fn miss_the_earlier_run(ctx: &mutCtx<'_>, id: &str, patch: &Map<String, Value>) -> Valid<()> {if patch.get("status").and_then(Value::as_str) != Some("done") {returnOk(()); }letSome((status, series, at)) = series_of(ctx, id)? else {returnOk(()); };if status != "open" {returnOk(()); }for earlier in earlier_in_series(ctx, &series, &at, "open")? {letmut missed = Map::new(); missed.insert("status".to_string(), Value::from("missed")); missed.insert("completed_at".to_string(), Value::Null); update_row(ctx, "cotton_todos", &earlier, missed)?; }Ok(())}/// What a write to a todo moves beside it ([`cotton_core::records::MISSED`]):/// the earlier occurrences of its series that are missed. A todo that does/// not repeat answers nothing.pubfn missed_beside(ctx: &Ctx<'_>, id: &str) -> Valid<Map<String, Value>> {letmut out = Map::new();ifletSome((_, series, at)) = series_of(ctx, id)? {let missed = earlier_in_series(ctx, &series, &at, "missed")?; out.insert( cotton_core::records::MISSED.to_string(),Value::Array(missed.into_iter().map(Value::from).collect()), ); }Ok(out)}/// The undo of a tick's missed run: each occurrence the tick marked missed/// (in `now`, not in `was`) is open again — the ones still missed, so a/// later hand on one of them is kept.pubfn reopen_the_missed_run(ctx: &mutCtx<'_>, moved: &Value) -> Valid<()> {let ids = |side: &str| -> Vec<String> { moved .get(side) .and_then(Value::as_array) .map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_string).collect()) .unwrap_or_default() };let was = ids("was");let cleared: Vec<String> = ids("now").into_iter().filter(|id| !was.contains(id)).collect();if cleared.is_empty() {returnOk(()); }let still_missed = rows( ctx, &read_todo_rows_query(&cleared).eq("status", "missed".to_string()), )?;for row in still_missed {letSome(id) = text(&row, "id") else { continue };letmut open = Map::new(); open.insert("status".to_string(), Value::from("open")); update_row(ctx, "cotton_todos", &id, open)?; }Ok(())}fn todo_answer(row: Map<String, Value>, zone: Option<&str>) -> Map<String, Value> {let due_at = text(&row, "due_at");letmut out = row; todo_due_fields(&mut out, due_at.as_deref(), zone); out}/// `update_todo` over many ids with one patch.////// Each row resolves the due change against ITS OWN current day, a missing id/// is reported rather than fatal, and a row the resolver refuses is reported by/// id with the sentence — the rest still land.pubfn update_todos(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_update_todos(args)?;let zone = zone_for_change(ctx, &args.patch.due)?;let known = crate::mcp::handlers::common::by_id(read_todo_rows(ctx, &args.ids)?);let read_zone = match zone.clone() {Some(zone) => Some(zone),None => workspace_timezone_or_null(ctx)?, };letmut updated: Vec<Value> = Vec::new();letmut missing: Vec<Value> = Vec::new();letmut refused: Vec<Value> = Vec::new();for id in &args.ids {letSome(current) = known.get(id) else { missing.push(Value::from(id.clone()));continue; };let patch = match todo_column_patch(ctx, None, &args.patch, current, zone.as_deref()) {Ok(patch) => patch,Err(failure) => {letmut entry = Map::new(); entry.insert("id".to_string(), Value::from(id.clone())); entry.insert("reason".to_string(), Value::from(failure.message())); refused.push(Value::Object(entry));continue; } }; miss_the_earlier_run(ctx, id, &patch)?; update_row(ctx, "cotton_todos", id, patch)?; ctx.commit()?;match read_todo_rows(ctx, std::slice::from_ref(id))? .into_iter() .next() {Some(after) => updated.push(Value::Object(todo_answer(after, read_zone.as_deref()))),None => missing.push(Value::from(id.clone())), } }letmut out = Map::new(); out.insert("updated".to_string(), Value::Array(updated));if !missing.is_empty() { out.insert("missing".to_string(), Value::Array(missing)); }if !refused.is_empty() { out.insert("refused".to_string(), Value::Array(refused)); }Ok(Value::Object(out))}