//! The repeat editor's four verbs, end to end over `dispatch::call_tool` //! against a real store — the writes `/todos/todo/[id]`'s repeat sheet makes //! and the pass the app runs at foreground. //! //! Each rule asserted here is a rule about a TEMPLATE and the occurrences //! projected from it: //! //! * the anchor todo BECOMES the first occurrence, and the mark starts at it so //! the materializer never re-creates the row it already is; //! * an unchanged rule keeps a forward mark, so a skipped occurrence stays //! skipped; a changed rule re-projects from now; //! * open FUTURE occurrences are projections and are rewritten; OVERDUE open //! ones are independent obligations and are never touched; //! * the earliest future occurrence is MOVED rather than replaced, so a detail //! screen the person is standing on survives the edit — unless its new slot //! is already taken, when it is dropped instead; //! * pausing is the one sanctioned mark regression, and it parks the mark at //! now so resuming does not back-fill the paused window; //! * stopping keeps the occurrence the person is standing on and detaches it. //! //! Called AS THE OWNER throughout, because that is the only caller these tools //! have; `mcp_owner.rs` holds the assistant's half over the catalogue's own //! list of owner-scope tools. mod support; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use support::harness::Harness; use support::mcp::call_tool_as_owner; use support::synthetic_uuid; /// The device id the owner's app writes under. Synthetic, like every fixture in /// this tree ([nothing-real-ever-goes-in-cotton-s-public-tree]). const DEVICE: &str = "device:00000000000000000000000000"; /// The harness clock is fixed at 2026-09-08T10:00:00Z — a Tuesday — so every /// instant below is chosen against it rather than against the wall clock. const AT: &str = "2026-09-08T10:00:00.000Z"; /// The anchor: Wednesday 09:00 UTC, one day after "now". const ANCHOR: &str = "2026-09-09T09:00:00.000Z"; const WEEKLY: &str = "FREQ=WEEKLY;BYDAY=WE"; /// The owner's phone holding its database alone — no Mac serves it yet — and /// so the file's writer of record: the one device whose foreground pass mints /// (`recurrence::mints_occurrences`; coordinator's decision (b), 295 C). fn alone() -> Harness { let mut h = Harness::new(); h.services.services.this_file = Some(cotton_tools::rails::ThisFile { held: cotton_tools::rails::FileHeld::Replica, device_id: Some(DEVICE.to_string()), unserved: true, kit: None, }); h } fn zoned() -> Harness { let h = alone(); // `cotton_news_settings.timezone` is the one workspace-scoped zone in the // file, written straight in: nothing on the MCP surface sets it. UTC keeps // every instant below readable as the instant it says. h.with(|db| { db.run( "INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at) \ VALUES (?, 'UTC', ?, ?)", &[ SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) }) .expect("the zone lands"); h } /// A plain todo, written straight in — `create_todo` is another group's tool /// and a fixture is not coverage. fn seed_todo(h: &Harness, label: &str, due_at: &str) -> String { let id = synthetic_uuid(label); h.with(|db| { db.run( "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, priority, \ created_at, updated_at) VALUES (?, ?, ?, 'open', ?, 0, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(format!("Water the alpacas ({label})")), SqlValue::Text(due_at.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) }) .expect("the todo lands"); id } fn ok(h: &Harness, tool: &str, args: Value) -> Value { let answer = call_tool_as_owner(h, DEVICE, tool, args); assert!(!answer.is_error, "{tool}: {}", answer.text); answer.json() } fn todo_row(h: &Harness, id: &str) -> Option> { h.one( "SELECT id, title, status, due_at, occurrence_at, recurrence_id, snoozed_until \ FROM cotton_todos WHERE id = ?", &[SqlValue::Text(id.to_string())], ) } fn occurrences(h: &Harness, recurrence_id: &str) -> Vec { h.all( "SELECT occurrence_at FROM cotton_todos WHERE recurrence_id = ? ORDER BY occurrence_at", &[SqlValue::Text(recurrence_id.to_string())], ) .iter() .filter_map(|row| { row.get("occurrence_at") .and_then(Value::as_str) .map(str::to_string) }) .collect() } fn mark(h: &Harness, recurrence_id: &str) -> Option { h.one( "SELECT materialized_until FROM cotton_todo_recurrences WHERE id = ?", &[SqlValue::Text(recurrence_id.to_string())], ) .and_then(|row| { row.get("materialized_until") .and_then(Value::as_str) .map(str::to_string) }) } /// A todo made recurring from an anchor still in the FUTURE — one occurrence, /// which is the planner's whole end state for such a series. fn recurring(h: &Harness) -> (String, String) { let todo = seed_todo(h, "anchor", ANCHOR); let template = ok( h, "make_todo_recurring", json!({ "todoId": todo, "rrule": WEEKLY, "dtstart": ANCHOR }), ); (todo, template["id"].as_str().expect("an id").to_string()) } /// The id of the occurrence at an instant. fn occurrence_id(h: &Harness, template: &str, at: &str) -> String { h.one( "SELECT id FROM cotton_todos WHERE recurrence_id = ? AND occurrence_at = ?", &[ SqlValue::Text(template.to_string()), SqlValue::Text(at.to_string()), ], ) .and_then(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) .expect("the occurrence is there") } /// One projected occurrence of a template, written straight in. fn seed_occurrence(h: &Harness, template: &str, at: &str) -> String { let id = synthetic_uuid(at); h.with(|db| { db.run( "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, occurrence_at, \ recurrence_id, priority, created_at, updated_at) \ VALUES (?, ?, 'Water the alpacas', 'open', ?, ?, ?, 0, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(at.to_string()), SqlValue::Text(at.to_string()), SqlValue::Text(template.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) }) .expect("the occurrence lands"); id } /// A series anchored a fortnight BACK, so the pass has catching up to do and /// there are several occurrences to reason about. fn catching_up(h: &Harness) -> (String, String) { let todo = seed_todo(h, "catching-up", "2026-08-26T09:00:00.000Z"); let template = ok( h, "make_todo_recurring", json!({ "todoId": todo, "rrule": WEEKLY, "dtstart": "2026-08-26T09:00:00.000Z" }), ); let template = template["id"].as_str().expect("an id").to_string(); // The next one after now beside the overdue anchor: the shape a series // made before one live copy per repeat (Cotton Days, 20 Nov 2026) holds. seed_occurrence(h, &template, "2026-09-09T09:00:00.000Z"); (todo, template) } // ── make_todo_recurring ───────────────────────────────────────────────────── #[test] fn the_anchor_todo_becomes_the_first_occurrence_rather_than_a_second_row() { let h = zoned(); let (todo, template) = recurring(&h); let row = todo_row(&h, &todo).expect("the anchor is still there"); assert_eq!( row.get("recurrence_id").and_then(Value::as_str), Some(template.as_str()) ); assert_eq!( row.get("occurrence_at").and_then(Value::as_str), Some(ANCHOR) ); // The due date SNAPS to the anchor: picking a rule from the sheet anchors // the series on the due instant the sheet was showing. assert_eq!(row.get("due_at").and_then(Value::as_str), Some(ANCHOR)); // And the anchor is not projected a second time — the mark starts at it. let slots = occurrences(&h, &template); assert_eq!(slots.iter().filter(|slot| *slot == ANCHOR).count(), 1); } #[test] fn a_future_anchor_is_itself_the_one_upcoming_occurrence_and_nothing_more_is_projected() { // The planner's end state is "everything due, plus ONE upcoming", so a // template whose anchor is still ahead has already reached it: a second // future row would be the duplication the mark exists to prevent. The pass // the create runs is what proves this rather than a hole in it. let h = zoned(); let (_, template) = recurring(&h); assert_eq!(occurrences(&h, &template), vec![ANCHOR.to_string()]); assert_eq!(mark(&h, &template).as_deref(), Some(ANCHOR)); } #[test] fn a_past_anchor_is_the_one_live_copy_and_nothing_is_made_beside_it() { // RULE (Cotton Days, 20 Nov 2026): a series anchored before now keeps its // anchor (open, overdue) as its one live copy; nothing is made beside it // until it is done or skipped, and the moments between are never made. let h = zoned(); let todo = seed_todo(&h, "past", "2026-08-26T09:00:00.000Z"); let template = ok( &h, "make_todo_recurring", json!({ "todoId": todo, "rrule": WEEKLY, "dtstart": "2026-08-26T09:00:00.000Z" }), ); let template = template["id"].as_str().expect("an id").to_string(); assert_eq!(occurrences(&h, &template), vec!["2026-08-26T09:00:00.000Z".to_string()]); } #[test] fn a_todo_that_already_repeats_is_refused_rather_than_given_a_second_series() { let h = zoned(); let (todo, _) = recurring(&h); let refused = call_tool_as_owner( &h, DEVICE, "make_todo_recurring", json!({ "todoId": todo, "rrule": "FREQ=DAILY", "dtstart": ANCHOR }), ); assert!(refused.is_error); assert!( refused.text.contains("already repeats"), "{}", refused.text ); } #[test] fn an_unsupported_rule_is_refused_before_anything_is_written() { let h = zoned(); let todo = seed_todo(&h, "plain", ANCHOR); let refused = call_tool_as_owner( &h, DEVICE, "make_todo_recurring", json!({ "todoId": todo, "rrule": "FREQ=FORTNIGHTLY", "dtstart": ANCHOR }), ); assert!(refused.is_error); // Nothing half-landed: no template, and the todo is still a plain one. assert_eq!( h.count("SELECT COUNT(*) FROM cotton_todo_recurrences", &[]), 0 ); let row = todo_row(&h, &todo).expect("the todo is untouched"); assert_eq!(row.get("recurrence_id").and_then(Value::as_str), None); } // ── update_todo_recurrence ────────────────────────────────────────────────── fn edit(h: &Harness, template: &str, rrule: &str, dtstart: &str, paused: bool, previous: Value) -> Value { ok( h, "update_todo_recurrence", json!({ "recurrenceId": template, "title": "Water the alpacas", "notes": Value::Null, "priority": 0, "rrule": rrule, "dtstart": dtstart, "paused": paused, "previous": previous, }), ) } #[test] fn a_rule_change_re_projects_from_now_and_leaves_one_future_occurrence() { let h = zoned(); let (_, template) = recurring(&h); let before = mark(&h, &template); let updated = edit( &h, &template, "FREQ=WEEKLY;BYDAY=FR", ANCHOR, false, json!({ "rrule": WEEKLY, "dtstart": ANCHOR, "materializedUntil": before }), ); assert_eq!(updated["rrule"], json!("FREQ=WEEKLY;BYDAY=FR")); // The anchor is in the future too (it is tomorrow), so it is the instance // that gets MOVED to the new rule's first firing — Friday the 11th. let slots = occurrences(&h, &template); assert_eq!(slots.len(), 1, "{slots:?}"); assert!(slots[0].starts_with("2026-09-11T09:00"), "{slots:?}"); assert_eq!(mark(&h, &template).as_deref(), Some(slots[0].as_str())); } /// RULE: A rule edited on its record page (update_record on todo_recurrence, the generic field editor's write) re-projects the open future todos exactly as the repeat verb does — the page carries no rule logic of its own. #[test] fn a_rule_edited_as_a_record_re_projects_the_open_future_todos() { let h = zoned(); let (todo, template) = recurring(&h); ok( &h, "update_record", json!({ "table": "todo_recurrence", "id": template, "patch": { "rrule": "FREQ=WEEKLY;BYDAY=FR" } }), ); let slots = occurrences(&h, &template); assert_eq!(slots.len(), 1, "{slots:?}"); assert!(slots[0].starts_with("2026-09-11T09:00"), "{slots:?}"); assert_eq!(mark(&h, &template).as_deref(), Some(slots[0].as_str())); assert!(todo_row(&h, &todo).is_some(), "the earliest occurrence is moved, not replaced"); } #[test] fn the_earliest_future_occurrence_keeps_its_id_so_the_screen_survives_the_edit() { let h = zoned(); let (todo, template) = recurring(&h); let before = mark(&h, &template); edit( &h, &template, "FREQ=WEEKLY;BYDAY=FR", ANCHOR, false, json!({ "rrule": WEEKLY, "dtstart": ANCHOR, "materializedUntil": before }), ); // The row the person is looking at is the same row, moved. let row = todo_row(&h, &todo).expect("the anchor survived"); assert!(row .get("occurrence_at") .and_then(Value::as_str) .is_some_and(|at| at.starts_with("2026-09-11T09:00"))); } #[test] fn an_overdue_open_occurrence_is_an_obligation_the_edit_never_touches() { let h = zoned(); let (_, template) = recurring(&h); // An occurrence that came due yesterday and is still open. let overdue = synthetic_uuid("overdue"); h.with(|db| { db.run( "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, occurrence_at, \ recurrence_id, priority, created_at, updated_at) \ VALUES (?, ?, 'Water the alpacas', 'open', ?, ?, ?, 0, ?, ?)", &[ SqlValue::Text(overdue.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text("2026-09-02T09:00:00.000Z".to_string()), SqlValue::Text("2026-09-02T09:00:00.000Z".to_string()), SqlValue::Text(template.clone()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) }) .expect("the overdue occurrence lands"); let before = mark(&h, &template); edit( &h, &template, "FREQ=WEEKLY;BYDAY=FR", ANCHOR, false, json!({ "rrule": WEEKLY, "dtstart": ANCHOR, "materializedUntil": before }), ); assert!( todo_row(&h, &overdue).is_some(), "an obligation that already came due was erased by a rule change" ); } #[test] fn pausing_parks_the_mark_at_now_so_resuming_does_not_back_fill() { let h = zoned(); let (_, template) = recurring(&h); let before = mark(&h, &template); let paused = edit( &h, &template, WEEKLY, ANCHOR, true, json!({ "rrule": WEEKLY, "dtstart": ANCHOR, "materializedUntil": before }), ); assert_eq!(paused["paused"], json!(true)); // Every open future occurrence is gone — a paused series projects nothing. assert!(occurrences(&h, &template).is_empty()); // THE ONE SANCTIONED REGRESSION: the mark comes back to now rather than // staying out at an occurrence that no longer exists. assert_eq!(mark(&h, &template).as_deref(), Some(AT)); } /// RULE: Pausing a series retracts its open future occurrence and resuming it brings that occurrence back live at the same derived id: a Retract never blocks a later create at the same id. #[test] fn paused_then_resumed_series_keeps_its_one_live_copy() { let h = zoned(); let (_, template) = catching_up(&h); let next = "2026-09-09T09:00:00.000Z"; let first = occurrence_id(&h, &template, next); let mark_before = mark(&h, &template); edit( &h, &template, WEEKLY, "2026-08-26T09:00:00.000Z", true, json!({ "rrule": WEEKLY, "dtstart": "2026-08-26T09:00:00.000Z", "materializedUntil": mark_before }), ); assert!(todo_row(&h, &first).is_none(), "pausing left the future occurrence standing"); let mark_paused = mark(&h, &template); let resumed = edit( &h, &template, WEEKLY, "2026-08-26T09:00:00.000Z", false, json!({ "rrule": WEEKLY, "dtstart": "2026-08-26T09:00:00.000Z", "materializedUntil": mark_paused }), ); assert_eq!(resumed["paused"], json!(false)); // RULE (Cotton Days, 20 Nov 2026): resumed, the series' one live copy is // its open overdue anchor; the dropped future copy is not made beside it. assert!(todo_row(&h, &first).is_none(), "a second live copy came back beside the open anchor"); let open = h.count( "SELECT COUNT(*) FROM cotton_todos WHERE recurrence_id = ? AND status = 'open' AND trashed_at IS NULL", &[SqlValue::Text(template.clone())], ); assert_eq!(open, 1, "a resumed series has one live copy: {:?}", occurrences(&h, &template)); } #[test] fn an_unchanged_rule_keeps_a_forward_mark_so_a_skipped_occurrence_stays_skipped() { let h = zoned(); let (_, template) = recurring(&h); // The person skipped ahead: the mark sits out at the 16th, past the // anchor. Re-saving the sheet without touching the rule must continue AFTER // that mark rather than re-projecting the occurrence they skipped. let ahead = "2026-09-16T09:00:00.000Z"; edit( &h, &template, WEEKLY, ANCHOR, false, json!({ "rrule": WEEKLY, "dtstart": ANCHOR, "materializedUntil": ahead }), ); // The next firing after the 16th is the 23rd — not the 9th, and not the // 16th itself. let slots = occurrences(&h, &template); assert_eq!(slots.len(), 1, "{slots:?}"); assert!(slots[0].starts_with("2026-09-23T09:00"), "{slots:?}"); } #[test] fn a_template_that_is_not_there_says_so() { let h = zoned(); let refused = call_tool_as_owner( &h, DEVICE, "update_todo_recurrence", json!({ "recurrenceId": synthetic_uuid("gone"), "title": "x", "notes": Value::Null, "priority": 0, "rrule": WEEKLY, "dtstart": ANCHOR, "paused": false, "previous": { "rrule": WEEKLY, "dtstart": ANCHOR }, }), ); assert!(refused.is_error); assert!(refused.text.contains("no repeating todo"), "{}", refused.text); } // ── stop_todo_recurrence ──────────────────────────────────────────────────── #[test] fn stopping_keeps_the_occurrence_the_person_is_standing_on_and_detaches_it() { let h = zoned(); let (_, template) = catching_up(&h); // The person is standing on the next occurrence — the lookahead the create // already projected — and there is one beyond it, the shape the planner // reaches once a further pass has run. let todo = occurrence_id(&h, &template, "2026-09-09T09:00:00.000Z"); seed_occurrence(&h, &template, "2026-09-16T09:00:00.000Z"); let before = occurrences(&h, &template) .iter() .filter(|slot| slot.as_str() > AT) .count(); assert_eq!(before, 2, "the fixture needs two future occurrences"); let stopped = ok( &h, "stop_todo_recurrence", json!({ "recurrenceId": template, "keepTodoId": todo }), ); assert_eq!(stopped["stopped"], json!(true)); assert_eq!( stopped["droppedOccurrences"], json!((before - 1) as i64), "every other open future occurrence goes" ); // The template is gone and the kept row reads as a plain todo: its soft // `recurrence_id` names no present template (nothing nulls the value). assert_eq!( h.count("SELECT COUNT(*) FROM cotton_todo_recurrences", &[]), 0 ); assert!(todo_row(&h, &todo).is_some(), "the kept todo survived"); let detached = h.one( &format!( "SELECT {} AS recurrence_id FROM cotton_todos WHERE id = ?", cotton_store::soft_refs::soft_value("cotton_todos.recurrence_id", "cotton_todo_recurrences") ), &[SqlValue::Text(todo.to_string())], ) .expect("the kept todo"); assert_eq!(detached.get("recurrence_id").and_then(Value::as_str), None); } #[test] fn stopping_without_naming_one_to_keep_drops_every_open_future_occurrence() { let h = zoned(); let (todo, template) = recurring(&h); ok(&h, "stop_todo_recurrence", json!({ "recurrenceId": template })); // The anchor is itself a future occurrence here, so it goes with the rest. assert!(todo_row(&h, &todo).is_none()); } // ── materialize_todo_recurrences ──────────────────────────────────────────── #[test] fn the_foreground_pass_gives_every_active_template_what_it_is_owed() { let h = zoned(); let (_, template) = catching_up(&h); // Wind the series back to where it was before anything was projected: the // mark at the anchor and no rows past it. This is the state a phone that // has been closed for a fortnight comes back to, and the pass is what fills // it in. let anchor = "2026-08-26T09:00:00.000Z"; h.with(|db| { db.run( "UPDATE cotton_todo_recurrences SET materialized_until = ? WHERE id = ?", &[ SqlValue::Text(anchor.to_string()), SqlValue::Text(template.clone()), ], ) }) .expect("the mark moves"); h.with(|db| { db.run( "DELETE FROM cotton_todos WHERE recurrence_id = ? AND occurrence_at > ?", &[ SqlValue::Text(template.clone()), SqlValue::Text(anchor.to_string()), ], ) }) .expect("the projection goes"); assert_eq!(occurrences(&h, &template).len(), 1); // An open overdue anchor is the series' one live copy: owed nothing. let report = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(report["created"], json!(0), "{report}"); // Done (on the phone, before the pass ran), it is owed its next. h.with(|db| { db.run( "UPDATE cotton_todos SET status = 'done', completed_at = ? WHERE recurrence_id = ?", &[SqlValue::Text(AT.to_string()), SqlValue::Text(template.clone())], ) }) .expect("the anchor is done"); let report = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(report["templates"], json!(1)); assert_eq!(report["created"], json!(1), "{report}"); assert_eq!(occurrences(&h, &template).len(), 2, "the done anchor, plus the one upcoming"); } #[test] fn the_pass_is_idempotent_so_two_foregrounds_do_not_mint_the_same_occurrence_twice() { let h = zoned(); let (_, template) = catching_up(&h); let first = occurrences(&h, &template); ok(&h, "materialize_todo_recurrences", json!({})); ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(occurrences(&h, &template), first); } #[test] fn a_paused_template_is_skipped_by_the_pass() { let h = zoned(); let (_, template) = recurring(&h); let before = mark(&h, &template); edit( &h, &template, WEEKLY, ANCHOR, true, json!({ "rrule": WEEKLY, "dtstart": ANCHOR, "materializedUntil": before }), ); let report = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(report["templates"], json!(0)); assert!(occurrences(&h, &template).is_empty()); } #[test] fn a_workspace_with_no_recorded_zone_takes_the_device_s_and_refuses_without_one() { // `expansionZone()`, exactly: the workspace's recorded zone wins wherever it // exists, the device's is the momentary fallback for a workspace that has // never recorded one, and there is NO UTC floor — flooring here would mint // rows at instants no other producer computes, which is the duplication the // derived occurrence id exists to end. let h = alone(); let refused = call_tool_as_owner(&h, DEVICE, "materialize_todo_recurrences", json!({})); assert!(refused.is_error, "a writer floored a missing zone to UTC"); assert!(refused.text.contains("timezone"), "{}", refused.text); let named = call_tool_as_owner( &h, DEVICE, "materialize_todo_recurrences", json!({ "timezone": "Asia/Kolkata" }), ); assert!(!named.is_error, "{}", named.text); } #[test] fn the_foreground_pass_claims_the_device_s_zone_when_nothing_has_recorded_one() { // `claimWorkspaceZone`, ported. Before it existed the phone fell back to the // device zone while the server rested rather than guess — two halves with // different answers about when a repeating todo happens, which is the // duplication the derived occurrence id exists to end. The phone is the half // that can know, so it writes the zone down on the same synced row the // server reads. let h = alone(); let claimed = ok( &h, "materialize_todo_recurrences", json!({ "timezone": "Asia/Kolkata" }), ); assert_eq!(claimed["timezone"], json!("Asia/Kolkata")); assert_eq!( h.one("SELECT timezone AS value FROM cotton_news_settings", &[]) .and_then(|row| row.get("value").and_then(Value::as_str).map(str::to_string)) .as_deref(), Some("Asia/Kolkata") ); } /// RULE: The foreground pass on a copy a Mac serves mints no occurrence — it answers `mints: false` and `created: 0` and leaves the occurrences to the serving Mac's tick — yet still claims the device's zone when nothing has recorded one (coordinator's decision (b), 295 C, walker294). #[test] fn a_copy_a_mac_serves_claims_the_zone_and_mints_nothing() { let h = Harness::new(); let claimed = ok(&h, "materialize_todo_recurrences", json!({ "timezone": "UTC" })); assert_eq!(claimed["mints"], json!(false), "{claimed}"); assert_eq!( h.one("SELECT timezone AS value FROM cotton_news_settings", &[]) .and_then(|row| row.get("value").and_then(Value::as_str).map(str::to_string)) .as_deref(), Some("UTC"), "the zone is claimed once, wherever the pass runs" ); let (_, template) = catching_up(&h); // A fortnight owed, as the writer-of-record twin of this case winds it // (`the_foreground_pass_gives_every_active_template_what_it_is_owed`). let anchor = "2026-08-26T09:00:00.000Z"; h.with(|db| { db.run( "UPDATE cotton_todo_recurrences SET materialized_until = ? WHERE id = ?", &[SqlValue::Text(anchor.to_string()), SqlValue::Text(template.clone())], )?; db.run( "DELETE FROM cotton_todos WHERE recurrence_id = ? AND occurrence_at > ?", &[SqlValue::Text(template.clone()), SqlValue::Text(anchor.to_string())], ) }) .expect("the series winds back"); let before = occurrences(&h, &template); assert_eq!(before.len(), 1); let report = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(report["mints"], json!(false), "{report}"); assert_eq!(report["created"], json!(0), "{report}"); assert_eq!(occurrences(&h, &template), before, "the serving Mac's tick mints them"); } #[test] fn a_recorded_zone_is_never_overwritten_by_the_device_s() { // A zone this device cannot read is still SOMEBODY's decision. Keying the // claim off "can I read it" rather than "is there a row" would have a phone // with a smaller zone table overwrite the zone another device chose, on // every launch, for ever. let h = zoned(); let ran = ok( &h, "materialize_todo_recurrences", json!({ "timezone": "Asia/Kolkata" }), ); assert_eq!(ran["timezone"], json!("UTC")); assert_eq!( h.one("SELECT timezone AS value FROM cotton_news_settings", &[]) .and_then(|row| row.get("value").and_then(Value::as_str).map(str::to_string)) .as_deref(), Some("UTC") ); } #[test] fn the_workspace_s_own_zone_wins_over_the_device_s() { // Travelling must not fork a series: the anchor is 09:00 UTC and the device // says Kolkata, but the recorded zone is UTC, so the instants — and so the // derived ids — are the ones every other producer computes. let h = zoned(); let todo = seed_todo(&h, "travelling", "2026-08-26T09:00:00.000Z"); let made = ok( &h, "make_todo_recurring", json!({ "todoId": todo, "rrule": WEEKLY, "dtstart": "2026-08-26T09:00:00.000Z", "timezone": "Asia/Kolkata", }), ); let template = made["id"].as_str().expect("an id"); for slot in occurrences(&h, template) { assert!(slot.ends_with("T09:00:00.000Z"), "{slot}"); } } // ── the review round's four ───────────────────────────────────────────────── #[test] fn a_pass_over_a_template_that_is_already_up_to_date_says_it_created_nothing() { // `materializeTemplate` answers the rows INSERTED after the skip // (`todoRecurrences.service.ts:517`); `plan.occurrences.len()` is the // SERVER worker's number. Reporting the planner's count here made every // foreground claim it had created todos it had only re-found. let h = zoned(); let (_, template) = catching_up(&h); ok(&h, "materialize_todo_recurrences", json!({})); let before = occurrences(&h, &template); let again = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(again["templates"], json!(1), "the template was still walked"); assert_eq!(again["created"], json!(0), "{again}"); assert_eq!(occurrences(&h, &template), before); } #[test] fn the_pass_walks_every_active_template_rather_than_the_first_two_hundred() { // There was a cap of 200 here with `more: true` in the answer and a comment // promising the next pass would pick the rest up. Nothing did: the read is // ordered `created_at ASC` with no cursor and no stored state, so every // pass re-walked the same first two hundred and the two hundred and first // template never materialised at all. `materializeForWorkspace` has no cap. let h = zoned(); // Anchors in the FUTURE, so each template plans its one lookahead and the // fixture stays cheap — what is under test is how many templates the pass // reaches, not how many rows each one is owed. let total = 205; h.with(|db| { for n in 0..total { db.run( "INSERT INTO cotton_todo_recurrences (id, workspace_id, title, priority, rrule, \ dtstart, paused, materialized_until, created_at, updated_at) \ VALUES (?,?,?,0,?,?,0,?,?,?)", &[ SqlValue::Text(format!("rec-{n:04}")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text("A synthetic series".to_string()), SqlValue::Text(WEEKLY.to_string()), SqlValue::Text("2027-01-06T09:00:00.000Z".to_string()), SqlValue::Text("2027-01-06T09:00:00.000Z".to_string()), SqlValue::Text(format!("2026-09-0{}T10:00:00.000Z", 1 + (n % 8))), SqlValue::Text(AT.to_string()), ], )?; } Ok::<(), cotton_store::error::StoreError>(()) }) .expect("the templates land"); let report = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(report["templates"], json!(total)); // And nothing tells the caller there is more to come, because there is not. assert_eq!(report.get("more"), None, "{report}"); } #[test] fn making_a_todo_repeat_with_no_zone_anywhere_leaves_no_half_made_series() { // `expansion_zone` refuses a workspace that has recorded none and was // passed none. It used to be asked for AFTER the template and the todo's // anchor were committed, so that refusal left a template nothing projects // and a todo already pointing at it. let h = Harness::new(); let todo = seed_todo(&h, "plain", ANCHOR); let refused = call_tool_as_owner( &h, DEVICE, "make_todo_recurring", json!({ "todoId": todo, "rrule": WEEKLY, "dtstart": ANCHOR }), ); assert!(refused.is_error, "{}", refused.text); assert!(refused.text.contains("timezone"), "{}", refused.text); assert_eq!( h.count("SELECT COUNT(*) FROM cotton_todo_recurrences", &[]), 0, "a template was written before the zone was resolved" ); let row = todo_row(&h, &todo).expect("the todo is untouched"); assert_eq!(row.get("recurrence_id").and_then(Value::as_str), None); assert_eq!(row.get("occurrence_at").and_then(Value::as_str), None); } #[test] fn a_row_standing_on_a_planned_instant_under_its_own_id_is_not_projected_over() { // The pass asks by the NATURAL key — `recurrence_id` + `occurrence_at`, // which is the pair `UNIQUE (recurrence_id, occurrence_at)` guards and what // both TypeScript twins ask by. A lookup by the DERIVED id cannot see a row // a different writer put on that instant (the anchor todo, or the // kept-and-moved instance an edit leaves), and the insert would then trip // that index. let h = zoned(); let (_, template) = recurring(&h); let taken = "2026-09-16T09:00:00.000Z"; // A todo on the series' next instant under a NON-derived id, exactly the // shape `make_todo_recurring`'s anchor and `update_todo_recurrence`'s moved // instance have. let squatter = synthetic_uuid("squatter"); h.with(|db| { db.run( "INSERT INTO cotton_todos (id, workspace_id, title, status, priority, recurrence_id, \ occurrence_at, due_at, created_at, updated_at) \ VALUES (?,?,?,'open',0,?,?,?,?,?)", &[ SqlValue::Text(squatter.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text("Already here".to_string()), SqlValue::Text(template.clone()), SqlValue::Text(taken.to_string()), SqlValue::Text(taken.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) }) .expect("the squatter lands"); // Wind the mark back so the pass really does plan that instant again. h.with(|db| { db.run( "UPDATE cotton_todo_recurrences SET materialized_until = ? WHERE id = ?", &[ SqlValue::Text(ANCHOR.to_string()), SqlValue::Text(template.clone()), ], ) }) .expect("the mark moves"); let report = call_tool_as_owner(&h, DEVICE, "materialize_todo_recurrences", json!({})); assert!(!report.is_error, "{}", report.text); // ONE row on that instant, and it is the one that was already there. let standing = h.all( "SELECT id FROM cotton_todos WHERE recurrence_id = ? AND occurrence_at = ?", &[ SqlValue::Text(template.clone()), SqlValue::Text(taken.to_string()), ], ); assert_eq!(standing.len(), 1, "{standing:?}"); assert_eq!(standing[0]["id"], json!(squatter)); } // ── a settled monthly expectation's next month, on the phone (e2e rulings R3) ── /// A settled monthly rent: its expectation and the payment that settles it, written straight in. fn settled_rent(h: &Harness) { let ws = SqlValue::Text(h.workspace_id.clone()); let at = SqlValue::Text(AT.to_string()); h.with(|db| { db.run( "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, amount_minor, amount_known, direction, currency, for_period, status, repeat, repeat_day, due_date, created_at, updated_at) \ VALUES ('rent-jan', ?, '2026-01-31', 'Synthetic rent', 250000, 1, 'out', 'INR', '2026-01', 'expected', 'monthly', 31, '2026-01-31', ?, ?)", &[ws.clone(), at.clone(), at.clone()], )?; db.run( "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, amount_minor, amount_known, direction, currency, status, settles_transaction_id, created_at, updated_at) \ VALUES ('rent-paid', ?, '2026-01-30', 'Synthetic rent paid', 250000, 1, 'out', 'INR', 'actual', 'rent-jan', ?, ?)", &[ws.clone(), at.clone(), at.clone()], ) }) .expect("the rent lands"); } /// The copy's money row definition, as the object serves it: open, or sealed. fn define_transaction(h: &Harness, definition: &str) { let table = cotton_tools::definitions::TABLE_DEFINITIONS; h.with(|db| { db.run(&format!("DELETE FROM {table} WHERE id = 'transaction'"), &[])?; db.run( &format!("INSERT INTO {table} (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('transaction', ?, ?, 0, ?, ?)"), &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(definition.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string())], ) }) .expect("the money row's definition"); } fn expectations(h: &Harness) -> Vec> { h.all( "SELECT id, occurred_on, description, amount_minor, for_period, due_date, status FROM cotton_money_transactions WHERE status = 'expected' ORDER BY occurred_on", &[], ) } /// RULE (e2e rulings R3, 16 Nov 2026): once the copy's money /// row is sealed the object makes no next month for a settled expectation (it /// cannot copy words it cannot read), so the writer of record's foreground /// pass makes it, under the derived id the object used, once; while money is /// open the object makes it and the pass makes none. #[test] fn the_pass_makes_a_settled_expectation_s_next_month_once_money_is_sealed() { let h = zoned(); settled_rent(&h); define_transaction(&h, r#"{"id":"transaction"}"#); let open = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(open["expected"], json!(0), "money open: the object makes it, {open}"); assert_eq!(expectations(&h).len(), 1); define_transaction(&h, r#"{"id":"transaction","seal":{"clear":["occurred_on","status"]}}"#); let sealed = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(sealed["expected"], json!(1), "{sealed}"); let rows = expectations(&h); assert_eq!(rows.len(), 2); let next = &rows[1]; assert_eq!(next["occurred_on"], json!("2026-02-28")); assert_eq!(next["description"], json!("Synthetic rent")); assert_eq!(next["amount_minor"], json!(250000)); assert_eq!(next["for_period"], json!("2026-02")); assert_eq!(next["due_date"], json!("2026-02-28")); let again = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(again["expected"], json!(0), "made once: {again}"); assert_eq!(expectations(&h).len(), 2); } fn define_attendees(h: &Harness, definition: &str) { let table = cotton_tools::definitions::TABLE_DEFINITIONS; h.with(|db| { db.run(&format!("DELETE FROM {table} WHERE id = 'event_attendee'"), &[])?; db.run( &format!("INSERT INTO {table} (id, workspace_id, definition, builtin, created_at, updated_at) VALUES ('event_attendee', ?, ?, 0, ?, ?)"), &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(definition.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string())], ) }) .expect("the attendee's definition"); } /// RULE (e2e rulings R3, 16 Nov 2026): once attendees are /// sealed the object cannot link them to People, so the writer of record's /// pass does, by the live handles People carry: each person matched gains the /// event once, and an attendee who matches nobody makes nobody up; while attendees are open the object links /// them and the pass links none. #[test] fn the_pass_links_a_sealed_events_attendees_to_people() { let h = zoned(); let event = synthetic_uuid("event"); let (asha, bela, chen) = (synthetic_uuid("asha"), synthetic_uuid("bela"), synthetic_uuid("chen")); h.with(|db| { db.run("INSERT INTO cotton_events (id, title, starts_at, created_at, updated_at) VALUES (?, 'Invented review', '2026-11-20T09:00:00.000Z', ?, ?)", &[SqlValue::Text(event.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())])?; for (id, name) in [(&asha, "Asha Example"), (&bela, "Bela Example"), (&chen, "Chen Example")] { db.run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &[SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(name.into()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())])?; } // Asha by email, Bela by phone; Chen's handle is in the bin, so Chen is matched by nothing. for (n, (person, kind, value)) in [(&asha, "email", "asha@example.test"), (&bela, "phone", "919000000101"), (&chen, "email", "chen@example.test")].into_iter().enumerate() { db.run( "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'manual', ?, ?)", &[SqlValue::Text(synthetic_uuid(&format!("handle-{n}"))), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(person.clone()), SqlValue::Text(kind.into()), SqlValue::Text(if kind == "phone" { format!("+{value}") } else { value.to_string() }), SqlValue::Text(value.into()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], )?; } db.run("UPDATE cotton_person_handles SET trashed_at = ? WHERE normalised = 'chen@example.test'", &[SqlValue::Text(AT.into())])?; for (n, (email, phone)) in [(Some("Asha@Example.test"), None), (None, Some("+919000000101")), (Some("chen@example.test"), None), (Some("nobody@example.test"), None)].into_iter().enumerate() { db.run( "INSERT INTO cotton_event_attendees (id, event_id, email, phone, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)", &[SqlValue::Text(synthetic_uuid(&format!("attendee-{n}"))), SqlValue::Text(event.clone()), email.map_or(SqlValue::Null, |e: &str| SqlValue::Text(e.into())), phone.map_or(SqlValue::Null, |p: &str| SqlValue::Text(p.into())), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], )?; } Ok::<(), cotton_store::StoreError>(()) }) .expect("an event, its attendees and People"); let edges = |h: &Harness| h.all("SELECT to_id FROM cotton_links WHERE from_kind = 'event' AND to_kind = 'person' ORDER BY to_id", &[]); define_attendees(&h, r#"{"id":"event_attendee"}"#); let open = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(open["attendees_linked"], json!(0), "attendees open: the object links them, {open}"); define_attendees(&h, r#"{"id":"event_attendee","seal":{"clear":["event_id"]}}"#); let sealed = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(sealed["attendees_linked"], json!(2), "{sealed}"); let mut linked: Vec = edges(&h).iter().map(|row| row["to_id"].clone()).collect(); linked.sort_by_key(|id| id.to_string()); let mut want = vec![json!(asha), json!(bela)]; want.sort_by_key(|id| id.to_string()); assert_eq!(linked, want, "Asha by her email (any case), Bela by his number; a binned handle and a stranger link nobody"); let again = ok(&h, "materialize_todo_recurrences", json!({})); assert_eq!(again["attendees_linked"], json!(0), "linked once: {again}"); }