//! The reminder engine, exhaustively — the port of //! `apps/cotton/__tests__/notifications/{desiredSet,identifiers,reconcile, //! prefs}.test.ts`, case for case. //! //! This is the file that has to be exhaustive. Everything downstream is a set //! difference over strings or a call into iOS, so every judgement the feature //! makes — which todo earns a reminder, at what hour, whether the day is //! already gone — is decided here and nowhere else. //! //! **The zone is pinned and the clock injected.** The TypeScript constructs its //! clocks with the LOCAL `Date(y, m, d, …)` form so the suite is //! timezone-independent rather than timezone-lucky; here the zone is an //! argument, so the cases name `Asia/Kolkata` and compute the instants through //! the same `zoned_clock` the engine uses. Nothing reads a wall clock. //! //! Every fixture is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]). use serde_json::json; use super::*; const ZONE: &str = "Asia/Kolkata"; /// A local instant in [`ZONE`], as epoch milliseconds — the analogue of the /// TypeScript's `new Date(y, m, d, h, min)`. fn local(year: i64, month: i64, day: i64, hour: i64, minute: i64) -> i64 { instant_from_zoned( ZonedParts { year, month, day, hour, minute, second: 0, }, 0, ZONE, ) .expect("a real zone") } /// The ISO string the app would have stored for that local instant. fn iso(year: i64, month: i64, day: i64, hour: i64, minute: i64) -> String { cotton_store::protocol::js::to_iso_string(local(year, month, day, hour, minute)) .expect("an instant a calendar can render") } /// Tuesday 11 August 2026, 08:00 local — the TypeScript's `NOW`. fn now() -> i64 { local(2026, 8, 11, 8, 0) } fn todo(id: &str, due_at: Option) -> TodoRow { TodoRow { id: id.to_string(), title: "Call the plumber".to_string(), status: "open".to_string(), due_at, snoozed_until: None, } } fn occurrence(id: &str, starts_at: String) -> EventOccurrence { EventOccurrence { event_id: id.to_string(), title: "Standup".to_string(), starts_at, all_day: false, my_response: Some("accepted".to_string()), lead_minutes: None, } } fn birthday( person_id: &str, name: &str, on: CivilDate, turning: Option, ) -> BirthdayOccurrence { BirthdayOccurrence { person_id: person_id.to_string(), name: name.to_string(), on, turning, } } #[derive(Default)] struct Build { todos: Vec, occurrences: Vec, birthdays: Vec, prefs: Option, now_ms: Option, horizon_days: Option, /// Every case but the DST ones runs in `ZONE`; those need a zone that /// actually transitions. timezone: Option, } impl Build { fn run(&self) -> Vec { let prefs = self.prefs.clone().unwrap_or_default(); build_desired_set(&DesiredSetInput { todos: &self.todos, occurrences: &self.occurrences, birthdays: &self.birthdays, prefs: &prefs, now_ms: self.now_ms.unwrap_or_else(now), timezone: self.timezone.as_deref().unwrap_or(ZONE), horizon_days: self.horizon_days.unwrap_or(HORIZON_DAYS), untimed_todos: true, }) .expect("a real zone") } } /// Prefs with one category switched off. fn without(category: NotificationCategory) -> NotificationPrefs { let mut prefs = NotificationPrefs::default(); prefs.categories.insert(category, false); prefs } // ── buildDesiredSet — todos ─────────────────────────────────────────────── #[test] fn a_timed_todo_reminds_at_its_stated_hour() { let found = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 12, 17, 30)))], ..Default::default() } .run(); let reminder = &found[0]; assert_eq!(reminder.kind, NotificationKind::Todo); assert_eq!(reminder.record_id, "todo-1"); assert_eq!(reminder.at_ms, local(2026, 8, 12, 17, 30)); assert_eq!(reminder.title.say(&[]), "Call the plumber"); assert_eq!(reminder.body.map(|body| body.say(&[])).as_deref(), Some("Due now")); assert_eq!(reminder.identifier, "cotton:todo:todo-1:20260812T1730"); } #[test] fn a_date_only_todo_reminds_at_nine_in_the_morning_not_at_midnight() { // Local midnight is the app's all-day convention, and `moment_split` is the one // place that says so. let found = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 13, 0, 0)))], ..Default::default() } .run(); assert_eq!(found[0].at_ms, local(2026, 8, 13, 9, 0)); assert_eq!(found[0].body.map(|body| body.say(&[])).as_deref(), Some("Due today")); assert_eq!(found[0].identifier, "cotton:todo:todo-1:20260813T0900"); } #[test] fn a_date_only_todo_due_today_still_reminds_while_nine_is_ahead() { // Clock is 08:00; the morning nudge has not gone yet. let found = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 11, 0, 0)))], ..Default::default() } .run(); assert_eq!(found.len(), 1); } #[test] fn it_stays_silent_once_todays_nine_has_passed() { let found = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 11, 0, 0)))], now_ms: Some(local(2026, 8, 11, 10, 0)), ..Default::default() } .run(); assert!(found.is_empty()); } #[test] fn a_done_or_dropped_todo_never_reminds() { for status in ["done", "dropped"] { let mut row = todo("todo-1", Some(iso(2026, 8, 12, 17, 30))); row.status = status.to_string(); let found = Build { todos: vec![row], ..Default::default() } .run(); assert!(found.is_empty(), "{status}"); } } #[test] fn a_todo_with_no_due_instant_or_an_unparseable_one_is_ignored() { let found = Build { todos: vec![todo("a", None), todo("b", Some("not a date".to_string()))], ..Default::default() } .run(); assert!(found.is_empty()); } #[test] fn a_due_instant_already_gone_is_ignored() { let found = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 10, 9, 0)))], ..Default::default() } .run(); assert!(found.is_empty()); } #[test] fn it_schedules_to_the_edge_of_the_horizon_and_no_further() { // NOW + 14 days = 25 Aug 08:00, so 07:00 is in and 09:00 is out. let found = Build { todos: vec![ todo("in", Some(iso(2026, 8, 25, 7, 0))), todo("out", Some(iso(2026, 8, 25, 9, 0))), ], ..Default::default() } .run(); let ids: Vec<&str> = found.iter().map(|n| n.record_id.as_str()).collect(); assert_eq!(ids, ["in"]); } #[test] fn a_shorter_horizon_is_respected_when_one_is_given() { let due = iso(2026, 8, 20, 9, 0); assert!(Build { todos: vec![todo("todo-1", Some(due.clone()))], horizon_days: Some(3), ..Default::default() } .run() .is_empty()); assert_eq!( Build { todos: vec![todo("todo-1", Some(due))], horizon_days: Some(14), ..Default::default() } .run() .len(), 1 ); } #[test] fn a_todo_snoozed_past_its_reminder_stays_silent() { let mut row = todo("todo-1", Some(iso(2026, 8, 12, 9, 0))); row.snoozed_until = Some(iso(2026, 8, 13, 9, 0)); assert!(Build { todos: vec![row], ..Default::default() } .run() .is_empty()); } #[test] fn a_snooze_that_ends_before_the_reminder_does_not_silence_it() { let mut row = todo("todo-1", Some(iso(2026, 8, 13, 9, 0))); row.snoozed_until = Some(iso(2026, 8, 12, 9, 0)); assert_eq!( Build { todos: vec![row], ..Default::default() } .run() .len(), 1 ); } // ── buildDesiredSet — events ────────────────────────────────────────────── #[test] fn an_event_reminds_ten_minutes_before_it_starts() { let found = Build { occurrences: vec![occurrence("event-1", iso(2026, 8, 12, 9, 0))], ..Default::default() } .run(); let reminder = &found[0]; assert_eq!(reminder.kind, NotificationKind::Event); assert_eq!(reminder.at_ms, local(2026, 8, 12, 8, 50)); assert_eq!(reminder.title.say(&[]), "Standup"); assert_eq!(reminder.body.map(|body| body.say(&[])).as_deref(), Some("Starts in 10 minutes")); assert_eq!(reminder.identifier, "cotton:event:event-1:20260812T0850"); } #[test] fn an_all_day_event_is_skipped_because_there_is_no_hour_to_be_ten_minutes_before() { let mut row = occurrence("event-1", iso(2026, 8, 13, 0, 0)); row.all_day = true; assert!(Build { occurrences: vec![row], ..Default::default() } .run() .is_empty()); } #[test] fn an_event_already_declined_is_skipped() { let mut row = occurrence("event-1", iso(2026, 8, 12, 9, 0)); row.my_response = Some("declined".to_string()); assert!(Build { occurrences: vec![row], ..Default::default() } .run() .is_empty()); } #[test] fn every_response_but_declined_still_reminds() { for response in [ Some("accepted"), Some("tentative"), Some("needs_action"), None, ] { let mut row = occurrence("event-1", iso(2026, 8, 12, 9, 0)); row.my_response = response.map(str::to_string); assert_eq!( Build { occurrences: vec![row], ..Default::default() } .run() .len(), 1, "{response:?}" ); } } #[test] fn an_event_whose_ten_minute_mark_has_gone_is_skipped() { // Starts 08:05, so the reminder instant (07:55) is behind the 08:00 clock. assert!(Build { occurrences: vec![occurrence("event-1", iso(2026, 8, 11, 8, 5))], ..Default::default() } .run() .is_empty()); } #[test] fn each_occurrence_of_a_recurring_event_gets_its_own_reminder() { let found = Build { occurrences: vec![ occurrence("weekly", iso(2026, 8, 12, 9, 0)), occurrence("weekly", iso(2026, 8, 19, 9, 0)), ], ..Default::default() } .run(); let identifiers: Vec<&str> = found.iter().map(|n| n.identifier.as_str()).collect(); assert_eq!( identifiers, [ "cotton:event:weekly:20260812T0850", "cotton:event:weekly:20260819T0850", ] ); } // ── buildDesiredSet — birthdays ─────────────────────────────────────────── #[test] fn a_birthday_reminds_at_nine_naming_the_age_when_the_year_is_known() { let found = Build { birthdays: vec![birthday( "person-1", "Asha", CivilDate { year: 2026, month: 8, day: 17, }, Some(34), )], ..Default::default() } .run(); let reminder = &found[0]; assert_eq!(reminder.kind, NotificationKind::Birthday); // A tap opens the PERSON — a birthday has no record of its own. assert_eq!(reminder.record_id, "person-1"); assert_eq!(reminder.at_ms, local(2026, 8, 17, 9, 0)); assert_eq!(reminder.title.say(&[]), "Asha's birthday"); assert_eq!(reminder.body.map(|body| body.say(&[])).as_deref(), Some("Turns 34 today")); assert_eq!( reminder.identifier, "cotton:birthday:person-1:20260817T0900" ); } #[test] fn no_age_is_invented_when_the_birth_year_is_unknown() { let found = Build { birthdays: vec![birthday( "person-1", "Asha", CivilDate { year: 2026, month: 8, day: 17, }, None, )], ..Default::default() } .run(); assert_eq!(found[0].body, None); } #[test] fn a_birthday_past_the_horizon_is_dropped() { assert!(Build { birthdays: vec![birthday( "person-1", "Asha", CivilDate { year: 2026, month: 9, day: 30, }, Some(34), )], ..Default::default() } .run() .is_empty()); } // ── buildDesiredSet — the switches ──────────────────────────────────────── fn everything() -> Build { Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 12, 17, 30)))], occurrences: vec![occurrence("event-1", iso(2026, 8, 12, 9, 0))], birthdays: vec![birthday( "p", "Asha", CivilDate { year: 2026, month: 8, day: 17, }, None, )], ..Default::default() } } #[test] fn all_three_kinds_are_scheduled_by_default() { let found = everything().run(); let kinds: Vec = found.iter().map(|n| n.kind).collect(); assert_eq!( kinds, [ NotificationKind::Event, NotificationKind::Todo, NotificationKind::Birthday, ] ); } #[test] fn a_category_switched_off_removes_every_notification_of_its_kind() { for (category, kind) in [ (NotificationCategory::Reminders, NotificationKind::Todo), (NotificationCategory::Events, NotificationKind::Event), (NotificationCategory::Birthdays, NotificationKind::Birthday), ] { let mut build = everything(); build.prefs = Some(without(category)); let found = build.run(); let kinds: Vec = found.iter().map(|n| n.kind).collect(); assert!(!kinds.contains(&kind), "{category:?}"); assert_eq!(kinds.len(), 2, "{category:?}"); } } #[test] fn the_master_switch_off_empties_the_set_which_is_how_the_queue_is_wiped() { let mut build = everything(); build.prefs = Some(NotificationPrefs { enabled: false, ..Default::default() }); assert!(build.run().is_empty()); } // ── buildDesiredSet — determinism ───────────────────────────────────────── #[test] fn the_set_comes_back_in_firing_order_regardless_of_input_order() { let found = Build { todos: vec![ todo("late", Some(iso(2026, 8, 14, 9, 0))), todo("early", Some(iso(2026, 8, 12, 9, 0))), ], occurrences: vec![occurrence("event-1", iso(2026, 8, 13, 9, 0))], ..Default::default() } .run(); let ids: Vec<&str> = found.iter().map(|n| n.record_id.as_str()).collect(); assert_eq!(ids, ["early", "event-1", "late"]); } #[test] fn the_same_world_is_named_the_same_way_twice() { // A FAITHFUL PORT of a JS guard against `Date.now()` leaking into a // function that takes `now`. It cannot go red here — `build_desired_set` is // pure and this crate cannot reach a clock — and it is kept because the // identifier is a contract: the day someone reaches for a random suffix or // a hash of a `HashMap`'s iteration order, this is what says no. let build = || Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 12, 17, 30)))], occurrences: vec![occurrence("event-1", iso(2026, 8, 12, 9, 0))], ..Default::default() }; let first: Vec = build().run().into_iter().map(|n| n.identifier).collect(); let again: Vec = build().run().into_iter().map(|n| n.identifier).collect(); assert_eq!(first, again); } #[test] fn a_todo_that_moves_to_a_different_hour_mints_a_new_name() { // The whole point of the minute stamp. let before = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 12, 9, 0)))], ..Default::default() } .run()[0] .identifier .clone(); let after = Build { todos: vec![todo("todo-1", Some(iso(2026, 8, 12, 18, 0)))], ..Default::default() } .run()[0] .identifier .clone(); assert_ne!(before, after); } // ── buildDesiredSet — the queue's ceiling ───────────────────────────────── // // iOS holds 64 pending requests per bundle and drops the rest SILENTLY, and // which ones it drops is undefined. These cases are the whole reason // `PENDING_BUDGET` exists: a fortnight-shaped horizon does not bound a COUNT. /// The local instant the `index`th todo of a synthetic queue is due at — /// 12 August 09:00 plus `index` minutes, so every row lands inside the horizon /// and every one earns a name of its own from the minute stamp. fn queue_instant(index: usize) -> i64 { let index = index as i64; local(2026, 8, 12, 9 + index / 60, index % 60) } /// `count` todos, one a minute, in firing order. fn a_queue_of(count: usize) -> Vec { (0..count) .map(|index| { let due = cotton_store::protocol::js::to_iso_string(queue_instant(index)) .expect("an instant a calendar can render"); todo(&format!("todo-{index:03}"), Some(due)) }) .collect() } #[test] fn a_queue_under_the_budget_is_left_whole() { let found = Build { todos: a_queue_of(PENDING_BUDGET - 1), ..Default::default() } .run(); assert_eq!(found.len(), PENDING_BUDGET - 1); } #[test] fn a_queue_at_the_budget_is_left_whole() { let found = Build { todos: a_queue_of(PENDING_BUDGET), ..Default::default() } .run(); assert_eq!(found.len(), PENDING_BUDGET); } #[test] fn a_queue_over_the_budget_is_cut_to_it() { let found = Build { todos: a_queue_of(PENDING_BUDGET + 12), ..Default::default() } .run(); assert_eq!(found.len(), PENDING_BUDGET); } #[test] fn the_cut_keeps_the_soonest_and_loses_the_furthest_out() { // The point of capping here rather than letting iOS choose: a full queue // costs a birthday a fortnight away, never the meeting this afternoon. let found = Build { todos: a_queue_of(PENDING_BUDGET + 12), ..Default::default() } .run(); let kept: Vec<&str> = found.iter().map(|n| n.record_id.as_str()).collect(); assert_eq!(kept.first().copied(), Some("todo-000")); assert_eq!( kept.last().copied(), Some(format!("todo-{:03}", PENDING_BUDGET - 1).as_str()) ); assert!(!kept.contains(&format!("todo-{PENDING_BUDGET:03}").as_str())); } #[test] fn the_cut_reads_the_clock_and_not_the_input_order() { // The rows arrive furthest-out FIRST. If the truncation happened before // the sort, every survivor would be one of the ones that fire last. let mut reversed = a_queue_of(PENDING_BUDGET + 12); reversed.reverse(); let found = Build { todos: reversed, ..Default::default() } .run(); assert_eq!(found.len(), PENDING_BUDGET); assert_eq!(found[0].record_id, "todo-000"); assert_eq!(found[0].at_ms, queue_instant(0)); } #[test] fn the_budget_leaves_headroom_under_the_operating_system_s_own_ceiling() { // 64 is iOS's, and it is shared with `/alarms` and anything scheduled by // hand. A budget that spent all of it would make the ceiling this engine's // problem to hit rather than its problem to stay under. // A binding rather than the literal, so the comparison is a test the runner // reports rather than a constant clippy folds away. let ios_ceiling: usize = 64; assert!( PENDING_BUDGET < ios_ceiling, "the budget must stay under iOS's {ios_ceiling}-pending ceiling" ); assert!( ios_ceiling - PENDING_BUDGET >= 16, "the headroom is what `/alarms` and anything scheduled by hand spend" ); } #[test] fn a_pass_after_the_budget_tightens_cancels_what_is_standing_beyond_it() { // The queue was scheduled whole by some earlier build; this pass wants only // the budget's worth, and the overflow has to come back off the queue // rather than sit there firing for rows nobody is reconciling any more. let rows = a_queue_of(PENDING_BUDGET + 12); let desired = Build { todos: rows.clone(), ..Default::default() } .run(); let held: Vec = rows .iter() .enumerate() .map(|(index, row)| { notification_identifier(NotificationKind::Todo, &row.id, queue_instant(index), ZONE) .expect("a real zone") }) .collect(); let plan = reconcile(&desired, &held); assert!(plan.to_schedule.is_empty(), "every survivor is already on the queue"); assert_eq!(plan.to_cancel.len(), 12); assert_eq!(plan.to_cancel[0], held[PENDING_BUDGET]); } // ── the zone, which the TypeScript never had to argue about ─────────────── #[test] fn an_unknown_zone_is_a_refusal_and_never_a_fallback_to_utc() { // AGENTS.md's rule, and the defect it exists to prevent: a check-in tapped // at 00:30 IST is stamped tomorrow by the writer and filtered out of // "today" by a reader that guessed UTC. let prefs = NotificationPrefs::default(); let error = build_desired_set(&DesiredSetInput { todos: &[], occurrences: &[], birthdays: &[], prefs: &prefs, now_ms: now(), timezone: "Middle/Earth", horizon_days: HORIZON_DAYS, untimed_todos: true, }) .expect_err("a refusal"); assert_eq!( error, ZoneError::UnknownTimeZone("Middle/Earth".to_string()) ); } #[test] fn the_morning_nudge_is_nine_in_the_named_zone_and_not_nine_utc() { // The same date-only todo, read in two zones. Under a UTC fallback both // would answer the same instant, which is the whole bug. let due = iso(2026, 8, 13, 0, 0); let prefs = NotificationPrefs::default(); let rows = [todo("todo-1", Some(due))]; let in_kolkata = build_desired_set(&DesiredSetInput { todos: &rows, occurrences: &[], birthdays: &[], prefs: &prefs, now_ms: now(), timezone: ZONE, horizon_days: HORIZON_DAYS, untimed_todos: true, }) .expect("a real zone"); let in_utc = build_desired_set(&DesiredSetInput { todos: &rows, occurrences: &[], birthdays: &[], prefs: &prefs, now_ms: now(), timezone: "UTC", horizon_days: HORIZON_DAYS, untimed_todos: true, }) .expect("a real zone"); assert_eq!(in_kolkata[0].at_ms, local(2026, 8, 13, 9, 0)); assert_ne!( in_kolkata[0].at_ms, in_utc[0].at_ms, "the zone decides the morning, so two zones must not agree on it" ); } // ── the name ────────────────────────────────────────────────────────────── #[test] fn a_notification_is_named_by_kind_record_and_local_fire_minute() { assert_eq!( notification_identifier( NotificationKind::Todo, "abc", local(2026, 8, 12, 17, 30), ZONE ) .expect("a real zone"), "cotton:todo:abc:20260812T1730" ); } #[test] fn the_name_changes_when_the_minute_changes_where_a_date_only_stamp_would_not() { let nine = notification_identifier( NotificationKind::Todo, "abc", local(2026, 8, 12, 9, 0), ZONE, ) .expect("a real zone"); let evening = notification_identifier( NotificationKind::Todo, "abc", local(2026, 8, 12, 18, 0), ZONE, ) .expect("a real zone"); assert_ne!(nine, evening); } #[test] fn a_uuid_survives_the_round_trip_which_is_where_a_naive_split_would_break() { let id = "6f1c2a3b-4d5e-4f60-8a9b-0c1d2e3f4a5b"; let identifier = notification_identifier(NotificationKind::Event, id, local(2026, 8, 12, 9, 0), ZONE) .expect("a real zone"); assert_eq!( parse_notification_identifier(&identifier), Some(ParsedIdentifier { kind: NotificationKind::Event, record_id: id.to_string(), stamp: "20260812T0900".to_string(), }) ); } #[test] fn the_stamp_pads_every_field_so_names_sort_as_they_fire() { assert_eq!( fire_stamp(local(2026, 1, 5, 7, 4), ZONE).expect("a real zone"), "20260105T0704" ); } #[test] fn only_cottons_own_identifiers_are_recognised() { for (identifier, expected) in [ ("cotton:todo:a:20260812T0900", true), ("cotton:alarm:a:20260812T0900", true), ("expo-push-42", false), ("cottonish:todo:a:20260812T0900", false), ("", false), ] { assert_eq!(is_cotton_identifier(identifier), expected, "{identifier}"); } } #[test] fn a_name_that_is_not_ours_or_not_whole_parses_to_nothing() { for identifier in [ "not-ours:todo:a:20260812T0900", "cotton:todo:a", "cotton:todo:a:20260812T0900:extra", "cotton:banana:a:20260812T0900", "cotton:todo::20260812T0900", ] { assert_eq!( parse_notification_identifier(identifier), None, "{identifier}" ); } } // ── the diff ────────────────────────────────────────────────────────────── fn desired(identifier: &str) -> DesiredNotification { DesiredNotification { identifier: identifier.to_string(), kind: NotificationKind::Todo, record_id: identifier.split(':').nth(2).unwrap_or_default().to_string(), at_ms: local(2026, 8, 12, 9, 0), title: ReminderTitle::Record("Something".to_string()), body: None, } } const A: &str = "cotton:todo:a:20260812T0900"; const B: &str = "cotton:todo:b:20260813T0900"; const C: &str = "cotton:event:c:20260814T0850"; fn names(plan: &ReconcilePlan) -> Vec<&str> { plan.to_schedule .iter() .map(|n| n.identifier.as_str()) .collect() } fn held(identifiers: &[&str]) -> Vec { identifiers.iter().map(|id| (*id).to_string()).collect() } #[test] fn everything_is_scheduled_when_ios_is_holding_nothing() { let plan = reconcile(&[desired(A), desired(B)], &[]); assert_eq!(names(&plan), [A, B]); assert!(plan.to_cancel.is_empty()); } #[test] fn nothing_happens_when_the_queue_already_matches() { let plan = reconcile(&[desired(A), desired(B)], &held(&[A, B])); assert!(plan.to_schedule.is_empty()); assert!(plan.to_cancel.is_empty()); assert!(is_noop(&plan)); } #[test] fn a_duplicate_of_something_already_on_the_queue_is_never_scheduled() { let plan = reconcile(&[desired(A), desired(B)], &held(&[A])); assert_eq!(names(&plan), [B]); } #[test] fn two_desired_entries_sharing_a_name_collapse_to_one() { // A recurring event expanded by two overlapping windows wants the same // name twice; scheduling it twice is a reminder that fires twice. let plan = reconcile(&[desired(A), desired(A)], &[]); assert_eq!(plan.to_schedule.len(), 1); } #[test] fn a_cotton_notification_no_longer_wanted_is_cancelled() { let plan = reconcile(&[desired(A)], &held(&[A, B, C])); assert!(plan.to_schedule.is_empty()); // `to_cancel` is sorted, so the event name precedes the todo ones. assert_eq!(plan.to_cancel, [C, B]); } #[test] fn notifications_that_are_not_ours_are_left_alone() { let plan = reconcile(&[], &held(&["some-other-library-id", "expo-push-42", A])); assert_eq!(plan.to_cancel, [A]); } #[test] fn an_empty_desired_set_wipes_every_cotton_reminder() { // This is what the master switch off, and a revoked OS permission, both // reduce to — there is deliberately no second code path for either. let plan = reconcile(&[], &held(&[A, B, C])); assert_eq!(plan.to_cancel, [C, A, B]); assert!(plan.to_schedule.is_empty()); } #[test] fn a_reminder_that_moves_is_both_a_cancel_and_a_schedule() { let moved = "cotton:todo:a:20260812T1800"; let plan = reconcile(&[desired(moved)], &held(&[A])); assert_eq!(names(&plan), [moved]); assert_eq!(plan.to_cancel, [A]); } // ── the switches, persisted ─────────────────────────────────────────────── #[test] fn the_storage_key_is_the_one_the_spec_fixed() { assert_eq!(NOTIF_PREFS_KEY, "@cotton:notifprefs"); } #[test] fn anything_that_is_not_a_record_falls_back_to_the_defaults() { // An array is an object in JavaScript, so it takes the partial path there // and supplies nothing — which must land on the defaults just the same. for raw in [Value::Null, json!("off"), json!(42), json!([]), json!(true)] { assert_eq!( migrate_notification_prefs(&raw), NotificationPrefs::default(), "{raw}" ); } } #[test] fn a_complete_stored_record_is_kept() { let stored = json!({ "enabled": false, "categories": { "reminders": false, "events": true, "birthdays": false, "alarms": true, }, "askedAt": "2026-08-11T02:00:00.000Z", }); let prefs = migrate_notification_prefs(&stored); assert!(!prefs.enabled); assert!(!prefs.category_enabled(NotificationCategory::Reminders)); assert!(prefs.category_enabled(NotificationCategory::Events)); assert!(!prefs.category_enabled(NotificationCategory::Birthdays)); assert!(prefs.category_enabled(NotificationCategory::Alarms)); assert_eq!(prefs.asked_at.as_deref(), Some("2026-08-11T02:00:00.000Z")); } #[test] fn a_category_a_stored_record_predates_takes_its_own_default() { // What a record written before `alarms` existed looks like. A new // category arrives on whatever a fresh install would have given it: on. let prefs = migrate_notification_prefs(&json!({ "enabled": true, "categories": { "reminders": false, "events": true, "birthdays": true }, })); assert!(!prefs.category_enabled(NotificationCategory::Reminders)); assert!(prefs.category_enabled(NotificationCategory::Events)); assert!(prefs.category_enabled(NotificationCategory::Birthdays)); assert!(prefs.category_enabled(NotificationCategory::Alarms)); } /// RULE: Cotton never asks about mood on a schedule (owner, 11 Oct 2026): a /// mood is recorded when the person chooses, from the home input or an /// assistant. There is no mood kind or switch, and a device's old `moodHour` /// or `mood` switch from an earlier build changes nothing. #[test] fn nothing_asks_about_mood_on_a_schedule() { assert_eq!(NotificationKind::parse("mood"), None); assert!(NOTIFICATION_CATEGORIES.iter().all(|category| category.as_str() != "mood")); let old = migrate_notification_prefs(&json!({ "moodHour": 18, "categories": { "mood": true, "reminders": false } })); assert_eq!(old, migrate_notification_prefs(&json!({ "categories": { "reminders": false } }))); // Every switch on and no record held: a day passes with nothing asked. let everything = Build::default().run(); assert!(everything.is_empty(), "{everything:?}"); } #[test] fn a_non_boolean_switch_is_refused_rather_than_made_truthy() { let prefs = migrate_notification_prefs(&json!({ "enabled": "yes", "categories": { "reminders": 1, "events": null }, })); assert!(prefs.enabled); assert!(prefs.category_enabled(NotificationCategory::Reminders)); assert!(prefs.category_enabled(NotificationCategory::Events)); } #[test] fn a_non_string_asked_at_is_dropped_so_a_corrupt_record_can_still_be_asked() { assert_eq!( migrate_notification_prefs(&json!({ "askedAt": 1_723_334_400_000i64 })).asked_at, None ); } #[test] fn the_defaults_have_every_record_shaped_category_on_and_nobody_asked_yet() { // On does not mean notifications happen: the OS permission is the real // gate, and Cotton never asks for it at boot. let prefs = NotificationPrefs::default(); assert!(prefs.enabled); assert!(prefs.category_enabled(NotificationCategory::Reminders)); assert!(prefs.category_enabled(NotificationCategory::Events)); assert!(prefs.category_enabled(NotificationCategory::Birthdays)); assert!(prefs.category_enabled(NotificationCategory::Alarms)); assert_eq!(prefs.asked_at, None); } #[test] fn a_kind_is_on_only_when_the_master_and_its_own_category_both_are() { let mut prefs = NotificationPrefs::default(); assert!(prefs.kind_enabled(NotificationKind::Todo)); prefs.categories.insert(NotificationCategory::Reminders, false); assert!(!prefs.kind_enabled(NotificationKind::Todo)); prefs.enabled = false; for kind in NOTIFICATION_KINDS { assert!(!prefs.kind_enabled(kind), "{kind:?}"); } } /// RULE: Each notification kind uses its intended preference category, so switching off that category actually silences its notifications. #[test] fn every_kind_is_governed_by_a_category_and_the_map_is_total() { // The TypeScript's `CATEGORY_FOR_KIND` is a `Record`, // which is what stops a new kind going ungoverned. Here it is a `match`, so // the compiler holds it — and this asserts the pairing itself. for (kind, category) in [ (NotificationKind::Todo, NotificationCategory::Reminders), (NotificationKind::Event, NotificationCategory::Events), (NotificationKind::Birthday, NotificationCategory::Birthdays), (NotificationKind::Alarm, NotificationCategory::Alarms), ] { assert_eq!(kind.category(), category, "{kind:?}"); } } /// RULE: Every notification kind round-trips its payload spelling and unknown spellings are refused, so a tap cannot silently resolve to another kind. #[test] fn every_kind_name_round_trips_the_wire_payload() { // `{kind, id}` is what a scheduled notification's payload holds and what // the Swift tap table parses, so every spelling must round-trip and an // unknown spelling must still be refused. for kind in NOTIFICATION_KINDS { assert_eq!(NotificationKind::parse(kind.as_str()), Some(kind)); } assert_eq!(NotificationKind::parse("banana"), None); assert_eq!(NotificationKind::parse(""), None); } #[test] fn a_reminders_words_are_the_databases_lines() { assert_eq!(ReminderLine::Turns { age: 34 }.say(&[]), "Turns 34 today"); // The name carries the title; the fixture is synthetic. assert_eq!(ReminderTitle::Birthday { name: "Asha".into() }.say(&[]), "Asha's birthday"); // The count picks its form (CLDR), and a rewording is a row. assert_eq!(ReminderLine::StartsSoon { minutes: 1 }.say(&[]), "Starts in 1 minute"); let row = LineRow { set: SET.into(), line: "due_now".into(), words: "Now".into() }; assert_eq!(ReminderLine::DueNow.say(&[row]), "Now"); } // ── the horizon across a DST change ─────────────────────────────────────── #[test] fn the_horizon_keeps_the_wall_clock_across_a_dst_change_rather_than_counting_seconds() { // THE CASE THAT CERTIFIES THE DEVIATION. `horizon_end` is calendar days, // not `horizon_days * 86_400_000`, and these are the two days a year the // difference is visible. // // New York's autumn transition is Sunday 1 November 2026: the clocks go // BACK, so that day has 25 hours. From 08:00 on 29 October, fourteen // calendar days later is 08:00 on 12 November — but fourteen times 86.4 // million milliseconds lands at 07:00, an hour SHORT. In spring the error // runs the other way and the window ends an hour early against the gate. let zone = "America/New_York"; let now_ms = instant_from_zoned( ZonedParts { year: 2026, month: 10, day: 29, hour: 8, minute: 0, second: 0, }, 0, zone, ) .expect("a real zone"); let end = horizon_end(now_ms, 14, zone).expect("a real zone"); let parts = zoned_parts(end, zone).expect("a real zone"); assert_eq!( (parts.year, parts.month, parts.day, parts.hour), (2026, 11, 12, 8), "the same wall-clock hour, fourteen calendar days on" ); // And the arithmetic the FFI used to do, written out, so the divergence is // a number in this file rather than a claim in a comment: one hour. let naive = now_ms + 14 * 86_400_000; assert_eq!(end - naive, 3_600_000); // The gate is the same window, so an event at the far edge is INSIDE it // under calendar days and OUTSIDE it under the naive count. That is the // whole failure: an event in that hour is never expanded and never // reminded, twice a year, at the far edge of a fortnight. let far_edge = instant_from_zoned( ZonedParts { year: 2026, month: 11, day: 12, hour: 7, minute: 30, second: 0, }, 0, zone, ) .expect("a real zone"); assert!(far_edge <= end); assert!(far_edge > naive); let found = Build { now_ms: Some(now_ms), timezone: Some(zone.to_string()), horizon_days: Some(14), occurrences: vec![occurrence( "event-1", cotton_store::protocol::js::to_iso_string(far_edge).expect("an instant"), )], ..Default::default() } .run(); let ids: Vec<&str> = found.iter().map(|n| n.record_id.as_str()).collect(); assert_eq!(ids, ["event-1"]); } #[test] fn a_spring_forward_shortens_the_window_by_the_same_hour_and_the_gate_follows() { // The other direction, so the rule is "wall clock" and not "always later". // New York springs forward on Sunday 8 March 2026: that day has 23 hours. let zone = "America/New_York"; let now_ms = instant_from_zoned( ZonedParts { year: 2026, month: 3, day: 5, hour: 8, minute: 0, second: 0, }, 0, zone, ) .expect("a real zone"); let end = horizon_end(now_ms, 14, zone).expect("a real zone"); let parts = zoned_parts(end, zone).expect("a real zone"); assert_eq!( (parts.year, parts.month, parts.day, parts.hour), (2026, 3, 19, 8) ); assert_eq!(end - (now_ms + 14 * 86_400_000), -3_600_000); } #[test] fn a_zone_with_no_dst_at_all_is_exactly_the_naive_count() { // The control: where there is no transition the two agree to the // millisecond, so the two cases above are about DST and not about an // off-by-one in `plus_days`. let now_ms = instant_from_zoned( ZonedParts { year: 2026, month: 10, day: 29, hour: 8, minute: 0, second: 0, }, 0, ZONE, ) .expect("a real zone"); assert_eq!( horizon_end(now_ms, 14, ZONE).expect("a real zone"), now_ms + 14 * 86_400_000 ); } /// RULE (DECISIONS.md, Days: alerts): in Cotton Days a to-do with only a day never alerts, one with a time does; an event alerts at its own alert's minutes before it starts, else ten. #[test] fn days_keeps_a_day_only_todo_quiet_and_an_event_keeps_its_own_lead() { let prefs = NotificationPrefs::default(); let todos = [todo("day-only", Some(iso(2026, 8, 12, 0, 0))), todo("timed", Some(iso(2026, 8, 12, 15, 0)))]; let mut own = occurrence("own-lead", iso(2026, 8, 12, 18, 0)); own.lead_minutes = Some(30); let occurrences = [own, occurrence("default-lead", iso(2026, 8, 12, 19, 0))]; let set = build_desired_set(&DesiredSetInput { todos: &todos, occurrences: &occurrences, birthdays: &[], prefs: &prefs, now_ms: now(), timezone: ZONE, horizon_days: HORIZON_DAYS, untimed_todos: false, }) .expect("a real zone"); let fired: Vec<(&str, i64)> = set.iter().map(|n| (n.record_id.as_str(), n.at_ms)).collect(); assert_eq!( fired, [ ("timed", local(2026, 8, 12, 15, 0)), ("own-lead", local(2026, 8, 12, 17, 30)), ("default-lead", local(2026, 8, 12, 18, 50)), ] ); } /// RULE (DECISIONS.md, Days: alerts): an event whose alert the person set to "No alert" (`NO_ALERT`) never reminds, and one with no alert stored still reminds ten minutes before, as every event stored before "No alert" existed did. #[test] fn days_keeps_an_event_with_no_alert_quiet_and_one_with_none_stored_at_ten_minutes() { let prefs = NotificationPrefs::default(); let mut quiet = occurrence("no-alert", iso(2026, 8, 12, 18, 0)); quiet.lead_minutes = Some(NO_ALERT); let occurrences = [quiet, occurrence("never-set", iso(2026, 8, 12, 19, 0))]; let set = build_desired_set(&DesiredSetInput { todos: &[], occurrences: &occurrences, birthdays: &[], prefs: &prefs, now_ms: now(), timezone: ZONE, horizon_days: HORIZON_DAYS, untimed_todos: false, }) .expect("a real zone"); let fired: Vec<(&str, i64, Option)> = set.iter().map(|n| (n.record_id.as_str(), n.at_ms, n.body.clone())).collect(); assert_eq!(fired, [("never-set", local(2026, 8, 12, 18, 50), Some(ReminderLine::StartsSoon { minutes: 10 }))]); }