//! `packages/core/__tests__/engine/rrule.test.ts` and//! `rruleZone.test.ts`, case for case.//!//! Two things about the TypeScript files are worth stating before the cases,//! because the port could not carry either one across unchanged.//!//! **`rrule.test.ts` passes NO zone.** Its `expandRrule(rule, dtstart, range)`//! calls are three-argument; at runtime `zone` is `undefined`, `Intl` reads it//! as "the runtime's zone", and the file's `local()` helper builds `Date`s in//! that same zone — so the assertions are self-consistent wherever they run.//! Rust has no `undefined`, and this engine may not read a machine's zone at//! all, so the port names one (`Asia/Kolkata`, the workspace's) and builds its//! dtstart and window in it. Same assertions, one fewer degree of freedom.//!//! **`rruleZone.test.ts` proves the answer does not depend on `process.env.TZ`**//! by running each expansion twice under two forced process zones. There is no//! Rust analogue and there does not need to be: the crate is pure — it reads no//! environment and no clock, and `zoned_clock` takes the zone as an argument on//! every call — so "the process zone leaked in" is not a state this code can//! reach. What DOES come over is the half that has teeth: the absolute instants//! each expansion must produce, and the proof that changing the zone argument//! changes the derived ids (without which every such test passes vacuously).usesuper::*;usecrate::js::to_iso_string;usecrate::zoned_clock::instant_from_zoned;/// The workspace's zone for the `rrule.test.ts` port — see the header.const ZONE: &str = "Asia/Kolkata";/// A wall clock in [`ZONE`], as an instant. The TypeScript's `local()`.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 known zone")}/// `YYYY-MM-DD` in [`ZONE`], the TypeScript's `dateKeys`.fn date_keys(instants: &[i64]) -> Vec<String> { instants .iter() .map(|instant| {let p = zoned_parts(*instant, ZONE).expect("a known zone"); format!("{:04}-{:02}-{:02}", p.year, p.month, p.day) }) .collect()}fn hours(instants: &[i64]) -> Vec<(i64, i64)> { instants .iter() .map(|instant| {let p = zoned_parts(*instant, ZONE).expect("a known zone"); (p.hour, p.minute) }) .collect()}fn expand(rule: &str, dtstart: i64, from: i64, to: i64) -> Vec<i64> { expand_rrule(rule, dtstart, DateRange { from, to }, ZONE).expect("a valid rule")}// ── parse_rrule ──────────────────────────────────────────────────────────────#[test]fn parses_freq_interval_count_until_byday() {let r = parse_rrule("FREQ=WEEKLY;INTERVAL=2;COUNT=5;BYDAY=MO,WE").expect("a valid rule"); assert_eq!(r.freq, RruleFreq::Weekly); assert_eq!(r.interval, 2); assert_eq!(r.count, Some(5)); assert_eq!(r.byday, vec![1, 3]);}#[test]fn defaults_interval_to_one_and_strips_an_rrule_prefix() {let r = parse_rrule("RRULE:FREQ=DAILY").expect("a valid rule"); assert_eq!(r.interval, 1); assert_eq!(r.freq, RruleFreq::Daily);// The prefix match is case-insensitive, as `/^RRULE:/i` is. assert_eq!( parse_rrule("rrule:FREQ=DAILY").expect("a valid rule").freq,RruleFreq::Daily );}#[test]fn refuses_a_missing_or_unknown_freq_so_schema_drift_surfaces() { assert!(parse_rrule("INTERVAL=2").is_err()); assert!(parse_rrule("FREQ=FORTNIGHTLY").is_err());// The sentence reaches an assistant through a tool error, so it is pinned. assert_eq!( parse_rrule("FREQ=FORTNIGHTLY").unwrap_err().to_string(),"Unsupported RRULE FREQ: \"FORTNIGHTLY\". Allowed: DAILY, WEEKLY, MONTHLY, YEARLY" ); assert_eq!( parse_rrule("INTERVAL=2").unwrap_err().to_string(),"Unsupported RRULE FREQ: \"\". Allowed: DAILY, WEEKLY, MONTHLY, YEARLY" );}#[test]fn refuses_an_invalid_byday_token() { assert!(parse_rrule("FREQ=WEEKLY;BYDAY=XX").is_err()); assert_eq!( parse_rrule("FREQ=WEEKLY;BYDAY=XX").unwrap_err().to_string(),"Invalid RRULE BYDAY token: \"XX\"" );}/// The parser's own edges, read out of Node rather than reasoned about.#[test]fn parser_edges_match_node() {// An ordinal prefix is stripped: `2MO` is Monday. assert_eq!( parse_rrule("FREQ=WEEKLY;BYDAY=2MO,-1FR") .expect("a valid rule") .byday, vec![1, 5] );// Lower case is folded on the key and the value alike. assert_eq!( parse_rrule("freq=daily;interval=3") .expect("a valid rule") .interval,3 );// An EMPTY value is falsy in JavaScript, so it takes the default rather// than failing — `INTERVAL=` is interval 1, `COUNT=` is no count.let empty = parse_rrule("FREQ=DAILY;INTERVAL=;COUNT=").expect("a valid rule"); assert_eq!((empty.interval, empty.count), (1, None));// `parseInt` reads the leading digits and discards the rest. assert_eq!( parse_rrule("FREQ=DAILY;INTERVAL=2weeks") .expect("a valid rule") .interval,2 );// Zero and negative intervals are refused; COUNT=0 is legal. assert!(parse_rrule("FREQ=DAILY;INTERVAL=0").is_err()); assert!(parse_rrule("FREQ=DAILY;INTERVAL=-2").is_err()); assert!(parse_rrule("FREQ=DAILY;COUNT=-1").is_err()); assert_eq!( parse_rrule("FREQ=DAILY;COUNT=0") .expect("a valid rule") .count,Some(0) );// A part with no `=` is skipped; a repeated key keeps the LAST one.let odd = parse_rrule("FREQ=DAILY;NOPE;INTERVAL=2;INTERVAL=5").expect("a valid rule"); assert_eq!(odd.interval, 5);// An unsupported key is ignored, not refused — `BYMONTHDAY` appears in real// rules the product writes and the engine simply does not read it. assert!(parse_rrule("FREQ=MONTHLY;BYMONTHDAY=2").is_ok());}// ── parse_ical_date ──────────────────────────────────────────────────────────#[test]fn parses_a_utc_datetime_and_a_bare_date() { assert_eq!( parse_ical_date("20260731T000000Z"),Ok(date_utc(2026, 6, 31, 0, 0, 0, 0)) ); assert_eq!( parse_ical_date("20260201"),Ok(date_utc(2026, 1, 1, 0, 0, 0, 0)) );}/// `parseIcalDate` vectors read out of Node, the ISO fallback included.#[test]fn parse_ical_date_matches_node_vectors() {for (raw, expected) in [ ("20260731T000000Z", 1_785_456_000_000_i64), ("20260731T123456Z", 1_785_501_296_000),// A zone-less iCal value is read as UTC, never as a local zone. ("20260731T000000", 1_785_456_000_000), ("20260201", 1_769_904_000_000), (" 20260201 ", 1_769_904_000_000),// The ISO fallback, for the strings callers may pass. ("2026-07-31T00:00:00.000Z", 1_785_456_000_000), ("2026-07-31T00:00:00Z", 1_785_456_000_000), ] { assert_eq!( parse_ical_date(raw),Ok(expected),"parse_ical_date({raw:?})" ); } assert_eq!( parse_ical_date("not a date").unwrap_err().to_string(),"Invalid iCal date: \"not a date\"" ); assert!(parse_ical_date("").is_err());}// ── expand_rrule — DAILY ─────────────────────────────────────────────────────#[test]fn emits_one_occurrence_per_day_within_the_window() {let out = expand("FREQ=DAILY", local(2026, 1, 1, 9, 0), local(2026, 1, 1, 0, 0), local(2026, 1, 5, 23, 59), ); assert_eq!( date_keys(&out), ["2026-01-01","2026-01-02","2026-01-03","2026-01-04","2026-01-05" ] );// Wall-clock time preserved on every occurrence. assert!(hours(&out).iter().all(|(hour, _)| *hour == 9));}#[test]fn honours_interval() {let out = expand("FREQ=DAILY;INTERVAL=2", local(2026, 1, 1, 9, 0), local(2026, 1, 1, 0, 0), local(2026, 1, 6, 23, 59), ); assert_eq!(date_keys(&out), ["2026-01-01", "2026-01-03", "2026-01-05"]);}#[test]fn count_counts_occurrences_before_the_window_too() {// dtstart Jan-1; COUNT=3 ⇒ Jan-1, Jan-2, Jan-3 exist. The window starts// Jan-2, so Jan-1 is consumed by COUNT but not returned.let out = expand("FREQ=DAILY;COUNT=3", local(2026, 1, 1, 9, 0), local(2026, 1, 2, 0, 0), local(2026, 1, 31, 0, 0), ); assert_eq!(date_keys(&out), ["2026-01-02", "2026-01-03"]);}#[test]fn stops_at_until_inclusive() {let out = expand("FREQ=DAILY;UNTIL=20260103T235959", local(2026, 1, 1, 9, 0), local(2026, 1, 1, 0, 0), local(2026, 1, 31, 0, 0), ); assert_eq!(date_keys(&out), ["2026-01-01", "2026-01-02", "2026-01-03"]);}// ── expand_rrule — WEEKLY BYDAY ──────────────────────────────────────────────#[test]fn emits_each_matching_weekday_respecting_interval_weeks() {// 2026-01-05 is a Monday. MO/WE/FR, every week.let out = expand("FREQ=WEEKLY;BYDAY=MO,WE,FR", local(2026, 1, 5, 8, 0), local(2026, 1, 5, 0, 0), local(2026, 1, 11, 23, 59), ); assert_eq!(date_keys(&out), ["2026-01-05", "2026-01-07", "2026-01-09"]);}#[test]fn interval_two_skips_the_intervening_week() {let out = expand("FREQ=WEEKLY;INTERVAL=2;BYDAY=MO", local(2026, 1, 5, 8, 0), local(2026, 1, 5, 0, 0), local(2026, 2, 2, 23, 59), );// Mondays: Jan-5 (wk0), Jan-19 (wk2), Feb-2 (wk4) — Jan-12/Jan-26 skipped. assert_eq!(date_keys(&out), ["2026-01-05", "2026-01-19", "2026-02-02"]);}// ── expand_rrule — the calendar edges ────────────────────────────────────────#[test]fn monthly_skips_months_without_a_thirty_first_never_rolling_forward() {let out = expand("FREQ=MONTHLY", local(2026, 1, 31, 10, 0), local(2026, 1, 1, 0, 0), local(2026, 7, 1, 0, 0), );// Jan, Mar, May have 31 days; Feb, Apr, Jun do not. assert_eq!(date_keys(&out), ["2026-01-31", "2026-03-31", "2026-05-31"]);}#[test]fn yearly_feb_twenty_nine_only_lands_on_leap_years() {let out = expand("FREQ=YEARLY", local(2024, 2, 29, 12, 0), local(2024, 1, 1, 0, 0), local(2033, 1, 1, 0, 0), ); assert_eq!(date_keys(&out), ["2024-02-29", "2028-02-29", "2032-02-29"]);}#[test]fn keeps_the_same_local_hour_across_a_would_be_dst_boundary() {// A daily 09:00 event across the US spring-forward window (mid-March). In a// DST zone the UTC instant shifts, but the LOCAL hour must stay 09:00; in a// non-DST zone it trivially holds. This is the DST-safety property whatever// the zone.let out = expand("FREQ=DAILY", local(2026, 3, 6, 9, 0), local(2026, 3, 6, 0, 0), local(2026, 3, 12, 23, 59), ); assert_eq!(out.len(), 7); assert!(hours(&out).iter().all(|clock| *clock == (9, 0)));}// ── expand_event ─────────────────────────────────────────────────────────────#[test]fn returns_a_single_occurrence_for_a_non_recurring_event_that_overlaps() {let occ = expand_event( &EventForExpansion { starts_at: local(2026, 1, 10, 14, 0), ends_at: Some(local(2026, 1, 10, 15, 0)), rrule: None, },DateRange { from: local(2026, 1, 1, 0, 0), to: local(2026, 1, 31, 0, 0), }, ZONE, ) .expect("a valid event"); assert_eq!(occ.len(), 1); assert!(occ[0].ends_at.is_some());}#[test]fn returns_nothing_for_a_non_recurring_event_outside_the_window() {let occ = expand_event( &EventForExpansion { starts_at: local(2026, 2, 10, 14, 0), ends_at: None, rrule: None, },DateRange { from: local(2026, 1, 1, 0, 0), to: local(2026, 1, 31, 0, 0), }, ZONE, ) .expect("a valid event"); assert!(occ.is_empty());}#[test]fn expands_a_recurring_event_preserving_each_occurrences_duration() {let occ = expand_event( &EventForExpansion { starts_at: local(2026, 1, 1, 9, 0), ends_at: Some(local(2026, 1, 1, 10, 30)), rrule: Some("FREQ=DAILY;COUNT=3".to_string()), },DateRange { from: local(2026, 1, 1, 0, 0), to: local(2026, 1, 31, 0, 0), }, ZONE, ) .expect("a valid event"); assert_eq!(occ.len(), 3);for o in &occ {let duration_min = (o.ends_at.expect("an end") - o.starts_at) / 60_000; assert_eq!(duration_min, 90); }}/// An occurrence that STARTS before the window but ENDS inside it is included —/// which is what the backwards widening by one duration is for.#[test]fn includes_an_occurrence_that_spans_into_the_window() {let occ = expand_event( &EventForExpansion { starts_at: local(2026, 1, 1, 22, 0), ends_at: Some(local(2026, 1, 2, 2, 0)), rrule: Some("FREQ=DAILY".to_string()), },DateRange { from: local(2026, 1, 3, 0, 0), to: local(2026, 1, 3, 12, 0), }, ZONE, ) .expect("a valid event");// The occurrence starting 22:00 on the 2nd runs to 02:00 on the 3rd, and// the one starting 22:00 on the 3rd begins inside the window's last hours. assert_eq!( date_keys(&occ.iter().map(|o| o.starts_at).collect::<Vec<_>>()), ["2026-01-02"] );}/// An empty rule string is "not recurring" in JavaScript (`!""` is true), never/// a parse error.#[test]fn an_empty_rule_is_not_a_parse_error() {let occ = expand_event( &EventForExpansion { starts_at: local(2026, 1, 10, 14, 0), ends_at: None, rrule: Some(String::new()), },DateRange { from: local(2026, 1, 1, 0, 0), to: local(2026, 1, 31, 0, 0), }, ZONE, ) .expect("a valid event"); assert_eq!(occ.len(), 1);}// ─────────────────────────────────────────────────────────────────────────────// `rruleZone.test.ts` — the duplication bug, pinned.//// A materialised occurrence's row id is DERIVED from// `(recurrence, occurrence_at)` precisely so the phone and the server converge// on ONE row instead of racing to mint two. That only holds if both compute the// same `occurrence_at`.// ─────────────────────────────────────────────────────────────────────────────fn iso_expand(rule: &str, dtstart: &str, from: &str, to: &str, zone: &str) -> Vec<String> {let at = |iso: &str| crate::js::parse_date_ms(iso).expect("an ISO instant"); expand_rrule( rule, at(dtstart),DateRange { from: at(from), to: at(to), }, zone, ) .expect("a valid rule") .into_iter() .map(|ms| to_iso_string(ms).expect("a renderable instant")) .collect()}#[test]fn monthly_nine_am_ist_anchored_in_february_the_reviewers_case() {// Anchored in Berlin's WINTER, swept in its summer: the offset delta across// the March transition is exactly what used to shift every occurrence.let out = iso_expand("FREQ=MONTHLY;BYMONTHDAY=2","2026-02-02T03:30:00.000Z", // 09:00 IST"2026-08-01T00:00:00.000Z","2026-10-01T00:00:00.000Z","Asia/Kolkata", ); assert_eq!( out, ["2026-08-02T03:30:00.000Z", "2026-09-02T03:30:00.000Z"] );}#[test]fn daily_across_europes_spring_forward_ten_of_ten_used_to_diverge() {let out = iso_expand("FREQ=DAILY","2026-03-25T03:30:00.000Z","2026-03-25T00:00:00.000Z","2026-04-04T00:00:00.000Z","Asia/Kolkata", ); assert_eq!(out.len(), 10);// Kolkata has no DST, so every instant holds the same clock time.let times: std::collections::BTreeSet<&str> = out.iter().map(|iso| &iso[11..]).collect(); assert_eq!(times.into_iter().collect::<Vec<_>>(), ["03:30:00.000Z"]);}#[test]fn weekly_byday_mo_with_a_2230z_anchor_where_the_zones_disagree_about_the_day() {// The nastiest case: 22:30Z is the 4th in UTC and already the 5th in IST,// so two runtimes did not merely shift the time, they picked different// DATES — disjoint sets, not neighbouring ones.let out = iso_expand("FREQ=WEEKLY;BYDAY=MO","2026-10-04T22:30:00.000Z","2026-10-01T00:00:00.000Z","2026-10-25T00:00:00.000Z","Asia/Kolkata", ); assert!(out.len() > 1);// In Asia/Kolkata that anchor reads Monday 5 October at 04:00 — so Mondays.for iso in &out {let ms = crate::js::parse_date_ms(iso).expect("an ISO instant");let p = zoned_parts(ms, "Asia/Kolkata").expect("a known zone"); assert_eq!(crate::zoned_clock::weekday_of_day_number(crate::zoned_clock::day_number(p.year, p.month, p.day) ),1,"{iso} is not a Monday in Asia/Kolkata" ); }}#[test]fn every_generator_branch_expands_to_something() {// A sweep of shapes rather than one, because the bug lived in four separate// branches of the generator (daily / weekly / monthly / yearly).for rule in ["FREQ=DAILY;INTERVAL=3","FREQ=WEEKLY;INTERVAL=2","FREQ=MONTHLY;BYMONTHDAY=31","FREQ=YEARLY","FREQ=WEEKLY;BYDAY=MO,WE,FR", ] {let out = iso_expand( rule,"2026-01-31T03:30:00.000Z","2026-01-01T00:00:00.000Z","2027-06-01T00:00:00.000Z","Asia/Kolkata", ); assert!(!out.is_empty(), "{rule} expanded to nothing"); }}#[test]fn next_occurrence_after_answers_the_zone_argument() {let at = |iso: &str| crate::js::parse_date_ms(iso).expect("an ISO instant");let got = next_occurrence_after("FREQ=MONTHLY;BYMONTHDAY=2", at("2026-02-02T03:30:00.000Z"), at("2026-08-23T00:00:00.000Z"),"Asia/Kolkata", ) .expect("a valid rule") .and_then(to_iso_string); assert_eq!(got.as_deref(), Some("2026-09-02T03:30:00.000Z"));}#[test]fn a_rule_expanded_in_europe_berlin_holds_0230_through_both_transitions() {// Not "the server's zone is wrong" — this is a workspace that really is in// Berlin, where the wall clock is the thing the person set and the INSTANT// is what has to move. 02:30 local is also the hardest pair of days in the// year: on 29 March it does not exist (the clock jumps 02:00 → 03:00) and// on 25 October it happens twice. Both must resolve deterministically, and// to the same instant on every runtime, or the two producers derive// different ids for the same day.let out = iso_expand("FREQ=DAILY","2026-03-01T01:30:00.000Z", // 02:30 CET"2026-03-01T00:00:00.000Z","2026-10-26T00:00:00.000Z","Europe/Berlin", );// The gap day: 02:30 does not exist, and the answer is the instant the// clock actually reads 03:30 — one deterministic choice, not a refusal. assert!(out.iter().any(|iso| iso == "2026-03-29T01:30:00.000Z"));// The ambiguous day: 02:30 happens twice; the first is taken. assert!(out.iter().any(|iso| iso == "2026-10-25T01:30:00.000Z"));// Summer occurrences sit an hour earlier in UTC, which is the whole point// of holding the WALL clock rather than the instant. assert!(out.iter().any(|iso| iso == "2026-07-01T00:30:00.000Z"));}/// The engine cannot read a process zone, so it refuses an unknown one rather/// than falling back to one.#[test]fn an_unknown_zone_is_refused_never_replaced_by_the_machines() {let refusal = expand_rrule("FREQ=DAILY",0,DateRange { from: 0, to: 1 },"Mars/Olympus_Mons", ) .expect_err("no such zone"); assert!(refusal.to_string().contains("not a known time zone"));}/// RULE: a repeating todo's rule reads the same on the phone and the Worker/// (decision 7): the shared vectors, which the Worker's recurrence.test.ts reads.#[test]fn todo_rules_read_as_the_shared_vectors_say() {let file: serde_json::Value = serde_json::from_str(include_str!("../vectors/todo_rule.json")).unwrap();for case in file["cases"].as_array().unwrap() {let got = parse_todo_rule(case["rule"].as_str().unwrap()).map(|r| r.to_json());match case.get("refused").and_then(serde_json::Value::as_str) {Some(words) => assert_eq!(got, Err(words.to_string()), "{case}"),None => assert_eq!(got, Ok(case["want"].clone()), "{case}"), } }}