//! `reminders.desired` — what the phone should have scheduled right now. //! //! P14: *"a Swift service that reads the recurrence engine through the FFI //! rather than re-deciding when a thing repeats."* This is that read. The //! decision itself is [`cotton_core::rules::reminders`]; what happens here is //! four queries and one join, and nothing else — the recurrence comes from //! `expand_calendar`, which is the SAME expansion `/calendar` uses. //! //! ## Why a METHOD and not a `read.*` //! //! **A `ScreenRead` must name a route** (`every_read_names_a_screen_that_exists`), //! and this read has no screen. The reminder pass is a SERVICE the app runs — //! on foreground and after a prefs change — and the only notifications route //! the app has, the settings page's Notifications row, is the screen that WRITES the //! preferences, owned by another lane and deferred to it. Naming it here would //! steal that lane's deferral line and claim a screen this read does not serve. //! //! So it stays a method, and that is the settled answer rather than a wait: the //! extensions lane's `Audience` seam gets no `Service` variant, because nothing //! but this would use one (4ij decision, 2026-09-09). A read table whose //! entries are screens is a table that means something; one with a variant for //! "not a screen" is a list. //! //! [`desired`] is still written to [`super::reads::ReadSource::Query`]'s exact //! signature, asserted by `the_answer_function_has_the_read_tables_own_signature` //! — not as a migration path any more, but because that signature is what //! PURITY looks like here: a replica and a map, no clock, no wire, nothing this //! function could reach for and quietly depend on. //! //! ## What the caller passes, and why the prefs are an argument //! //! `{ now?, timeZone, horizonDays?, prefs }`. The preferences are DEVICE-LOCAL //! (`@cotton:notifprefs`, never synced), so the crate must not invent a place //! for a preference the person's file does not hold — they arrive with the //! call. `timeZone` is REQUIRED and a missing one is a refusal: the host runs //! `TZ=UTC` and a guess would put the morning nudge on the wrong morning. //! `now` is optional and defaults to the injected clock, so a test can name an //! instant and a phone need not. The prefs are DELIVERY only — whether this //! device notifies, per category. Nothing asks about mood on a schedule //! (owner, 11 Oct 2026). use serde_json::{json, Map, Value}; use crate::shell::file::ReadFile; use cotton_core::rules::reminders::{ build_desired_set, BirthdayOccurrence, horizon_end, DesiredNotification, DesiredSetInput, EventOccurrence, NotificationPrefs, TodoRow, EVENT_LEAD_MINUTES, HORIZON_DAYS, }; use cotton_core::transforms::rrule::DateRange; use cotton_core::rules::series::{expand_calendar, SeriesRow}; use cotton_core::transforms::zoned_clock::{next_yearly_occurrence, zoned_parts, CivilDate}; use cotton_core::records::page::years_completed; use cotton_store::protocol::js::{parse_date_ms, to_iso_string}; use rusqlite::types::Value as SqlValue; use crate::handle::CottonHandle; use crate::methods::MethodError; use cotton_core::rules::shell_lines::LineRow; /// The longest an event's own alert may lead it by (Cotton Days' sheet: /// a day), which is how far past the gate the expansion reads. pub const MOST_LEAD_MINUTES: i64 = 24 * 60; /// The call, read and defended. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DesiredRequest { pub now_ms: i64, pub timezone: String, pub horizon_days: i64, pub prefs: NotificationPrefs, /// Whether a day-only to-do reminds at 09:00: not in Cotton Days /// (`app_slug` "days"), where a to-do alerts only if it has a time. pub untimed_todos: bool, } /// Read the arguments, or say which one is missing. /// /// `now` is taken from the caller when it names one and from the injected clock /// otherwise — the same shape every banding read uses, so a test can pin an /// instant without the crate ever reaching for a wall clock. `clock_now` is /// `None` where there is no clock to reach (see [`desired`]), and then `now` /// is required rather than defaulted. pub fn read_request( args: &Map, clock_now: Option<&str>, ) -> Result { let named = args .get("now") .and_then(Value::as_str) .filter(|value| !value.is_empty()); let Some(now) = named.or(clock_now) else { return Err( "`now` is the instant this pass is decided at, and this caller reaches no \ clock to default it from" .to_string(), ); }; let Some(now_ms) = parse_date_ms(now) else { return Err(format!("`now` is not an instant: {now:?}")); }; let Some(timezone) = args .get("timeZone") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) else { return Err( "`timeZone` is the IANA zone every local-hour decision is made in, and this core \ never guesses one" .to_string(), ); }; // ABSENT takes the engine's own fourteen; PRESENT is passed through, and a // present-but-impossible one is a REFUSAL rather than a fallback. // // The TypeScript passes `-1` straight through and produces an empty set, // and the earlier shape here clamped it back to fourteen — so a caller that // asked to schedule NOTHING got a fortnight, silently. That is the exact // shape of the fallback this file's zone rule exists to forbid, one field // away from it. A horizon of zero is legal and means today only. let horizon_days = match args.get("horizonDays") { None | Some(Value::Null) => HORIZON_DAYS, Some(value) => { let days = value.as_i64().ok_or_else(|| { "`horizonDays` is a whole number of days, or absent for the default fourteen" .to_string() })?; if !(0..=365).contains(&days) { return Err(format!( "`horizonDays` is {days}, which is not a window this can schedule: a \ negative horizon is not a window at all, and more than a year is a pass \ nobody asked for. Send 0 for today only, or leave it out for {HORIZON_DAYS}." )); } days } }; // THE ZONE IS CHECKED HERE, where it is an ARGUMENT. `answer` refuses an // unknown zone too — it has to, it is the one that does the arithmetic — // but its single error type reaches `call` as `unreadable`, which would // send a Swift caller looking at the database over its own typo. Resolving // it once at the edge makes the refusal a `bad_request` with the zone // named, and leaves the deeper refusal as the unreachable backstop it // should be. zoned_parts(now_ms, timezone).map_err(|error| error.to_string())?; Ok(DesiredRequest { now_ms, timezone: timezone.to_string(), horizon_days, prefs: cotton_core::rules::reminders::migrate_notification_prefs( args.get("prefs").unwrap_or(&Value::Null), ), untimed_todos: true, }) } fn workspace(replica: &ReadFile<'_>) -> SqlValue { SqlValue::Text(replica.workspace_id.to_string()) } /// Every todo that could possibly fire — every one with a due date. /// /// The `due_at IS NOT NULL` narrowing is not a rule, it is the absence of a /// row: a todo with no due date has no instant to schedule against, and /// `todo_fire_at` answers `None` for it anyway. The STATUS filter is the rule, /// and it deliberately is not here — it lives in the engine (`todo_fire_at` /// refuses anything that is not `open`), so a `WHERE status = 'open'` in this /// query would be the same rule in two places and the copy without the tests. fn todos(replica: &ReadFile<'_>) -> Result, String> { let rows = replica .driver .all( "SELECT id, title, status, due_at, snoozed_until FROM cotton_todos WHERE workspace_id = ? AND trashed_at IS NULL AND due_at IS NOT NULL", &[workspace(replica)], ) .map_err(|error| error.to_string())?; Ok(rows .iter() .map(|row| TodoRow { id: row.text("id").unwrap_or_default().to_string(), title: row.text("title").unwrap_or_default().to_string(), status: row.text("status").unwrap_or_default().to_string(), due_at: row.text("due_at").map(str::to_string), snoozed_until: row.text("snoozed_until").map(str::to_string), }) .collect()) } /// The occurrences inside the window, expanded by the engine that owns /// recurrence, then joined back to the two columns the reminder decision needs. /// /// The join is what the TypeScript's `EventOccurrence` carries for free: /// `expand_calendar` answers WHEN, and `all_day` / `my_response` live on the /// row. An occurrence whose row cannot be found is dropped — that is an /// exception whose master went missing mid-read, and inventing an event for it /// would put a reminder on the lock screen for a row nobody can open. fn occurrences( replica: &ReadFile<'_>, range: DateRange, timezone: &str, ) -> Result, String> { // The event's own alert (a kit column Cotton Days keeps on the copy). let alert = if replica .driver .all("SELECT name FROM pragma_table_info('cotton_events') WHERE name = 'alert'", &[]) .map_err(|error| error.to_string())? .is_empty() { "NULL AS alert" } else { "alert" }; let rows = replica .driver .all( // NO WORKSPACE FILTER, and its absence is the schema's: `cotton_events` // carries no `workspace_id` column — a calendar belongs to its // collection and the file belongs to one person. Adding a predicate // on a column that does not exist would be an SQL error; adding one // on `collection_id` would be a filter nobody asked for. &format!( "SELECT id, title, starts_at, ends_at, all_day, rrule, exdates, series_id, original_starts_at, trashed_at, my_response, {alert} FROM cotton_events" ), &[], ) .map_err(|error| error.to_string())?; let leads: std::collections::HashMap<&str, i64> = rows .iter() .filter_map(|row| Some((row.text("id")?, row.int("alert")?))) .collect(); let mut facts: std::collections::HashMap<&str, (&str, bool, Option<&str>)> = std::collections::HashMap::with_capacity(rows.len()); let mut series: Vec = Vec::with_capacity(rows.len()); for row in &rows { let Some(id) = row.text("id") else { continue }; facts.insert( id, ( row.text("title").unwrap_or_default(), row.int("all_day").unwrap_or_default() != 0, row.text("my_response"), ), ); series.push(SeriesRow { id: id.to_string(), starts_at: row.text("starts_at").unwrap_or_default().to_string(), ends_at: row.text("ends_at").map(str::to_string), rrule: row.text("rrule").map(str::to_string), exdates: row .text("exdates") .and_then(|raw| serde_json::from_str::>(raw).ok()), series_id: row.text("series_id").map(str::to_string), original_starts_at: row.text("original_starts_at").map(str::to_string), trashed_at: row.text("trashed_at").map(str::to_string), }); } let expanded = expand_calendar(&series, range, timezone).map_err(|error| error.to_string())?; Ok(expanded .into_iter() .filter_map(|occurrence| { let (title, all_day, my_response) = facts.get(occurrence.event_id.as_str())?; Some(EventOccurrence { event_id: occurrence.event_id.clone(), title: (*title).to_string(), starts_at: occurrence.starts_at, all_day: *all_day, my_response: my_response.map(|value| value.to_string()), lead_minutes: leads .get(occurrence.event_id.as_str()) .or_else(|| occurrence.series_id.as_deref().and_then(|id| leads.get(id))) .copied(), }) }) .collect()) } /// Every birthday coming round inside `[today, today + horizon_days]`, /// soonest first, ties by name: each person's yearly date through /// [`next_yearly_occurrence`] (today counts; 29 February keeps the 28th in a /// common year) and the age it completes through [`years_completed`]. /// /// An archived person is skipped: they are out of the directory, and a /// notification naming them would be the one place they came back. /// /// A person's birthday is `cotton_core::rules::people::birthday`'s one rule: /// the phone's own month and day where set, else the date a signed-in copy /// keeps whole from the object — the same answer the views narrow by. fn birthdays( replica: &ReadFile<'_>, today: CivilDate, horizon_days: i64, ) -> Result, String> { use cotton_core::rules::people::birthday::{birthday_sql, columns_sql, whole_held, Birthday, PEOPLE_TABLE}; let held = whole_held(replica.driver).map_err(|error| error.to_string())?; let rows = replica .driver .all( &format!( "SELECT id, full_name, {} FROM cotton_people WHERE workspace_id = ? AND archived_at IS NULL AND {} IS NOT NULL", columns_sql(PEOPLE_TABLE, held), birthday_sql(PEOPLE_TABLE, held) ), &[workspace(replica)], ) .map_err(|error| error.to_string())?; let from = today.day_number(); let mut out: Vec = rows .iter() .filter_map(|row| { let Birthday { month, day, year } = Birthday::of_row(row)?; let on = CivilDate::from(next_yearly_occurrence(month, day, today.tuple())); (on.day_number() - from <= horizon_days).then(|| BirthdayOccurrence { person_id: row.text("id").unwrap_or_default().to_string(), name: row.text("full_name").unwrap_or_default().to_string(), on, turning: year.and_then(|year| years_completed((year, month, day), on.tuple())), }) }) .filter(|occurrence| !occurrence.person_id.is_empty()) .collect(); cotton_core::js_text::sort_by_name(&mut out, |b| b.name.clone(), |b| b.person_id.clone()); out.sort_by_key(|occurrence| occurrence.on.day_number()); Ok(out) } /// One desired notification, on the wire. fn painted(notification: &DesiredNotification, lines: &[LineRow]) -> Value { json!({ "identifier": notification.identifier, "kind": notification.kind.as_str(), "recordId": notification.record_id, // ISO, because a scheduler takes a date and an epoch integer crossing // the boundary as a JSON number would lose precision above 2^53 — // which this never reaches, and is exactly the kind of "never reaches" // that stops being true. "at": to_iso_string(notification.at_ms), "title": notification.title.say(lines), "body": notification.body.map(|body| body.say(lines)), }) } /// THE PASS, in [`super::reads::ReadSource::Query`]'s signature. /// /// Written to that signature deliberately — see the module header: it is what /// purity looks like here, a replica and a map and nothing reachable besides. pub fn desired(replica: &ReadFile<'_>, args: &Map) -> Result { // NO CLOCK HERE, and that is the signature's doing rather than an omission: // a `Query` sees a replica and a map and nothing else, so `now` must be an // argument. Every caller from the boundary goes through [`call`], which // defaults it from the injected clock; this entry point is the one a test // uses to pin an instant, and the one that proves nothing here reads a // wall clock. let request = read_request(args, None)?; answer(replica, &request) } /// The pass itself, over a request already read. pub fn answer(replica: &ReadFile<'_>, request: &DesiredRequest) -> Result { let desired = desired_set(replica, request)?; let lines = cotton_tools::presentation::line_rows(replica.driver, replica.workspace_id); Ok(json!({ "reminders": desired.iter().map(|notification| painted(notification, &lines)).collect::>(), "count": desired.len(), // What the pass was decided against, echoed back. A scheduler that // reconciled against a horizon it did not ask for would cancel // everything past the one it thought it had. "horizonDays": request.horizon_days, "timeZone": request.timezone, "now": to_iso_string(request.now_ms), })) } /// The desired set itself, before anything paints it. /// /// Split out from [`answer`] for [`reconcile_call`], which needs the ROWS and /// not their JSON — the diff is over `DesiredNotification`s and painting them /// only to read the identifiers back out would be a second shape of the same /// data with two chances to disagree. fn desired_set( replica: &ReadFile<'_>, request: &DesiredRequest, ) -> Result, String> { let today = zoned_parts(request.now_ms, &request.timezone).map_err(|error| error.to_string())?; let today = CivilDate { year: today.year, month: today.month, day: today.day, }; // The occurrence window is the reminder window, and it is the ENGINE's // window rather than a second one computed here: `horizon_end` is public // for exactly this caller. The engine's gate is `(now, horizon_end]` in // CALENDAR days, so `now + horizon_days * 86_400_000` would land an hour // early across a spring-forward — an event whose ten-minute mark fell in // that hour would never be expanded and never reminded, twice a year, at // the far edge of a fortnight. Expanding beyond the gate would instead be // work whose every row the gate throws away. let range = DateRange { from: request.now_ms, // The gate's own end, plus the LEAD TIME — a SUPERSET of what the gate // accepts, never an independent guess. An event's fire instant is // `starts - EVENT_LEAD_MINUTES`, so an event STARTING up to ten // minutes past `horizon_end` still has a reminder inside the window; // expanding only to `horizon_end` would drop it. Over-fetching is what // the TypeScript does too (`queries.ts` runs to the end of the last // calendar day) and it is free: every row past the gate is discarded // by the gate. to: horizon_end(request.now_ms, request.horizon_days, &request.timezone) .map_err(|error| error.to_string())? + EVENT_LEAD_MINUTES.max(MOST_LEAD_MINUTES) * 60_000, }; let todos = todos(replica)?; let occurrences = occurrences(replica, range, &request.timezone)?; let birthdays = birthdays(replica, today, request.horizon_days)?; build_desired_set(&DesiredSetInput { todos: &todos, occurrences: &occurrences, birthdays: &birthdays, prefs: &request.prefs, now_ms: request.now_ms, timezone: &request.timezone, horizon_days: request.horizon_days, untimed_todos: request.untimed_todos, }) .map_err(|error| error.to_string()) } /// A pass that names no `prefs` is decided by this device's own /// (`device_preferences`): a platform that keeps no copy of its own (Android) /// hands none, and the file the device page writes is the one it obeys. fn own_prefs(client: &crate::shell::client::ClientController, args: &Map, mut read: DesiredRequest) -> Result { if args.get("prefs").is_none_or(Value::is_null) { read.prefs = super::device_preferences::prefs(client)?; } Ok(read) } /// `reminders.desired` — the method, and a method for good (see the header). pub fn call(handle: &CottonHandle, request: &Value) -> Result { let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_default(); let client = handle.client(); let now = client.now_iso(); let mut read = own_prefs(&client, &args, read_request(&args, Some(&now)) .map_err(|reason| MethodError::new("bad_request", reason))?)?; // Cotton Days: a to-do with only a day never alerts (DECISIONS.md). read.untimed_todos = handle.app_slug() != "days"; client .with_file(|replica| answer(replica, &read)) .map_err(|reason| MethodError::new("unreadable", reason)) } /// The identifiers iOS is holding, out of a `reconcile` call. /// /// `held` is `getPendingNotificationRequests`' answer, verbatim and unfiltered /// — FOREIGN identifiers included. Filtering them on the Swift side would be /// the one rule of this diff that is not set arithmetic living in the half that /// cannot be tested on Linux; [`cotton_core::rules::reminders::reconcile`] /// already leaves anything without the `cotton:` prefix alone, and it is the /// only place that decision should exist. fn held_identifiers(args: &Map) -> Vec { args.get("held") .and_then(Value::as_array) .map(|held| { held.iter() .filter_map(Value::as_str) .map(str::to_string) .collect() }) .unwrap_or_default() } /// `reminders.reconcile` — the desired set, diffed against what iOS holds. /// /// **A SECOND METHOD rather than a flag on `reminders.desired`**, because the /// two answers are different questions with different callers: the scheduler /// asks this one and applies both lists; anything that wants to SHOW what is /// coming asks for the desired set and has no `held` to give. /// /// The diff itself is [`cotton_core::rules::reminders::reconcile`] — a pure /// set difference over identifiers that already encode the fire instant, so /// "already correct" is set membership and nothing is compared field by field. /// It was ported, tested and unreachable until the landing review; this is the /// method that reaches it, and it exists so the Swift half APPLIES a plan /// rather than re-implementing one. Two implementations of "which reminders /// change" would eventually disagree, and a disagreement there is a person /// whose reminder fires twice or not at all. pub fn reconcile_call(handle: &CottonHandle, request: &Value) -> Result { let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_default(); let client = handle.client(); let now = client.now_iso(); let mut read = own_prefs(&client, &args, read_request(&args, Some(&now)) .map_err(|reason| MethodError::new("bad_request", reason))?)?; // Cotton Days: a to-do with only a day never alerts (DECISIONS.md), in the pass that schedules as in `desired`. read.untimed_todos = handle.app_slug() != "days"; let held = held_identifiers(&args); let (desired, lines) = client .with_file(|replica| { Ok(( desired_set(replica, &read)?, cotton_tools::presentation::line_rows(replica.driver, replica.workspace_id), )) }) .map_err(|reason| MethodError::new("unreadable", reason))?; let plan = cotton_core::rules::reminders::reconcile(&desired, &held); Ok(json!({ // The FULL rows, not the identifiers: the Swift side has to build a // `UNNotificationRequest` out of each, and asking it to look them up in // a second answer would be two calls whose results could disagree. "schedule": plan.to_schedule.iter().map(|notification| painted(notification, &lines)).collect::>(), // Identifiers only — `removePendingNotificationRequests` takes names. "cancel": plan.to_cancel, // The common case, every tick. A caller that trusts this can skip two // `UNUserNotificationCenter` calls. "noop": cotton_core::rules::reminders::is_noop(&plan), "timeZone": read.timezone, "now": to_iso_string(read.now_ms), })) } #[cfg(test)] #[path = "reminders_tests.rs"] mod tests;