//! Two pieces of `packages/server/src/mcp/` that are neither a tool nor a pure//! engine, ported here because their permanent home does not exist yet.//!//! MATERIALIZE_TEMPLATE is `packages/server/src/mcp/recurrence.ts`. It is the//! ONE place a recurring-todo template becomes `cotton_todos` rows, and it has//! TWO callers in the TypeScript: `create_todo` with an rrule (here) and the//! hourly recurrence worker (step 2e). It belongs at//! `crates/cotton-server/src/recurrence.rs` the moment that worker lands —//! MOVE IT THERE rather than writing a second copy, because two implementations//! of "which occurrences exist" is exactly the disagreement the TypeScript's//! own comment says this function exists to prevent. The DECISION is already in//! `cotton_core::rules::todo_recurrence::plan_materialization`; this half only//! touches the database.use cotton_core::rules::todo_recurrence::{plan_materialization, LatestOccurrence, TodoRecurrencePlanInput};use cotton_store::protocol::derived_id::recurrence_occurrence_id;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{ insert_row, iso_of_ms, maybe_row, now_ms, parse_ms, rows, text, update_row,};usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Order, Query};/// A `cotton_todo_recurrences` row, as the planner wants it.#[derive(Debug, Clone)]pubstructRecurrenceTemplate {pub id: String,pub workspace_id: String,pub title: String,pub notes: Option<String>,pub priority: i64,pub rrule: String,pub dtstart: String,pub paused: bool,pub materialized_until: Option<String>,}/// The columns a template is read with — `RECURRENCE_TEMPLATE_COLUMNS`.pubconst RECURRENCE_TEMPLATE_COLUMNS: &[&str] = &["id","workspace_id","title","notes","priority","rrule","dtstart","paused","materialized_until",];implRecurrenceTemplate {pubfn of(row: &Map<String, Value>) -> RecurrenceTemplate {usecrate::mcp::handlers::common::{flag, int};RecurrenceTemplate { id: text(row, "id").unwrap_or_default(), workspace_id: text(row, "workspace_id").unwrap_or_default(), title: text(row, "title").unwrap_or_default(), notes: text(row, "notes"), priority: int(row, "priority"), rrule: text(row, "rrule").unwrap_or_default(), dtstart: text(row, "dtstart").unwrap_or_default(), paused: flag(row, "paused"), materialized_until: text(row, "materialized_until"), } }}/// Give one template what the planner says it is owed: write the instances and/// advance the mark, guarded so it never regresses. Answers how many rows were/// actually WRITTEN — not how many the plan named.////// The difference is the whole answer of a foreground pass over templates that/// are already up to date: `materializeTemplate` returns the rows inserted/// after the skip (`todoRecurrences.service.ts:517`), so such a pass answers/// `0`. Returning `plan.occurrences.len()` is the SERVER worker's number/// (`packages/server/src/mcp/recurrence.ts:124`), and reporting it here made/// every launch claim it had created todos it had only re-found.////// The occurrence id is DERIVED, never minted, for the reason the TypeScript/// spells out: the phone's own pass computes the same occurrence from the same/// rule, and two independently-minted ids for one logical occurrence are two/// INSERTs, the second of which trips `UNIQUE (recurrence_id, occurrence_at)`/// and wedges the push. Derived, both sides write the same row and the second/// write is the last-write-wins no-op it is described as.pubfn materialize_template( ctx: &mutCtx<'_>, template: &RecurrenceTemplate, timezone: &str,) -> Result<usize, ToolFailure> {let dtstart = parse_ms(&template.dtstart) .ok_or_else(|| ToolFailure::new("this template's first occurrence is not an instant"))?; collapse_open_stack(ctx, &template.id)?;// The series' current occurrence: its latest one not in the bin.let latest = maybe_row( ctx, &Query::on("cotton_todos") .columns(&["status", "occurrence_at"]) .eq("recurrence_id", template.id.clone()) .filter(Filter::IsNull("trashed_at".to_string())) .filter(Filter::NotNull("occurrence_at".to_string())) .order_by("occurrence_at", Order::Desc) .limit(1), )? .and_then(|row| {let at = parse_ms(&text(&row, "occurrence_at")?)?;let finished = matches!(text(&row, "status").as_deref(), Some("done" | "dropped" | "missed"));Some(LatestOccurrence { at, finished }) });let plan = plan_materialization( &TodoRecurrencePlanInput { rrule: template.rrule.clone(), dtstart, materialized_until: template.materialized_until.as_deref().and_then(parse_ms), latest, paused: template.paused, timezone: timezone.to_string(), }, now_ms(ctx), ) .map_err(|error| ToolFailure::new(error.to_string()))?;letSome(advance_mark_to) = plan.advance_mark_to else {returnOk(0); };if plan.occurrences.is_empty() {returnOk(0); }// The person's mark goes on with the series: the next copy wears the// last marked one's (Cotton Days), where this file keeps the column.let mark = carried_mark(ctx, &template.id)?;letmut written = 0usize;for occurrence in &plan.occurrences {let occurrence_at = iso_of_ms(*occurrence);let id = recurrence_occurrence_id(&template.id, &occurrence_at);// `ignoreDuplicates` in the TypeScript: an occurrence that is already// there must not be restamped. A read-then-skip is the same rule.//// ASKED BY THE NATURAL KEY, not by the derived id, which is what both// TypeScript twins do — `recurrence_id = ? AND occurrence_at = ?`// (`todoRecurrences.service.ts:465-469`) and the server's// `onConflict: "recurrence_id,occurrence_at"`. That is the pair// `UNIQUE (recurrence_id, occurrence_at)` actually guards, and a row// standing on a planned instant under a NON-derived id — the anchor// todo `make_todo_recurring` writes, or the kept-and-moved instance// `update_todo_recurrence` leaves — is invisible to a lookup by id and// would trip that index on the insert.let claimed = maybe_row( ctx, &Query::on("cotton_todos") .columns(&["id"]) .eq("recurrence_id", template.id.clone()) .eq("occurrence_at", occurrence_at.clone()), )?;if claimed.is_some() {continue; }letmut patch = Map::new(); patch.insert("workspace_id".to_string(),Value::from(template.workspace_id.clone()), ); patch.insert("title".to_string(), Value::from(template.title.clone())); patch.insert("notes".to_string(), template.notes.clone().map_or(Value::Null, Value::from), ); patch.insert("priority".to_string(), Value::from(template.priority)); patch.insert("recurrence_id".to_string(),Value::from(template.id.clone()), ); patch.insert("occurrence_at".to_string(),Value::from(occurrence_at.clone()), ); patch.insert("due_at".to_string(), Value::from(occurrence_at));ifletSome(mark) = &mark { patch.insert("mark".to_string(), Value::from(mark.clone())); } insert_row(ctx, "cotton_todos", &id, patch)?; written += 1; } ctx.commit()?;// The mark must never go BACKWARDS — two passes can overlap, and a// regressing mark would make the next pass re-plan occurrences that are// already there. Read-then-compare rather than one guarded statement,// exactly as the TypeScript does it.let mark_iso = iso_of_ms(advance_mark_to);let current = maybe_row( ctx, &Query::on("cotton_todo_recurrences") .columns(&["materialized_until"]) .eq("id", template.id.clone()), )? .and_then(|row| text(&row, "materialized_until"));if current.is_none_or(|mark| mark < mark_iso) {letmut patch = Map::new(); patch.insert("materialized_until".to_string(), Value::from(mark_iso)); update_row(ctx, "cotton_todo_recurrences", &template.id, patch)?; ctx.commit()?; }Ok(written)}/// A stack the old rule left (one late open copy per missed day) collapses/// to its newest open occurrence: every earlier open one is `missed`, in this/// write, and nothing is deleted (`cotton_core::rules::todo_recurrence::collapse_stack`)./// Answers how many were marked; a series with one open copy marks none.pubfn collapse_open_stack(ctx: &mutCtx<'_>, series: &str) -> Result<usize, ToolFailure> {use cotton_core::rules::todo_recurrence::{collapse_stack, OpenOccurrence};let open: Vec<OpenOccurrence> = rows( ctx, &Query::on("cotton_todos") .columns(&["id", "occurrence_at"]) .eq("recurrence_id", series.to_string()) .eq("status", "open".to_string()) .filter(Filter::IsNull("trashed_at".to_string())) .filter(Filter::NotNull("occurrence_at".to_string())), )? .iter() .filter_map(|row| Some(OpenOccurrence { id: text(row, "id")?, at: parse_ms(&text(row, "occurrence_at")?)? })) .collect();let missed = collapse_stack(&open);for id in &missed {letmut patch = Map::new(); patch.insert("status".to_string(), Value::from("missed")); patch.insert("completed_at".to_string(), Value::Null); update_row(ctx, "cotton_todos", id, patch)?; }if !missed.is_empty() { ctx.commit()?; }Ok(missed.len())}/// The mark of a series' latest marked occurrence, where this file keeps a/// `mark` column on `cotton_todos` (a copy keeps it from its open; a file/// without it carries nothing).fn carried_mark(ctx: &Ctx<'_>, series: &str) -> Result<Option<String>, ToolFailure> {let db = ctx.read.driver();let kept = db .all("SELECT name FROM pragma_table_info('cotton_todos') WHERE name = 'mark'", &[]) .map_err(|error| ToolFailure::new(error.to_string()))?;if kept.is_empty() {returnOk(None); }Ok(db .get("SELECT mark FROM cotton_todos WHERE recurrence_id = ? AND mark IS NOT NULL AND trashed_at IS NULL ORDER BY occurrence_at DESC LIMIT 1", &[rusqlite::types::Value::Text(series.to_string())], ) .map_err(|error| ToolFailure::new(error.to_string()))? .and_then(|row| row.text("mark").map(str::to_string)))}