Cotton code
1084 lines · 36.7 KB · RustRaw
//! Ported case-for-case from `packages/core/__tests__/engine/eventEdits.test.ts`,//! plus the Node vectors.//!//! These planners exist because there are TWO writers of `cotton_events` — the//! phone's service layer and the server's MCP — and two implementations of//! "editing this Tuesday means a new row that claims Tuesday's instant" would//! eventually disagree. So the decisions are asserted here, once, against the//! live shapes: weekly "Vicky" (`FREQ=WEEKLY`, 12:00 Asia/Kolkata on a Friday),//! synced to Google as `7pfkedoofe98utr5qbffl34oab`.use serde_json::json;use super::*;const NOW: &str = "2026-09-04T10:00:00.000Z";const KOLKATA: &str = "Asia/Kolkata";fn vicky() -> EventRowForPlan {    EventRowForPlan {        id: "ev-vicky".into(),        collection_id: Some("cal-1".into()),        title: "Vicky".into(),        notes: None,        location: None,        starts_at: "2026-09-04T06:30:00.000Z".into(),        ends_at: Some("2026-09-04T07:30:00.000Z".into()),        all_day: false,        rrule: Some("FREQ=WEEKLY".into()),        exdates: None,        series_id: None,        original_starts_at: None,        gcal_id: Some("7pfkedoofe98utr5qbffl34oab".into()),        sync_state: Some("synced".into()),        trashed_at: None,    }}/// The same series, living only in Cotton.fn local_vicky() -> EventRowForPlan {    EventRowForPlan {        gcal_id: None,        sync_state: None,        ..vicky()    }}fn edit<'a>(    master: &'a EventRowForPlan,    occurrence_at: &'a str,    patch: &'a OccurrencePatch,    new_id: &'a str,) -> OccurrenceEdit<'a> {    OccurrenceEdit {        master,        existing: None,        occurrence_at,        patch,        new_id,        now: NOW,    }}/// A patch as JSON, so a vector can be written as the TypeScript printed it —/// key ORDER included, which `preserve_order` makes observable.fn as_json(patch: &RowPatch) -> serde_json::Value {    serde_json::Value::Object(patch.clone())}fn keys(patch: &RowPatch) -> Vec<&str> {    patch.keys().map(String::as_str).collect()}// ── planOccurrenceEdit ───────────────────────────────────────────────────────#[test]fn mints_an_exception_that_claims_the_instant_and_keeps_the_series_duration() {    let master = vicky();    let patch = OccurrencePatch {        starts_at: Some("2026-09-08T06:30:00.000Z".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-04T06:30:00.000Z", &patch, "ev-new"))        .expect("a readable master");    assert!(plan.created);    assert_eq!(plan.exception_id, "ev-new");    for (key, expected) in [        ("id", json!("ev-new")),        ("collection_id", json!("cal-1")),        ("title", json!("Vicky")),        ("series_id", json!("ev-vicky")),        ("original_starts_at", json!("2026-09-04T06:30:00.000Z")),        ("starts_at", json!("2026-09-08T06:30:00.000Z")),        // one hour, carried from the master rather than re-stated by the caller        ("ends_at", json!("2026-09-08T07:30:00.000Z")),        // An exception does not repeat and is in nobody's bin.        ("rrule", json!(null)),        ("exdates", json!(null)),        ("trashed_at", json!(null)),        // Google identity is never copied, and nothing pushes (Days, 20 Nov        // 2026: nothing writes to Google), so no pending mark.        ("gcal_id", json!(null)),        ("gcal_etag", json!(null)),        ("sync_state", json!(null)),    ] {        assert_eq!(plan.patch.get(key), Some(&expected), "column {key}");    }    assert!(plan.master_patch.is_empty());}/// It never leaves the file, so it is never marked.#[test]fn leaves_an_exception_of_a_cotton_only_series_unmarked() {    let master = local_vicky();    let patch = OccurrencePatch {        title: Some("Vicky, moved".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-04T06:30:00.000Z", &patch, "ev-new"))        .expect("a readable master");    assert_eq!(plan.patch.get("sync_state"), Some(&json!(null)));}/// RULE (Days, 20 Nov 2026): nothing pushes to a calendar door, so an/// exception of a series a CalDAV server holds is not marked pending either.#[test]fn leaves_an_exception_of_a_caldav_series_unmarked_too() {    let master = EventRowForPlan {        gcal_id: None,        ..vicky()    };    let patch = OccurrencePatch {        title: Some("Vicky, moved".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-04T06:30:00.000Z", &patch, "ev-new"))        .expect("a readable master");    assert_eq!(plan.patch.get("sync_state"), Some(&json!(null)));    assert!(plan.master_patch.is_empty());}#[test]fn keeps_an_open_ended_series_open_ended() {    let master = EventRowForPlan {        ends_at: None,        ..vicky()    };    let patch = OccurrencePatch::default();    let plan = plan_occurrence_edit(edit(&master, "2026-09-04T06:30:00.000Z", &patch, "ev-new"))        .expect("a readable master");    assert_eq!(plan.patch.get("ends_at"), Some(&json!(null)));}#[test]fn patches_the_exception_that_is_already_there_rather_than_minting_a_second_claim() {    let master = vicky();    let existing = EventRowForPlan {        id: "ev-vicky-0904".into(),        rrule: None,        series_id: Some("ev-vicky".into()),        original_starts_at: Some("2026-09-04T06:30:00.000Z".into()),        starts_at: "2026-09-08T06:30:00.000Z".into(),        ends_at: Some("2026-09-08T07:30:00.000Z".into()),        gcal_id: Some("7pfkedoofe98utr5qbffl34oab_20260904T063000Z".into()),        ..vicky()    };    let patch = OccurrencePatch {        title: Some("Vicky (rescheduled)".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(OccurrenceEdit {        master: &master,        existing: Some(&existing),        occurrence_at: "2026-09-04T06:30:00.000Z",        patch: &patch,        new_id: "ev-unused",        now: NOW,    })    .expect("a readable master");    assert!(!plan.created);    assert_eq!(plan.exception_id, "ev-vicky-0904");    assert_eq!(        as_json(&plan.patch),        json!({            "updated_at": NOW,            "title": "Vicky (rescheduled)",        })    );}/// Clearing notes is not the same as leaving them.#[test]fn carries_an_explicit_null_through() {    let master = EventRowForPlan {        notes: Some("bring the file".into()),        ..vicky()    };    let patch = OccurrencePatch {        notes: FieldChange::Cleared,        ..Default::default()    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-04T06:30:00.000Z", &patch, "ev-new"))        .expect("a readable master");    assert_eq!(plan.patch.get("notes"), Some(&json!(null)));}// ── planOccurrenceCancel ─────────────────────────────────────────────────────#[test]fn adds_the_instant_to_the_masters_exdates_and_marks_nothing() {    let master = vicky();    let plan = plan_occurrence_cancel(&master, None, "2026-09-11T06:30:00.000Z", NOW)        .expect("a readable instant");    assert!(!plan.already_cancelled);    assert_eq!(        as_json(&plan.master_patch),        json!({            "exdates": ["2026-09-11T06:30:00.000Z"],            "updated_at": NOW,        })    );    assert_eq!(plan.trash_exception_id, None);    assert_eq!(plan.remove_exception_id, None);}#[test]fn writes_nothing_when_the_occurrence_is_already_cancelled() {    let master = EventRowForPlan {        exdates: Some(vec!["2026-09-11T06:30:00.000Z".into()]),        ..vicky()    };    // A different SPELLING of the same instant — `withExdate` compares instants.    let plan = plan_occurrence_cancel(&master, None, "2026-09-11T06:30:00Z", NOW)        .expect("a readable instant");    assert!(plan.already_cancelled);    assert!(plan.master_patch.is_empty());}/// The push deletes its instance.#[test]fn trashes_a_synced_exception_standing_on_that_instant() {    let master = vicky();    let exception = EventRowForPlan {        id: "ev-vicky-0904".into(),        rrule: None,        series_id: Some("ev-vicky".into()),        original_starts_at: Some("2026-09-04T06:30:00.000Z".into()),        gcal_id: Some("7pfkedoofe98utr5qbffl34oab_20260904T063000Z".into()),        ..vicky()    };    let plan = plan_occurrence_cancel(&master, Some(&exception), "2026-09-04T06:30:00.000Z", NOW)        .expect("a readable instant");    assert_eq!(plan.trash_exception_id.as_deref(), Some("ev-vicky-0904"));    assert_eq!(plan.remove_exception_id, None);}/// It has nowhere else to be.#[test]fn removes_a_cotton_only_exception_outright() {    let master = local_vicky();    let exception = EventRowForPlan {        id: "ev-local-exc".into(),        rrule: None,        series_id: Some("ev-vicky".into()),        original_starts_at: Some("2026-09-04T06:30:00.000Z".into()),        ..local_vicky()    };    let plan = plan_occurrence_cancel(&master, Some(&exception), "2026-09-04T06:30:00.000Z", NOW)        .expect("a readable instant");    assert_eq!(plan.remove_exception_id.as_deref(), Some("ev-local-exc"));    assert_eq!(plan.trash_exception_id, None);    assert_eq!(plan.master_patch.get("sync_state"), None);}// ── planEventDelete ──────────────────────────────────────────────────────────#[test]fn trashes_a_google_linked_event_rather_than_dropping_it() {    let plan = plan_event_delete(&vicky(), NOW);    assert_eq!(plan.trash, vec!["ev-vicky".to_string()]);    assert_eq!(        as_json(&plan.trash_patch),        json!({ "trashed_at": NOW, "updated_at": NOW })    );}/// RULE: A Cotton-only event deleted waits in the bin like a synced one — trashed, never dropped — and goes nowhere else: no pending mark, since Google has nothing to hear.#[test]fn trashes_a_cotton_only_event_too() {    let plan = plan_event_delete(&local_vicky(), NOW);    assert_eq!(plan.trash, vec!["ev-vicky".to_string()]);    assert_eq!(as_json(&plan.trash_patch), json!({ "trashed_at": NOW, "updated_at": NOW }));}#[test]fn does_not_re_mark_a_row_whose_edit_is_already_in_flight() {    let event = EventRowForPlan {        sync_state: Some("pending".into()),        ..vicky()    };    let plan = plan_event_delete(&event, NOW);    assert_eq!(        as_json(&plan.trash_patch),        json!({ "trashed_at": NOW, "updated_at": NOW })    );}// ── pendingMarkPatch ─────────────────────────────────────────────────────────/// RULE (Days, 20 Nov 2026): nothing writes to Google or a CalDAV server, and no code read a pending mark, so no edit is marked: a mark claiming a push would be a quiet lie.#[test]fn marks_no_row_since_nothing_pushes() {    assert!(pending_mark_patch(SyncIdentity {        gcal_id: Some("g1"),        sync_state: Some("synced"),    })    .is_empty());    assert!(pending_mark_patch(SyncIdentity {        gcal_id: None,        sync_state: None,    })    .is_empty());    assert!(pending_mark_patch(SyncIdentity {        gcal_id: Some("g1"),        sync_state: Some("pending"),    })    .is_empty());}// ── planSeriesMove ───────────────────────────────────────────────────────────/// Weekly "Vicky" with 11 Sep cancelled.fn with_history() -> EventRowForPlan {    EventRowForPlan {        exdates: Some(vec!["2026-09-11T06:30:00.000Z".into()]),        ..vicky()    }}/// 4 Sep moved to the 8th.fn moved() -> EventRowForPlan {    EventRowForPlan {        id: "ev-vicky-0904".into(),        rrule: None,        series_id: Some("ev-vicky".into()),        original_starts_at: Some("2026-09-04T06:30:00.000Z".into()),        starts_at: "2026-09-08T06:30:00.000Z".into(),        gcal_id: Some("7pfkedoofe98utr5qbffl34oab_20260904T063000Z".into()),        ..vicky()    }}#[test]fn re_keys_the_exdates_and_the_exceptions_claims_when_the_series_time_moves() {    // 12:00 → 13:00 Kolkata. Leave the two pointers where they were and the    // rule now fires at 13:00 on instants neither of them names: the cancelled    // 11 Sep comes back, and 4 Sep is drawn twice.    let plan = plan_series_move(        &with_history(),        &[moved()],        "2026-09-04T07:30:00.000Z",        KOLKATA,    )    .expect("a known zone");    assert_eq!(        as_json(&plan.master_patch),        json!({ "exdates": ["2026-09-11T07:30:00.000Z"] })    );    assert_eq!(plan.exception_patches.len(), 1);    assert_eq!(plan.exception_patches[0].id, "ev-vicky-0904");    assert_eq!(        as_json(&plan.exception_patches[0].patch),        json!({ "original_starts_at": "2026-09-04T07:30:00.000Z" })    );}#[test]fn re_keys_when_the_series_moves_to_another_day_keeping_the_same_offsets() {    // Friday 4 Sep → Saturday 5 Sep: every occurrence slides one day.    let plan = plan_series_move(        &with_history(),        &[moved()],        "2026-09-05T06:30:00.000Z",        KOLKATA,    )    .expect("a known zone");    assert_eq!(        as_json(&plan.master_patch),        json!({ "exdates": ["2026-09-12T06:30:00.000Z"] })    );    assert_eq!(        as_json(&plan.exception_patches[0].patch),        json!({ "original_starts_at": "2026-09-05T06:30:00.000Z" })    );}/// The person put it there.#[test]fn leaves_an_exceptions_own_time_alone() {    let plan = plan_series_move(        &with_history(),        &[moved()],        "2026-09-04T07:30:00.000Z",        KOLKATA,    )    .expect("a known zone");    assert_eq!(        keys(&plan.exception_patches[0].patch),        ["original_starts_at"]    );}#[test]fn re_anchors_on_the_wall_clock_so_a_move_across_a_dst_change_stays_on_the_hour() {    // Europe/London: a weekly 09:00 series anchored in BST, moved to 10:00.    // Its October occurrence is already in GMT, so a millisecond delta would    // put that exdate at 09:00 — an hour off the occurrence it removes, and the    // cancelled call would simply come back.    let london = EventRowForPlan {        starts_at: "2026-09-09T08:00:00.000Z".into(), // 09:00 BST        ends_at: None,        exdates: Some(vec!["2026-10-28T09:00:00.000Z".into()]), // 09:00 GMT        ..vicky()    };    let plan = plan_series_move(        &london,        &[],        "2026-09-09T09:00:00.000Z", // 10:00 BST        "Europe/London",    )    .expect("a known zone");    // 10:00 GMT on the October occurrence, not 10:00 BST-as-instant.    assert_eq!(        as_json(&plan.master_patch),        json!({ "exdates": ["2026-10-28T10:00:00.000Z"] })    );}#[test]fn writes_nothing_when_the_start_did_not_actually_move() {    let plan = plan_series_move(&with_history(), &[moved()], &vicky().starts_at, KOLKATA)        .expect("a known zone");    assert!(plan.master_patch.is_empty());    assert!(plan.exception_patches.is_empty());}#[test]fn touches_no_exdates_on_a_series_that_has_none() {    let plan =        plan_series_move(&vicky(), &[], "2026-09-04T07:30:00.000Z", KOLKATA).expect("a known zone");    assert!(plan.master_patch.is_empty());}// ─────────────────────────────────────────────────────────────────────────────// Node vectors — every expected value below was PRINTED by running the// TypeScript (`packages/core`, `npx tsx`), never reasoned out.// ─────────────────────────────────────────────────────────────────────────────/// The whole minted row, KEY ORDER included: an op's patch is stored as text,/// so the order the TypeScript's object literal produces is observable.#[test]fn vector_the_minted_exception_row_is_byte_for_byte_the_typescripts() {    let master = vicky();    let patch = OccurrencePatch::default();    let plan = plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &patch, "ev-a"))        .expect("a readable master");    assert_eq!(        as_json(&plan.patch),        json!({            "id": "ev-a",            "collection_id": "cal-1",            "title": "Vicky",            "notes": null,            "location": null,            "starts_at": "2026-09-11T06:30:00.000Z",            "ends_at": "2026-09-11T07:30:00.000Z",            "all_day": false,            "rrule": null,            "exdates": null,            "trashed_at": null,            "series_id": "ev-vicky",            "original_starts_at": "2026-09-11T06:30:00.000Z",            "gcal_id": null,            "gcal_etag": null,            "sync_state": null,            "organizer_is_self": true,            "my_response": null,            "created_at": "2026-09-04T10:00:00.000Z",            "updated_at": "2026-09-04T10:00:00.000Z"        })    );    assert_eq!(        keys(&plan.patch),        [            "id",            "collection_id",            "title",            "notes",            "location",            "starts_at",            "ends_at",            "all_day",            "rrule",            "exdates",            "trashed_at",            "series_id",            "original_starts_at",            "gcal_id",            "gcal_etag",            "sync_state",            "organizer_is_self",            "my_response",            "created_at",            "updated_at"        ]    );}/// A 90-minute master and a start carrying a fraction of a second: the/// milliseconds ride along.#[test]fn vector_the_derived_end_carries_sub_second_precision() {    let master = EventRowForPlan {        ends_at: Some("2026-09-04T08:00:00.000Z".into()),        ..vicky()    };    let patch = OccurrencePatch {        starts_at: Some("2026-09-11T06:30:00.250Z".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &patch, "ev-b"))        .expect("a readable master");    assert_eq!(        plan.patch.get("ends_at"),        Some(&json!("2026-09-11T08:00:00.250Z"))    );}/// `starts_at` is stored VERBATIM and `ends_at` is derived through/// `toISOString`, so an offset-bearing start leaves the row holding two/// spellings of the same clock. That is the TypeScript's behaviour and a/// caller that dislikes it has to normalise before calling.#[test]fn vector_an_offset_bearing_start_is_not_normalised_but_the_derived_end_is() {    let master = vicky();    let patch = OccurrencePatch {        starts_at: Some("2026-09-11T12:00:00+05:30".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &patch, "ev-c"))        .expect("a readable master");    assert_eq!(        plan.patch.get("starts_at"),        Some(&json!("2026-09-11T12:00:00+05:30"))    );    assert_eq!(        plan.patch.get("ends_at"),        Some(&json!("2026-09-11T07:30:00.000Z"))    );}/// A master whose end PRECEDES its start: the negative duration is carried/// rather than clamped, because the planner is not the place a broken row gets/// quietly repaired.#[test]fn vector_a_negative_duration_is_carried() {    let master = EventRowForPlan {        ends_at: Some("2026-09-04T05:30:00.000Z".into()),        ..vicky()    };    let patch = OccurrencePatch::default();    let plan = plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &patch, "ev-d"))        .expect("a readable master");    assert_eq!(        plan.patch.get("ends_at"),        Some(&json!("2026-09-11T05:30:00.000Z"))    );}#[test]fn vector_every_field_patched_on_a_cotton_only_master() {    let master = local_vicky();    let patch = OccurrencePatch {        title: Some("moved".into()),        starts_at: Some("2026-09-12T06:30:00.000Z".into()),        ends_at: FieldChange::Cleared,        all_day: Some(true),        location: FieldChange::Set("office".into()),        notes: FieldChange::Set("bring the file".into()),    };    let plan = plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &patch, "ev-e"))        .expect("a readable master");    assert_eq!(        as_json(&plan.patch),        json!({            "id": "ev-e",            "collection_id": "cal-1",            "title": "moved",            "notes": "bring the file",            "location": "office",            "starts_at": "2026-09-12T06:30:00.000Z",            "ends_at": null,            "all_day": true,            "rrule": null,            "exdates": null,            "trashed_at": null,            "series_id": "ev-vicky",            "original_starts_at": "2026-09-11T06:30:00.000Z",            "gcal_id": null,            "gcal_etag": null,            "sync_state": null,            "organizer_is_self": true,            "my_response": null,            "created_at": "2026-09-04T10:00:00.000Z",            "updated_at": "2026-09-04T10:00:00.000Z"        })    );}/// The update branch's key order is `updated_at` first, then the columns in/// the order the TypeScript tests them — never the order the caller wrote them.#[test]fn vector_the_update_patchs_key_order_is_the_planners_not_the_callers() {    let master = vicky();    let existing = EventRowForPlan {        id: "ev-x".into(),        gcal_id: Some("g_inst".into()),        sync_state: Some("synced".into()),        ..vicky()    };    let patch = OccurrencePatch {        notes: FieldChange::Cleared,        location: FieldChange::Set("office".into()),        all_day: Some(false),        ends_at: FieldChange::Set("2026-09-08T07:30:00.000Z".into()),        starts_at: Some("2026-09-08T06:30:00.000Z".into()),        title: Some("t".into()),    };    let plan = plan_occurrence_edit(OccurrenceEdit {        master: &master,        existing: Some(&existing),        occurrence_at: "2026-09-04T06:30:00.000Z",        patch: &patch,        new_id: "unused",        now: NOW,    })    .expect("a readable master");    assert_eq!(        keys(&plan.patch),        [            "updated_at",            "title",            "starts_at",            "ends_at",            "all_day",            "location",            "notes",        ]    );    assert_eq!(        as_json(&plan.patch),        json!({            "updated_at": "2026-09-04T10:00:00.000Z",            "title": "t",            "starts_at": "2026-09-08T06:30:00.000Z",            "ends_at": "2026-09-08T07:30:00.000Z",            "all_day": false,            "location": "office",            "notes": null,        })    );}#[test]fn vector_an_existing_local_exception_takes_only_the_stamp() {    let master = vicky();    let existing = EventRowForPlan {        id: "ev-y".into(),        ..local_vicky()    };    let patch = OccurrencePatch {        title: Some("t".into()),        ..Default::default()    };    let plan = plan_occurrence_edit(OccurrenceEdit {        master: &master,        existing: Some(&existing),        occurrence_at: "2026-09-04T06:30:00.000Z",        patch: &patch,        new_id: "unused",        now: NOW,    })    .expect("a readable master");    assert_eq!(        as_json(&plan.patch),        json!({ "updated_at": "2026-09-04T10:00:00.000Z", "title": "t" })    );}/// A pure library may not panic on a row a stranger's calendar wrote: a master/// whose `starts_at` cannot be read would make `new Date(NaN).toISOString()`/// throw over there, so it is an error here — with the runtime's own sentence.#[test]fn an_unreadable_master_instant_is_an_error_rather_than_a_panic() {    let master = EventRowForPlan {        starts_at: "not a date".into(),        ..vicky()    };    let patch = OccurrencePatch::default();    assert_eq!(        plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &patch, "ev-z")),        Err(EventEditsError::InvalidTimeValue)    );    assert_eq!(        EventEditsError::InvalidTimeValue.to_string(),        "Invalid time value"    );}/// An open-ended master never reaches the arithmetic, so the same unreadable/// row plans fine — exactly as the TypeScript's `master.ends_at ? … : null`/// short-circuit has it.#[test]fn an_open_ended_master_never_reaches_the_arithmetic() {    let master = EventRowForPlan {        starts_at: "not a date".into(),        ends_at: None,        ..vicky()    };    let patch = OccurrencePatch::default();    let plan = plan_occurrence_edit(edit(&master, "also not a date", &patch, "ev-z"))        .expect("no arithmetic to do");    assert_eq!(plan.patch.get("ends_at"), Some(&json!(null)));}// ── planOccurrenceCancel vectors ─────────────────────────────────────────────#[test]fn vector_the_new_exdate_list_is_sorted() {    let master = EventRowForPlan {        exdates: Some(vec![            "2026-09-25T06:30:00.000Z".into(),            "2026-09-11T06:30:00.000Z".into(),        ]),        ..vicky()    };    let plan = plan_occurrence_cancel(&master, None, "2026-09-18T06:30:00.000Z", NOW)        .expect("a readable instant");    assert_eq!(        as_json(&plan.master_patch),        json!({            "exdates": [                "2026-09-11T06:30:00.000Z",                "2026-09-18T06:30:00.000Z",                "2026-09-25T06:30:00.000Z"            ],            "updated_at": "2026-09-04T10:00:00.000Z",        })    );}/// An exdate already in the list keeps the SPELLING it was written with; only/// the new one is minted through `toISOString`. The sort is then a plain/// code-unit sort over two different shapes, and `…09-11T12:00:00+05:30` lands/// first because `11` precedes `18`, not because of anything about offsets.#[test]fn vector_an_existing_exdates_own_spelling_survives() {    let master = EventRowForPlan {        exdates: Some(vec!["2026-09-11T12:00:00+05:30".into()]),        ..vicky()    };    let plan = plan_occurrence_cancel(&master, None, "2026-09-18T06:30:00.000Z", NOW)        .expect("a readable instant");    assert_eq!(        plan.master_patch.get("exdates"),        Some(&json!([            "2026-09-11T12:00:00+05:30",            "2026-09-18T06:30:00.000Z"        ]))    );}/// `alreadyCancelled` is about the WHOLE act, not just the list: an exception/// still standing on the instant means there is work to do, so the master's/// patch is written even though its exdates did not grow.#[test]fn vector_an_exception_on_an_already_cancelled_instant_is_still_work() {    let master = EventRowForPlan {        exdates: Some(vec!["2026-09-11T06:30:00.000Z".into()]),        ..vicky()    };    let exception = EventRowForPlan {        id: "ev-exc".into(),        gcal_id: Some("g_inst".into()),        ..vicky()    };    let plan = plan_occurrence_cancel(&master, Some(&exception), "2026-09-11T06:30:00.000Z", NOW)        .expect("a readable instant");    assert!(!plan.already_cancelled);    assert_eq!(        as_json(&plan.master_patch),        json!({            "exdates": ["2026-09-11T06:30:00.000Z"],            "updated_at": "2026-09-04T10:00:00.000Z",        })    );    assert_eq!(plan.trash_exception_id.as_deref(), Some("ev-exc"));}#[test]fn vector_a_master_already_pending_is_not_re_marked() {    let master = EventRowForPlan {        sync_state: Some("pending".into()),        ..vicky()    };    let plan = plan_occurrence_cancel(&master, None, "2026-09-11T06:30:00.000Z", NOW)        .expect("a readable instant");    assert_eq!(        as_json(&plan.master_patch),        json!({            "exdates": ["2026-09-11T06:30:00.000Z"],            "updated_at": "2026-09-04T10:00:00.000Z"        })    );}/// `withExdate` refuses an instant it cannot read, and the sentence is its own.#[test]fn cancelling_an_unreadable_instant_is_refused_with_the_typescripts_sentence() {    let error = plan_occurrence_cancel(&vicky(), None, "not a date", NOW)        .expect_err("an unreadable instant");    assert_eq!(error.to_string(), "not an instant: \"not a date\"");}// ── planEventDelete / pendingMarkPatch vectors ───────────────────────────────/// A conflicted row is not re-marked on delete either: nothing pushes.#[test]fn vector_a_conflicted_row_is_not_re_marked_on_delete() {    let event = EventRowForPlan {        sync_state: Some("conflict".into()),        ..vicky()    };    let plan = plan_event_delete(&event, NOW);    assert_eq!(        as_json(&plan.trash_patch),        json!({            "trashed_at": "2026-09-04T10:00:00.000Z",            "updated_at": "2026-09-04T10:00:00.000Z",        })    );}#[test]fn vector_the_pending_mark_reads_gcal_id_first_and_sync_state_second() {    // Nothing is marked, whatever the row: nothing pushes.    for state in [Some("synced"), Some("conflict"), None] {        assert!(            pending_mark_patch(SyncIdentity {                gcal_id: Some("g"),                sync_state: state,            })            .is_empty(),            "sync_state {state:?}"        );    }    // No `gcal_id` and no door's state — a row only Cotton holds: nothing to    // push. (A `gcal_id`-less row with a state is a CalDAV row, and goes    // pending: a_caldav_row_goes_pending_on_an_edit_and_a_cotton_only_row_does_not.)    assert!(pending_mark_patch(SyncIdentity {        gcal_id: None,        sync_state: None,    })    .is_empty());}// ── planSeriesMove vectors ───────────────────────────────────────────────────/// Three exdates and four exceptions at once, moved to a sub-second anchor:/// the milliseconds come off the ANCHOR (`Intl` has no sub-second field), the/// exdates come back sorted, and the two exceptions with no readable claim are/// silently dropped rather than patched with nonsense.#[test]fn vector_a_whole_series_re_keyed_at_once_in_kolkata() {    let master = EventRowForPlan {        exdates: Some(vec![            "2026-09-25T06:30:00.000Z".into(),            "2026-09-11T06:30:00.000Z".into(),            "2026-10-30T06:30:00.000Z".into(),        ]),        ..vicky()    };    let exceptions = [        EventRowForPlan {            id: "e1".into(),            original_starts_at: Some("2026-09-11T06:30:00.000Z".into()),            ..vicky()        },        EventRowForPlan {            id: "e2".into(),            original_starts_at: Some("2026-10-30T06:30:00.000Z".into()),            ..vicky()        },        EventRowForPlan {            id: "e3".into(),            original_starts_at: None,            ..vicky()        },        EventRowForPlan {            id: "e4".into(),            original_starts_at: Some("not a date".into()),            ..vicky()        },    ];    let plan = plan_series_move(&master, &exceptions, "2026-09-04T02:15:30.125Z", KOLKATA)        .expect("a known zone");    assert_eq!(        as_json(&plan.master_patch),        json!({            "exdates": [                "2026-09-11T02:15:30.125Z",                "2026-09-25T02:15:30.125Z",                "2026-10-30T02:15:30.125Z"            ]        })    );    assert_eq!(        plan.exception_patches            .iter()            .map(|patch| (patch.id.as_str(), as_json(&patch.patch)))            .collect::<Vec<_>>(),        vec![            (                "e1",                json!({ "original_starts_at": "2026-09-11T02:15:30.125Z" })            ),            (                "e2",                json!({ "original_starts_at": "2026-10-30T02:15:30.125Z" })            ),        ]    );}/// The proof the shift is WALL CLOCK and not a delta: a 09:00 EDT series moved/// to 11:30 EDT leaves its October exdate at 15:30Z and its NOVEMBER one at/// 16:30Z, because November is EST. A millisecond delta would have put both an/// hour apart from the occurrence they remove.#[test]fn vector_a_move_across_the_new_york_fall_back() {    let master = EventRowForPlan {        starts_at: "2026-10-02T13:00:00.000Z".into(), // 09:00 EDT        exdates: Some(vec![            "2026-11-06T14:00:00.000Z".into(), // 09:00 EST            "2026-10-09T13:00:00.000Z".into(), // 09:00 EDT        ]),        ..vicky()    };    let plan = plan_series_move(        &master,        &[],        "2026-10-02T15:30:00.000Z", // 11:30 EDT        "America/New_York",    )    .expect("a known zone");    assert_eq!(        plan.master_patch.get("exdates"),        Some(&json!([            "2026-10-09T15:30:00.000Z",            "2026-11-06T16:30:00.000Z"        ]))    );}/// Backwards across a month boundary, in a zone at +05:45 — the day delta is/// negative and the anchor's new wall time is what every occurrence takes.#[test]fn vector_a_move_backwards_in_kathmandu() {    let master = EventRowForPlan {        starts_at: "2026-09-04T06:30:00.000Z".into(),        exdates: Some(vec![            "2026-09-11T06:30:00.000Z".into(),            "2026-09-18T06:30:00.000Z".into(),        ]),        ..vicky()    };    let plan = plan_series_move(&master, &[], "2026-08-30T18:45:00.000Z", "Asia/Kathmandu")        .expect("a known zone");    assert_eq!(        plan.master_patch.get("exdates"),        Some(&json!([            "2026-09-06T18:45:00.000Z",            "2026-09-13T18:45:00.000Z"        ]))    );}/// A wall time that does not exist (inside London's spring-forward gap) still/// resolves to ONE deterministic instant. WHICH one is not the point; that/// both runtimes compute the same one is, because an exdate that misses is a/// cancelled appointment back on somebody's calendar.#[test]fn vector_a_move_that_lands_in_a_spring_forward_gap() {    let master = EventRowForPlan {        starts_at: "2026-03-22T01:30:00.000Z".into(),        exdates: Some(vec!["2026-03-29T00:30:00.000Z".into()]),        ..vicky()    };    let plan = plan_series_move(&master, &[], "2026-03-22T01:00:00.000Z", "Europe/London")        .expect("a known zone");    assert_eq!(        plan.master_patch.get("exdates"),        Some(&json!(["2026-03-29T01:00:00.000Z"]))    );}/// An unreadable new start is "nothing to re-key", not a failure: the caller's/// own write of `starts_at` is a separate act and this planner declines to/// judge it.#[test]fn vector_an_unreadable_new_start_re_keys_nothing() {    let plan =        plan_series_move(&with_history(), &[moved()], "not a date", KOLKATA).expect("a known zone");    assert!(plan.master_patch.is_empty());    assert!(plan.exception_patches.is_empty());}/// A series whose exdates are ALL unreadable still gets a patch — `null`,/// because it HAD exdates and now has none that survive the move. Leaving the/// unreadable strings in place would leave the master claiming to skip/// instants no rule can produce.#[test]fn vector_exdates_that_all_fail_to_re_key_become_null() {    let master = EventRowForPlan {        exdates: Some(vec!["nope".into(), "also nope".into()]),        ..vicky()    };    let plan =        plan_series_move(&master, &[], "2026-09-04T07:30:00.000Z", KOLKATA).expect("a known zone");    assert_eq!(as_json(&plan.master_patch), json!({ "exdates": null }));}#[test]fn refuses_a_zone_it_does_not_know_rather_than_guessing_utc() {    let error = plan_series_move(        &with_history(),        &[],        "2026-09-04T07:30:00.000Z",        "Mars/Olympus",    )    .expect_err("an unknown zone");    assert_eq!(        error.to_string(),        "cotton: \"Mars/Olympus\" is not a known time zone"    );}/// RULE (Days, 20 Nov 2026): a local edit to a row a CalDAV server keeps is not marked pending either: the Mac's CalDAV door only reads.#[test]fn a_caldav_row_is_not_marked_on_an_edit_and_nor_is_a_cotton_only_row() {    let caldav = pending_mark_patch(SyncIdentity {        gcal_id: None,        sync_state: Some("synced"),    });    assert!(caldav.is_empty());    let local = pending_mark_patch(SyncIdentity {        gcal_id: None,        sync_state: None,    });    assert!(local.is_empty());}/// RULE (27 Oct 2026): an event is the database's, never its calendar's — the/// object keeps no calendars and its Google pull names none — so a moved/// occurrence of a series that names no calendar names none either: null,/// never an empty id.#[test]fn an_occurrence_of_a_series_in_no_calendar_names_none() {    let master = EventRowForPlan { collection_id: None, ..vicky() };    let plan = plan_occurrence_edit(edit(&master, "2026-09-11T06:30:00.000Z", &OccurrencePatch::default(), "ev-a"))        .expect("a readable master");    assert_eq!(plan.patch.get("collection_id"), Some(&json!(null)));}