//! The repeating-todo planner. PURE, and the one rule for every producer: //! the phone's foreground pass, `create_todo`'s repeating path and the Worker //! (through the rules module) all ask it. //! //! **The one rule** (Days, 20 Nov 2026: a repeat never stacks): a series has //! ONE live copy, its latest occurrence. While that one is open, ahead of its //! moment or long past it, nothing is owed: left undone, it stays the one row //! (Days draws it on today "from ") until it is done or skipped. Once it //! is finished (done, dropped, missed) the series owes the SINGLE next //! occurrence after now (and after its latest and its mark), so a daily to-do //! done three days late is next due tomorrow. Missed moments are never made //! after the fact. //! //! Before 20 Nov an occurrence that passed open had its next made beside it, //! one late copy per day; [`collapse_stack`] says which of such a stack stays. //! //! A series with no occurrence and no mark owes its first at `dtstart`, then //! the rule above applies to that one. //! //! Idempotency is the `(recurrence_id, occurrence_at)` unique constraint; //! skip-safety is the mark: planning only ever looks PAST it, so a binned //! future occurrence ("skip next") never comes back. The mark never regresses. //! //! Shared vectors: `crates/cotton-rules/vectors/todo_recurrence.json`. use crate::rrule::{next_after_parsed, parse_todo_rule, RruleError}; /// A template, as much of it as the planner reads. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TodoRecurrencePlanInput { /// iCal RRULE. The engine REFUSES an unsupported rule — surface, never /// degrade. pub rrule: String, /// The first occurrence's due instant — the expansion anchor. pub dtstart: i64, /// Newest occurrence ever instantiated; `None` = nothing materialised. pub materialized_until: Option, /// The series' latest occurrence not in the bin, `None` when it has none. pub latest: Option, pub paused: bool, /// The WORKSPACE's IANA zone, in which this rule's wall-clock times are /// read. /// /// REQUIRED, and required is the point. Every producer that can write the /// same occurrence must pass the SAME value, because the row id is derived /// from `occurrence_at`: two zones produce two instants, two ids, no /// unique-constraint conflict, and the person sees every recurring todo /// twice. The phone passes the workspace's zone rather than the device's /// for the same reason — travelling must not fork the series. /// /// It used to default to UTC for the benefit of one legacy caller. Every /// caller passed it anyway, so the default cost nothing and bought nothing /// — except that a FUTURE caller could omit it and re-create the /// duplication bug with no type error and no test failing. pub timezone: String, } /// A series' current occurrence, as much of it as the planner reads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LatestOccurrence { /// Its moment. pub at: i64, /// Done, dropped or missed. pub finished: bool, } /// What the planner decided. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct TodoRecurrencePlan { /// Occurrence instants to instantiate, ascending. Empty = nothing to do. pub occurrences: Vec, /// What `materialized_until` should advance to (the newest planned /// occurrence), or `None` when nothing is planned — the mark then stays /// where it was. pub advance_mark_to: Option, } /// Why a plan could not be made. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum PlanError { /// The TypeScript's sentence, verbatim. #[error("planMaterialization: timezone is required — pass the WORKSPACE's IANA zone (every producer must pass the same one, or the derived occurrence ids diverge)")] TimezoneRequired, /// The todo rule does not read (`parse_todo_rule`'s words). #[error("{0}")] Rule(String), #[error(transparent)] Rrule(#[from] RruleError), } /// Plan the occurrences a series is owed at `now`: none, its next, or (a /// series with nothing made yet) its first at `dtstart` and, when that one has /// already passed, its next. pub fn plan_materialization( template: &TodoRecurrencePlanInput, now: i64, ) -> Result { if template.paused { return Ok(TodoRecurrencePlan::default()); } // No silent default: a producer expanding in another zone mints instants // the others never compute, and every occurrence is then drawn twice. if template.timezone.is_empty() { return Err(PlanError::TimezoneRequired); } let zone = template.timezone.as_str(); // A rule a todo does not keep is refused before anything is owed. let rule = parse_todo_rule(&template.rrule).map_err(PlanError::Rule)?; let mut occurrences = Vec::new(); let latest = match (template.latest, template.materialized_until) { (Some(latest), _) => latest, (None, Some(_)) => LatestOccurrence { at: i64::MIN, finished: true }, (None, None) => { // The first occurrence is the anchor itself. occurrences.push(template.dtstart); LatestOccurrence { at: template.dtstart, finished: false } } }; // An open live copy is owed nothing, however long ago its moment was. if latest.finished { let after = [now, latest.at, template.materialized_until.unwrap_or(i64::MIN)].into_iter().max().unwrap_or(now); if let Some(next) = next_after_parsed(&rule, template.dtstart, after, zone)? { occurrences.push(next); } } let advance_mark_to = occurrences.last().copied(); Ok(TodoRecurrencePlan { occurrences, advance_mark_to }) } /// One open occurrence of a series, as [`collapse_stack`] reads it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OpenOccurrence { pub id: String, /// Its moment (`occurrence_at`). pub at: i64, } /// A stack left by the old rule (one late open copy per missed day): the ids /// to mark `missed`. The NEWEST open occurrence stays the live copy, every /// earlier open one is missed (never done, so the history says what really /// happened), and nothing is deleted. One open occurrence, or none, answers /// nothing: there is no stack. pub fn collapse_stack(open: &[OpenOccurrence]) -> Vec { let Some(newest) = open.iter().max_by(|a, b| a.at.cmp(&b.at).then_with(|| a.id.cmp(&b.id))) else { return Vec::new(); }; let mut missed: Vec<&OpenOccurrence> = open.iter().filter(|one| one.id != newest.id).collect(); missed.sort_by(|a, b| a.at.cmp(&b.at).then_with(|| a.id.cmp(&b.id))); missed.into_iter().map(|one| one.id.clone()).collect() } #[cfg(test)] #[path = "todo_recurrence_tests.rs"] mod tests;