//! THE LOCAL REMINDER ENGINE — what notifications SHOULD exist right now, what//! each one is NAMED, and the diff between that and what the OS is holding.//!//! The port of `apps/cotton/src/notifications/{types,prefs,copy,identifiers,//! reconcile,desiredSet}.ts`, which are the pure half of the eleven-file//! TypeScript engine. The other half — `scheduler.ts`, `pass.ts`,//! `useNotificationEngine.ts` — is the part that talks to iOS, and it stays in//! Swift because there is nothing else it could be.//!//! **Cotton REMINDS from LOCAL scheduled notifications only** (ratified//! 2026-08-11, unchanged by the 2026-08-14 return of push). No server, no push//! worker, no row anywhere: *"everything Cotton reminds about already lives on//! the device that would be reminded, so a round trip through a database, a//! push worker and APNs would add three failure modes to deliver a fact the//! phone already holds."* The consequence, and it is the accepted trade://! **nothing here survives an uninstall or reaches a second device.**//!//! The rules, in one place://!//! - **A todo with a due instant reminds once.** Timed (the record states an//! hour) → at that hour. Date-only → 09:00 that morning. "Date-only" is the//! app's existing convention and [`crate::transforms::moment_split`] is the one//! place that decides it, so a notification cannot disagree with the row//! that produced it.//! - **A todo that is not open never reminds**, and neither does one **snoozed//! past the moment it would fire** — snoozing is a person saying "not until//! then", and a reminder inside the snooze is the app arguing with them.//! - **A day-only todo stays quiet in Cotton Days** (`untimed_todos` false)://! there a to-do alerts only if it was given a time.//! - **An event reminds ten minutes before it starts**, or at its own//! `alert` minutes before; an `alert` of [`NO_ALERT`] (the person chose//! "No alert") never reminds, while no `alert` at all keeps the ten//! minutes. All-day events carry//! no hour to be ten minutes before, so they are skipped; so is anything//! already declined.//! - **A birthday reminds at 09:00** on its day, naming the age when the year//! is known. The caller resolves the days from any yearly date with//! [`crate::transforms::zoned_clock::next_yearly_occurrence`].//! - **Nothing in the past, nothing past the horizon.** The window is//! `(now, now + horizon_days]`; a fire instant already gone is not a//! reminder, it is a notification arriving late.//!//! **Every local-hour decision takes an explicit IANA zone.** The TypeScript//! reads the device's own clock through `Date`; the host this crate also runs//! on is `TZ=UTC` by deploy-time assertion, so guessing here would put a//! check-in on tomorrow and a reminder on the wrong morning. The zone is an//! argument and a bad one is a refusal, never a fallback.//!//! The output is sorted (instant, then identifier) so a test can assert a list//! rather than a set, and two runs a millisecond apart produce byte-identical//! plans.usesuper::shell_lines::{resolve, LineRow};use std::collections::{BTreeMap, BTreeSet};use serde_json::Value;use cotton_store::protocol::js::parse_date_ms;usecrate::transforms::moment_split::{states_clock_time, MomentSplitError};usecrate::transforms::zoned_clock::{ civil_from_days, instant_from_zoned, CivilDate, zoned_parts, ZoneError, ZonedParts,};/// How far ahead the engine schedules. iOS caps a bundle at 64 pending.pubconst HORIZON_DAYS: i64 = 14;/// THE COUNT CEILING — how many notifications one pass may leave standing.////// **iOS holds 64 pending requests per BUNDLE and drops the rest SILENTLY.**/// The horizon alone does not bound the count: a fortnight with a due todo an/// hour and a full calendar is easily past sixty, and what `UNUserNotification\/// Center` does then is accept `add` and never fire — *which* requests survive/// is undefined, so the one that goes can be the reminder ten minutes from now./// A horizon is a statement about relevance; this is the statement about the/// queue, and they are two different facts.////// **48 and not 64**, for two reasons that both cost nothing until they don't:/// the 64 is shared with everything else the bundle schedules — `/alarms` puts/// AlarmKit requests on the same queue, and anything scheduled by hand lands/// there too — and [`reconcile`] cancels AFTER the OS has been asked to add, so/// a pass that filled the queue exactly would fail the last additions of the/// very pass that was about to make room. Sixteen of headroom is the margin.////// The set is sorted by firing instant before it is cut, so what a full queue/// loses is always the FURTHEST OUT — a birthday a fortnight away rather than/// the meeting this afternoon. That is the whole point of capping here instead/// of letting iOS choose.pubconst PENDING_BUDGET: usize = 48;/// The morning hour a day-shaped reminder lands on.pubconst MORNING_HOUR: i64 = 9;/// How long before an event starts its reminder fires when the event names/// no alert of its own (`event.alert` empty).pubconst EVENT_LEAD_MINUTES: i64 = 10;/// The `event.alert` a person's "No alert" stores: no reminder for it at all.////// A VALUE IN THE ONE COLUMN, not a second column, so an event's alert can never/// say two things at once (minutes in one column, "off" in another), and an/// exception of a repeating event inherits its series' "No alert" through the/// same fallback that carries the series' minutes. Empty stays what it always/// was, the ten-minute default, so every event stored before this keeps/// reminding as it did. Any value below zero reads as no alert; Days writes -1.pubconst NO_ALERT: i64 = -1;/// How long before an event its reminder fires, from its stored `alert`:/// `None` when the person chose no alert ([`NO_ALERT`]), the ten minutes when/// it names none.pubfn event_lead(alert: Option<i64>) -> Option<i64> {match alert {Some(minutes) if minutes < 0 => None,Some(minutes) => Some(minutes),None => Some(EVENT_LEAD_MINUTES), }}/// The storage key the device-local preferences live under, fixed by the spec.////// Restated here rather than owned here: the prefs are DEVICE-LOCAL and never/// synced, so this crate never reads or writes them — they arrive as an/// argument. The constant is carried so the one key has one spelling on both/// sides of the boundary.pubconst NOTIF_PREFS_KEY: &str = "@cotton:notifprefs";/// Every identifier this app owns starts here. Nothing else is ever cancelled.pubconst IDENTIFIER_PREFIX: &str = "cotton";// ── the vocabulary ────────────────────────────────────────────────────────/// What a scheduled notification is ABOUT — one kind per record type.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]pubenumNotificationKind {Todo,Event,Birthday,Alarm,}/// What a person can switch off, one line at a time.////// `Alarms` is the alarm-mirror category. Its toggle exists here even though/// `/alarms` is another lane's subsystem, so the engine's pref shape does not/// change under it later.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]pubenumNotificationCategory {Reminders,Events,Birthdays,Alarms,}/// The four kinds. There is no mood kind: Cotton never asks how you are on a/// schedule (owner, 11 Oct 2026) — a mood is recorded when the person chooses.pubconst NOTIFICATION_KINDS: [NotificationKind; 4] = [NotificationKind::Todo,NotificationKind::Event,NotificationKind::Birthday,NotificationKind::Alarm,];/// The four categories.pubconst NOTIFICATION_CATEGORIES: [NotificationCategory; 4] = [NotificationCategory::Reminders,NotificationCategory::Events,NotificationCategory::Birthdays,NotificationCategory::Alarms,];implNotificationKind {pubfn as_str(self) -> &'static str {matchself {NotificationKind::Todo => "todo",NotificationKind::Event => "event",NotificationKind::Birthday => "birthday",NotificationKind::Alarm => "alarm", } }pubfn parse(value: &str) -> Option<NotificationKind> { NOTIFICATION_KINDS .into_iter() .find(|kind| kind.as_str() == value) }/// Which switch governs this kind. A `match` and not a map, so a new kind/// is a COMPILE error rather than a kind that quietly goes ungoverned —/// which is what the TypeScript's `Record<NotificationKind, …>` buys there.pubfn category(self) -> NotificationCategory {matchself {NotificationKind::Todo => NotificationCategory::Reminders,NotificationKind::Event => NotificationCategory::Events,NotificationKind::Birthday => NotificationCategory::Birthdays,NotificationKind::Alarm => NotificationCategory::Alarms, } }}implNotificationCategory {pubfn as_str(self) -> &'static str {matchself {NotificationCategory::Reminders => "reminders",NotificationCategory::Events => "events",NotificationCategory::Birthdays => "birthdays",NotificationCategory::Alarms => "alarms", } }}// ── the switches ──────────────────────────────────────────────────────────/// The person's switches, as the device holds them.////// DEVICE-LOCAL and never synced (`@cotton:notifprefs`), which is why this/// crate takes them as an ARGUMENT and never looks for a place to keep them:/// inventing a home for a preference the person's file does not hold would be/// this engine deciding something the app already decided.////// Everything defaults ON, which is not the same as "notifications default on":/// nothing can be scheduled until the OS grants permission, and Cotton never/// asks for that at boot. So these switches describe what a person would want/// IF they said yes, and the OS prompt is the real gate.////// `asked_at` shares the record because it is the same question's other half:/// "have we ever asked?" travels with "what did they say?".#[derive(Debug, Clone, PartialEq, Eq)]pubstructNotificationPrefs {/// The master switch. Off means the engine schedules nothing at all.pub enabled: bool,/// One flag per [`NotificationCategory`], TOTAL.pub categories: BTreeMap<NotificationCategory, bool>,/// ISO instant of the ONE inline permission ask, or `None` if never asked.pub asked_at: Option<String>,}implDefaultforNotificationPrefs {/// All on: every category reminds about something the person already made/// — a todo they wrote, an event they accepted, a birthday they kept.fn default() -> Self {NotificationPrefs { enabled: true, categories: NOTIFICATION_CATEGORIES .into_iter() .map(|category| (category, true)) .collect(), asked_at: None, } }}implNotificationPrefs {/// Is this kind switched on right now? Master AND its own category.pubfn kind_enabled(&self, kind: NotificationKind) -> bool {self.enabled && self.category_enabled(kind.category()) }/// A category's flag. **A MISSING KEY IS OFF**, which is `kindEnabled`'s own/// rule — `prefs.categories[CATEGORY_FOR_KIND[kind]] === true`, where a/// hole is `undefined` and `undefined === true` is false.////// The map is held total by [`migrate_notification_prefs`], so in practice/// there is no hole; the question is which way this fails if there ever is/// one. Defaulting to on here would/// SCHEDULE against a preference record that does not say to — a person/// who turned a category off and whose stored map then lost the key would/// start being reminded again, silently. Failing closed costs a reminder/// nobody asked for; failing open sends one somebody declined.pubfn category_enabled(&self, category: NotificationCategory) -> bool {self.categories.get(&category).copied().unwrap_or(false) }}/// The ONE entry point stored preferences come in through.////// Anything malformed, partial or from an older shape resolves to the defaults/// for the parts it cannot supply. A category added later takes the DEFAULT for/// someone whose stored record predates it, exactly as a fresh install gets it.////// It is deliberately suspicious of TYPES and not only of shape: a stored/// `"yes"` is not `true`. A stored `moodHour` or `mood` switch from an older/// build is ignored: Cotton no longer asks about mood on a schedule (owner,/// 11 Oct 2026).pubfn migrate_notification_prefs(raw: &Value) -> NotificationPrefs {let defaults = NotificationPrefs::default();letSome(record) = raw.as_object() else {return defaults; };let stored = record.get("categories").and_then(Value::as_object);let categories = NOTIFICATION_CATEGORIES .into_iter() .map(|category| {let value = stored .and_then(|held| held.get(category.as_str())) .and_then(Value::as_bool); (category, value.unwrap_or(true)) }) .collect();NotificationPrefs { enabled: record .get("enabled") .and_then(Value::as_bool) .unwrap_or(defaults.enabled), categories, asked_at: record .get("askedAt") .and_then(Value::as_str) .map(str::to_string), }}// ── what a notification says ──────────────────────────────────────────────//// The lock screen already says "Cotton", so the title is the thing itself — the// todo's words, the meeting's name — and the body is the one fact that makes it// actionable. No exclamation, no "Don't forget!", no emoji shouting a kind the// glyph already carries.//// The engine says which fact; the words are the database's line set// `reminders` (`rules::shell_lines`), said at the reading edge// (`cotton_ffi::phone::reminders`)./// The line set a notification's words live in.pubconst SET: &str = "reminders";/// What a notification's title is.#[derive(Debug, Clone, PartialEq, Eq)]pubenumReminderTitle {/// The record's own words — the todo's title, the event's name.Record(String),/// A birthday: the person's name carries it.Birthday { name: String },}/// The one fact that makes a notification actionable.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumReminderLine {/// A timed todo, at its stated hour: the hour IS the message.DueNow,/// A date-only todo, at the morning nudge: the day is the promise.DueToday,/// An event, `minutes` out.StartsSoon { minutes: i64 },/// A birthday whose year is known; nothing invented when it is not.Turns { age: i64 },}implReminderTitle {pubfn say(&self, rows: &[LineRow]) -> String {matchself {ReminderTitle::Record(words) => words.clone(),ReminderTitle::Birthday { name } => resolve(SET, "birthday", rows, &[("name", name)]).unwrap_or_default(), } }}implReminderLine {pubfn say(&self, rows: &[LineRow]) -> String {matchself {ReminderLine::DueNow => resolve(SET, "due_now", rows, &[]),ReminderLine::DueToday => resolve(SET, "due_today", rows, &[]),ReminderLine::StartsSoon { minutes } => { resolve(SET, "starts_soon", rows, &[("n", &super::shell_lines::number(*minutes))]) }ReminderLine::Turns { age } => resolve(SET, "turns", rows, &[("age", &age.to_string())]), } .unwrap_or_default() }}// ── the name ──────────────────────────────────────────────────────────────/// The local fire instant, to the minute — the part that makes a name unique.////// **THE MINUTE IS THE WHOLE DIFFING MECHANISM.** [`reconcile`] compares the/// names it WANTS against the names iOS is holding and never reads a trigger/// back out of the OS, which only works if the name changes whenever the/// notification would fire at a different moment. Move a todo from 9:00 to/// 18:00 on the same day and a date-only stamp would leave the old 9:00/// notification standing — same name, already scheduled, nothing to do — while/// the app believed it had rescheduled. With a minute stamp the new name is/// absent (schedule it) and the old one is an orphan (cancel it): one set/// difference, no special case.pubfn fire_stamp(at_ms: i64, timezone: &str) -> Result<String, ZoneError> {let parts = zoned_parts(at_ms, timezone)?;Ok(format!("{:04}{:02}{:02}T{:02}{:02}", parts.year, parts.month, parts.day, parts.hour, parts.minute ))}/// `cotton:<kind>:<recordId>:<stamp>`.////// A record id is a uuid, so it never contains `:` and the parse is total.pubfn notification_identifier( kind: NotificationKind, record_id: &str, at_ms: i64, timezone: &str,) -> Result<String, ZoneError> {let stamp = fire_stamp(at_ms, timezone)?;Ok(format!("{IDENTIFIER_PREFIX}:{}:{record_id}:{stamp}", kind.as_str() ))}/// Is this one of ours?////// [`reconcile`] cancels orphans, and an orphan test that did not ask this/// would happily cancel a notification another library — or a future Cotton/// feature that schedules by hand — put on the queue.pubfn is_cotton_identifier(identifier: &str) -> bool { identifier.starts_with(IDENTIFIER_PREFIX) && identifier.as_bytes().get(IDENTIFIER_PREFIX.len()) == Some(&b':')}/// What a Cotton identifier names.#[derive(Debug, Clone, PartialEq, Eq)]pubstructParsedIdentifier {pub kind: NotificationKind,pub record_id: String,pub stamp: String,}/// The inverse of [`notification_identifier`]; `None` for anything foreign.pubfn parse_notification_identifier(identifier: &str) -> Option<ParsedIdentifier> {let parts: Vec<&str> = identifier.split(':').collect();if parts.len() != 4 {returnNone; }if parts[0] != IDENTIFIER_PREFIX {returnNone; }let kind = NotificationKind::parse(parts[1])?;if parts[2].is_empty() || parts[3].is_empty() {returnNone; }Some(ParsedIdentifier { kind, record_id: parts[2].to_string(), stamp: parts[3].to_string(), })}// ── the desired set ───────────────────────────────────────────────────────/// One notification the app WANTS to exist.#[derive(Debug, Clone, PartialEq, Eq)]pubstructDesiredNotification {/// `cotton:<kind>:<recordId>:<stamp>`.pub identifier: String,pub kind: NotificationKind,/// The record a tap opens (a PERSON id for a birthday).pub record_id: String,/// When it fires, as epoch milliseconds.////// One representation, not two: the local wall clock it corresponds to is/// in the identifier's stamp, and carrying both here would be two answers/// to one question.pub at_ms: i64,pub title: ReminderTitle,pub body: Option<ReminderLine>,}/// A todo, as this engine reads it.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructTodoRow {pub id: String,pub title: String,/// `open`, `done`, `dropped` — only `open` earns a reminder.pub status: String,pub due_at: Option<String>,pub snoozed_until: Option<String>,}/// One expanded occurrence, with the two facts about its EVENT that decide/// whether it earns a reminder.////// Shaped like the TypeScript's `EventOccurrence` rather than like/// [`crate::rules::series::SeriesOccurrence`], because the decision needs/// `all_day` and `my_response`, which live on the row and not on the/// expansion. The caller joins the two — the recurrence itself is/// `expand_calendar`'s, and this engine never re-decides when a thing repeats.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructEventOccurrence {/// The event row a tap opens — the master's id for an ordinary occurrence,/// the exception's for one that was moved.pub event_id: String,pub title: String,/// This occurrence's own start, ISO.pub starts_at: String,pub all_day: bool,/// `Some("declined")` is the one value that silences it.pub my_response: Option<String>,/// The event's own alert, minutes before it starts (`event.alert`, the/// person's own even on a Google event); `None` is the ten minutes and/// [`NO_ALERT`] is none at all.pub lead_minutes: Option<i64>,}/// One yearly date coming round inside the horizon: the record a tap opens/// (a person), the name it carries, its day in the caller's zone, and the/// years it completes that day (`None` when the year is not known).#[derive(Debug, Clone, PartialEq, Eq)]pubstructBirthdayOccurrence {pub person_id: String,pub name: String,pub on: CivilDate,pub turning: Option<i64>,}/// Everything the decision reads.#[derive(Debug, Clone)]pubstructDesiredSetInput<'a> {/// Every todo the app holds — the pool, not a pre-filtered selection.pub todos: &'a [TodoRow],/// Expanded occurrences across the horizon (recurrence already unrolled).pub occurrences: &'a [EventOccurrence],/// Birthdays falling inside the horizon, soonest first.pub birthdays: &'a [BirthdayOccurrence],pub prefs: &'a NotificationPrefs,/// The instant the pass runs at, epoch milliseconds. Injected, never read.pub now_ms: i64,/// The IANA zone every local-hour decision is made in. Required.pub timezone: &'a str,pub horizon_days: i64,/// Whether a to-do with only a day (no time) reminds at 09:00. Cotton/// Days says no (DECISIONS.md: a to-do alerts only if it was given a/// time); the other apps keep their morning nudge.pub untimed_todos: bool,}// THE ONLY FAILURE IS THE ZONE, and it is a [`ZoneError`] rather than an error// type of this module's own. Everything else a row can get wrong — an// unparseable `due_at`, a `starts_at` that is not an instant — is SKIPPED, which// is what the TypeScript's `instant()` answering null does. A second error// vocabulary here would be a refusal shape nobody raises./// The civil day an instant falls on, in `timezone`.fn civil_day(at_ms: i64, timezone: &str) -> Result<CivilDate, ZoneError> {let parts = zoned_parts(at_ms, timezone)?;Ok(CivilDate { year: parts.year, month: parts.month, day: parts.day, })}/// A civil day plus a wall-clock hour, back as an instant.fn at_hour(day: CivilDate, hour: i64, timezone: &str) -> Result<i64, ZoneError> { instant_from_zoned(ZonedParts { year: day.year, month: day.month, day: day.day, hour, minute: 0, second: 0, },0, timezone, )}/// The far end of the reminder window, in CALENDAR days.////// **PUBLIC because it has two callers and must have one spelling.** The pass/// below gates every candidate on it, and the FFI's `reminders.desired` asks/// the recurrence engine to expand occurrences up to it — and a window/// computed twice is a window that disagrees on exactly the two days a year/// this arithmetic exists for. `addDays` preserves the WALL CLOCK across a DST/// change; `horizon_days * 86_400_000` does not, and across a spring-forward/// it lands an hour early, which is an event in that hour never expanded and/// never reminded.////// The end carries `now`'s hour, minute and second but NOT its millisecond/// (`instant_from_zoned(…, 0, …)` below), so the window is up to 999 ms shorter/// than date-fns' `addDays`. Sub-millisecond, at the far edge of a fortnight,/// and harmless — written down only because this module claims byte-identical/// plans and an unexplained millisecond is how that claim stops being checkable.pubfn horizon_end(now_ms: i64, horizon_days: i64, timezone: &str) -> Result<i64, ZoneError> {let today = civil_day(now_ms, timezone)?;let now_parts = zoned_parts(now_ms, timezone)?;let last_day = plus_days(today, horizon_days); instant_from_zoned(ZonedParts { year: last_day.year, month: last_day.month, day: last_day.day, hour: now_parts.hour, minute: now_parts.minute, second: now_parts.second, },0, timezone, )}/// `day + offset`, as a civil date.fn plus_days(day: CivilDate, offset: i64) -> CivilDate {let (year, month, date) = civil_from_days(day.day_number() + offset);CivilDate { year, month, day: date, }}/// The morning of the day `day` names, in local time.fn morning_of(day: CivilDate, timezone: &str) -> Result<i64, ZoneError> { at_hour(day, MORNING_HOUR, timezone)}/// Parse an instant a record holds; `None` when absent or unparseable — the/// TypeScript's `instant()`, and the reason an unreadable row is SKIPPED rather/// than fatal.fn instant(at: Option<&str>) -> Option<i64> { parse_date_ms(at?)}/// When a todo's single reminder fires, or `None` if it earns none.////// `timed` says which of the two shapes it was, because the wording differs and/// re-deriving it at the call site is how two answers to one question start/// drifting.pubfn todo_fire_at(todo: &TodoRow, timezone: &str) -> Result<Option<(i64, bool)>, ZoneError> {if todo.status != "open" {returnOk(None); }letSome(due_at) = todo.due_at.as_deref() else {returnOk(None); };letSome(due_ms) = parse_date_ms(due_at) else {returnOk(None); };// The app's all-day convention, decided in the ONE place that owns it:// local midnight means "this day", with no hour claimed. A day-shaped// promise gets a morning nudge, not a midnight one.let timed = match states_clock_time(due_at, timezone) {Ok(timed) => timed,Err(MomentSplitError::Zone(zone)) => returnErr(zone),// A `due_at` the due engine cannot read is a row this engine skips,// the same answer `instant()` gives the TypeScript.Err(_) => returnOk(None), };if timed {Ok(Some((due_ms, true))) } else {Ok(Some(( morning_of(civil_day(due_ms, timezone)?, timezone)?,false, ))) }}/// When an occurrence's reminder fires, or `None` if it earns none.pubfn event_fire_at(occurrence: &EventOccurrence) -> Option<i64> {// An all-day event has no hour to be ten minutes before; a declined one is// not on your day at all.if occurrence.all_day {returnNone; }if occurrence.my_response.as_deref() == Some("declined") {returnNone; }// "No alert" is the person saying so; it is not the default.let lead = event_lead(occurrence.lead_minutes)?;let starts = instant(Some(occurrence.starts_at.as_str()))?;Some(starts - lead * 60_000)}/// The whole "what should exist" decision.pubfn build_desired_set( input: &DesiredSetInput<'_>,) -> Result<Vec<DesiredNotification>, ZoneError> {letDesiredSetInput { prefs, now_ms, timezone, horizon_days, .. } = *input;// CALENDAR days, not `horizon_days * 86_400_000` — see [`horizon_end`],// which is public precisely so the caller that EXPANDS the occurrences// asks the same question this gate answers.let horizon_end = horizon_end(now_ms, horizon_days, timezone)?;// One gate for both ends of the window, so "past" and "too far out" can// never disagree between kinds.let in_window = |at: i64| at > now_ms && at <= horizon_end;letmut out: Vec<DesiredNotification> = Vec::new();if prefs.kind_enabled(NotificationKind::Todo) {for todo in input.todos {letSome((at, timed)) = todo_fire_at(todo, timezone)? else {continue; };if !timed && !input.untimed_todos {continue; }if !in_window(at) {continue; }// Snoozed past the reminder: the person already moved this out of// their way, and a notification would be the app disagreeing.ifletSome(snoozed) = instant(todo.snoozed_until.as_deref()) {if snoozed > at {continue; } } out.push(DesiredNotification { identifier: notification_identifier(NotificationKind::Todo, &todo.id, at, timezone, )?, kind: NotificationKind::Todo, record_id: todo.id.clone(), at_ms: at, title: ReminderTitle::Record(todo.title.clone()), body: Some(if timed { ReminderLine::DueNow } else { ReminderLine::DueToday }), }); } }if prefs.kind_enabled(NotificationKind::Event) {for occurrence in input.occurrences {letSome(at) = event_fire_at(occurrence) else {continue; };if !in_window(at) {continue; } out.push(DesiredNotification { identifier: notification_identifier(NotificationKind::Event, &occurrence.event_id, at, timezone, )?, kind: NotificationKind::Event, record_id: occurrence.event_id.clone(), at_ms: at, title: ReminderTitle::Record(occurrence.title.clone()), body: event_lead(occurrence.lead_minutes).map(|minutes| ReminderLine::StartsSoon { minutes }), }); } }if prefs.kind_enabled(NotificationKind::Birthday) {for birthday in input.birthdays {let at = morning_of(birthday.on, timezone)?;if !in_window(at) {continue; } out.push(DesiredNotification { identifier: notification_identifier(NotificationKind::Birthday, &birthday.person_id, at, timezone, )?, kind: NotificationKind::Birthday, record_id: birthday.person_id.clone(), at_ms: at, title: ReminderTitle::Birthday { name: birthday.name.clone() }, body: birthday.turning.map(|age| ReminderLine::Turns { age }), }); } }// Firing order, then the name. The TypeScript's tiebreak is// `localeCompare` over an identifier, which is `cotton:` plus a kind plus a// uuid plus digits — ASCII throughout, where ICU collation and byte order// agree. out.sort_by(|a, b| { a.at_ms .cmp(&b.at_ms) .then_with(|| a.identifier.cmp(&b.identifier)) });// THE CUT, and it is after the sort on purpose: the queue's ceiling costs// the furthest-out notification, never the next one. See [`PENDING_BUDGET`]. out.truncate(PENDING_BUDGET);Ok(out)}// ── the diff ──────────────────────────────────────────────────────────────/// What one pass would change.#[derive(Debug, Clone, PartialEq, Eq, Default)]pubstructReconcilePlan {/// Desired notifications iOS is not holding yet.pub to_schedule: Vec<DesiredNotification>,/// Cotton identifiers iOS holds that are no longer wanted.pub to_cancel: Vec<String>,}/// True when the plan would change nothing (the common case, every tick).pubfn is_noop(plan: &ReconcilePlan) -> bool { plan.to_schedule.is_empty() && plan.to_cancel.is_empty()}/// THE DIFF — desired names against the names iOS is holding.////// Deliberately trivial: because an identifier encodes the fire instant,/// "already correct" is set membership and nothing has to be read back out of/// the OS or compared field by field. The whole reconciliation is two set/// differences.////// The one rule that is not set arithmetic: **only Cotton's own identifiers are/// ever cancelled**. Anything else on the queue belongs to someone else — a/// library, a future feature that schedules by hand — and cancelling it because/// it was not in our desired set would be this engine quietly deleting other/// people's work.pubfn reconcile(desired: &[DesiredNotification], scheduled: &[String]) -> ReconcilePlan {let held: BTreeSet<&str> = scheduled.iter().map(String::as_str).collect();// Dedup by identifier: two records can legitimately want the same name (the// same recurring event expanded twice by overlapping windows), and// scheduling it twice is a reminder that fires twice. Insertion order is// kept, because the desired set is already sorted and a plan that reordered// it would schedule out of firing order.letmut seen: BTreeSet<&str> = BTreeSet::new();letmut wanted: Vec<&DesiredNotification> = Vec::new();for notification in desired {if seen.insert(notification.identifier.as_str()) { wanted.push(notification); } }let wanted_names: BTreeSet<&str> = seen;let to_schedule: Vec<DesiredNotification> = wanted .into_iter() .filter(|notification| !held.contains(notification.identifier.as_str())) .cloned() .collect();// Sorted, and a `BTreeSet` walk is already in that order — the TypeScript// sorts explicitly for the same reason: a cancel list a test can assert.let to_cancel: Vec<String> = held .into_iter() .filter(|identifier| is_cotton_identifier(identifier)) .filter(|identifier| !wanted_names.contains(identifier)) .map(str::to_string) .collect();ReconcilePlan { to_schedule, to_cancel, }}#[cfg(test)]#[path = "reminders_tests.rs"]mod tests;