//! Cotton Days over invented days, signed out: nobody here is real.use serde_json::{json, Value};use tempfile::TempDir;usecrate::handle::{CottonHandle, OpenConfig, OpenMode};usecrate::methods::dispatch;pub(crate) const ZONE: &str = "Europe/London";pub(crate) const TODAY: &str = "2026-11-20"; // a Fridaypub(crate) fn phone(dir: &TempDir) -> CottonHandle {// The app's own manifest, kit and all, as the phone opens it.let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours/days/flavour.json");let manifest: Value = serde_json::from_slice(&std::fs::read(&path).unwrap_or_else(|error| panic!("the Days manifest at {}: {error}", path.display()))).expect("a manifest");let handle = CottonHandle::open(OpenConfig { mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some(ZONE.to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(manifest), }) .expect("an open core"); dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started"); handle}pub(crate) fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value { dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}pub(crate) fn refused(handle: &CottonHandle, method: &str, request: Value) -> (String, String) {let error = dispatch(handle, method, &request).expect_err("refused"); (error.code.to_string(), error.message.clone())}/// Rows straight into this copy, as another device's sync would land them.pub(crate) fn sql(handle: &CottonHandle, statement: &str) { handle .client() .with_writer(|replica| { replica.driver.run(&statement.replace("$WS", replica.workspace_id), &[]).map(|_| ()).map_err(|error| error.to_string()) }) .expect("the fixture lands");}pub(crate) fn span(handle: &CottonHandle, from: &str, to: &str) -> Value { ask(handle, "days.span", json!({ "timezone": ZONE, "today": TODAY, "from": from, "to": to }))}/// Each day as "day: rows", each row "time mark words suffix".pub(crate) fn lines(answer: &Value) -> Vec<String> { answer["days"] .as_array() .expect("days") .iter() .map(|entry| {ifletSome(fold) = entry.get("fold") {return fold["words"].as_str().unwrap_or_default().to_string(); }let rows: Vec<String> = entry["rows"] .as_array() .expect("rows") .iter() .map(|row| {let mark = match row["mark"]["kind"].as_str() {Some("tick") if row["done"] == json!(true) => "✓".to_string(),Some("tick") => "○".to_string(),Some("drawn") => format!("[{}]", row["mark"]["id"].as_str().unwrap_or("")), _ => "·".to_string(), };letmut line = format!("{} {} {}", row["time"].as_str().unwrap_or(""), mark, row["words"].as_str().unwrap_or(""));ifletSome(suffix) = row["suffix"].as_str() { line = format!("{line} {suffix}"); } line.trim().to_string() }) .collect(); format!("{}: {}", entry["day"].as_str().unwrap_or_default(), rows.join(" | ")) }) .collect()}pub(crate) fn zone(handle: &CottonHandle) { sql(handle, "INSERT OR REPLACE INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at) VALUES ('$WS', 'Europe/London', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");}/// RULE (DECISIONS.md, Structure): the Days read is every day's one list from events, to-dos and birthdays: whole-day things, then timed things in order, then to-dos with no time; an undone to-do from an earlier day is on today "from <day>" and not on its own day; a done one is on the day it was done; empty runs fold.#[test]fn the_days_read_is_one_list_a_day_from_events_todos_and_birthdays() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle); sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, created_at, updated_at) VALUES ('ev-visit', 'Rosein town', '2026-11-20T00:00:00.000Z', '2026-11-21T23:59:59.999Z', 1, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'), ('ev-bank', 'Call with the bank', '2026-11-20T11:30:00.000Z', '2026-11-20T12:00:00.000Z', 0, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'), ('ev-flight', 'Flight to Hyderabad', '2026-11-26T06:40:00.000Z', NULL, 0, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"); sql(&handle, "UPDATE cotton_events SET mark = 'plane' WHERE id = 'ev-flight'"); sql(&handle, "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, completed_at, created_at, updated_at) VALUES ('td-pages', '$WS', 'Morning pages', 'open', '2026-11-20T09:00:00.000Z', NULL, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'), ('td-form', '$WS', 'Renew passport form', 'open', '2026-11-20T00:00:00.000Z', NULL, '2026-11-02T00:00:00.000Z', '2026-11-02T00:00:00.000Z'), ('td-invoice', '$WS', 'Send the invoice', 'open', '2026-11-17T00:00:00.000Z', NULL, '2026-11-03T00:00:00.000Z', '2026-11-03T00:00:00.000Z'), ('td-ink', '$WS', 'Order printer ink', 'done', '2026-11-19T00:00:00.000Z', '2026-11-18T15:00:00.000Z', '2026-11-04T00:00:00.000Z', '2026-11-18T15:00:00.000Z'), ('td-someday', '$WS', 'Learn the guitar', 'open', NULL, NULL, '2026-11-05T00:00:00.000Z', '2026-11-05T00:00:00.000Z'), ('td-dropped', '$WS', 'Let go', 'dropped', '2026-11-20T00:00:00.000Z', NULL, '2026-11-05T00:00:00.000Z', '2026-11-05T00:00:00.000Z')"); sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, created_at, updated_at) VALUES ('pe-akash', '$WS', 'AkashInvented', 11, 21, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");let answer = span(&handle, "2026-11-17", "2026-11-26"); assert_eq!( lines(&answer), [// The quiet run before the 18th is one fold, back to Akash's birthday a year ago (21 Nov 2025)."22 Nov 2025 – 17 Nov 2026 · 361 quiet days","2026-11-18: ✓ Order printer ink","19 · a quiet day","2026-11-20: · Rose in town | 9:00 ○ Morning pages | 11:30 · Call with the bank to 12:00 | ○ Renew passport form | ○ Send the invoice from Tue","2026-11-21: · Rose in town | [cake] Akash Invented's birthday","22 – 25 · four quiet days","2026-11-26: 6:40 [plane] Flight to Hyderabad", ],"{answer}" );let today = &answer["days"][3]; assert_eq!((today["today"].clone(), today["weekday"].clone()), (json!(true), json!("Friday")));let birthday = &answer["days"][4]["rows"][1]; assert_eq!((birthday["whose"].clone(), birthday["opens"].clone()), (json!("birthday"), json!({ "person": "pe-akash" })));}/// RULE (Days, 20 Nov 2026): a repeating to-do is one row however many days it was missed: a stack the old rule left draws as its newest, done makes the next after today, and skip lets the live copy go (dropped) and makes the next; a to-do that does not repeat is not skipped.#[test]fn a_repeating_todo_is_one_row_and_done_or_skip_moves_to_the_next() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle); sql(&handle, "INSERT INTO cotton_todo_recurrences (id, workspace_id, title, priority, rrule, dtstart, paused, materialized_until, created_at, updated_at) VALUES ('00000000-0000-4000-8000-0000000000a1', '$WS', 'Walk', 0, 'FREQ=DAILY', '2026-11-17T08:00:00.000Z', 0, '2026-11-19T08:00:00.000Z', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"); sql(&handle, "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, recurrence_id, occurrence_at, created_at, updated_at) VALUES ('00000000-0000-4000-8000-000000000017', '$WS', 'Walk', 'open', '2026-11-17T08:00:00.000Z', '00000000-0000-4000-8000-0000000000a1', '2026-11-17T08:00:00.000Z', '2026-11-17T00:00:00.000Z', '2026-11-17T00:00:00.000Z'), ('00000000-0000-4000-8000-000000000018', '$WS', 'Walk', 'open', '2026-11-18T08:00:00.000Z', '00000000-0000-4000-8000-0000000000a1', '2026-11-18T08:00:00.000Z', '2026-11-18T00:00:00.000Z', '2026-11-18T00:00:00.000Z'), ('00000000-0000-4000-8000-000000000019', '$WS', 'Walk', 'open', '2026-11-19T08:00:00.000Z', '00000000-0000-4000-8000-0000000000a1', '2026-11-19T08:00:00.000Z', '2026-11-19T00:00:00.000Z', '2026-11-19T00:00:00.000Z'), ('00000000-0000-4000-8000-0000000000b1', '$WS', 'Plain', 'open', '2026-11-25T00:00:00.000Z', NULL, NULL, '2026-11-19T00:00:00.000Z', '2026-11-19T00:00:00.000Z')");let answer = span(&handle, TODAY, TODAY); assert_eq!(lines(&answer), ["2026-11-20: ○ Walk from Thu"], "{answer}"); ask(&handle, "days.done", json!({ "id": "00000000-0000-4000-8000-000000000019", "timezone": ZONE }));let statuses = |handle: &CottonHandle| -> Vec<(String, String)> { handle .client() .with_writer(|replica| {Ok::<_, String>( replica .driver .all("SELECT occurrence_at, status FROM cotton_todos WHERE recurrence_id = '00000000-0000-4000-8000-0000000000a1' ORDER BY occurrence_at", &[]) .map_err(|e| e.to_string())? .iter() .map(|row| (row.text("occurrence_at").unwrap_or("").to_string(), row.text("status").unwrap_or("").to_string())) .collect(), ) }) .unwrap() };let after = statuses(&handle); assert_eq!(after.len(), 4, "{after:?}"); assert_eq!(&after[..3].iter().map(|(_, s)| s.as_str()).collect::<Vec<_>>(), &["missed", "missed", "done"]); assert_eq!(after[3].1, "open"); assert!(after[3].0.as_str() > "2026-11-19T08:00:00.000Z", "the next is after the one done: {after:?}");let next = after[3].0.clone();let next_id: String = handle .client() .with_writer(|replica| {Ok::<_, String>( replica .driver .get("SELECT id FROM cotton_todos WHERE occurrence_at = ?", &[rusqlite::types::Value::Text(next.clone())]) .map_err(|e| e.to_string())? .and_then(|row| row.text("id").map(str::to_string)) .unwrap_or_default(), ) }) .unwrap(); ask(&handle, "days.skip", json!({ "id": next_id, "timezone": ZONE }));let skipped = statuses(&handle); assert_eq!(skipped.len(), 5, "{skipped:?}"); assert_eq!((skipped[3].1.as_str(), skipped[4].1.as_str()), ("dropped", "open"));let (code, message) = refused(&handle, "days.skip", json!({ "id": "00000000-0000-4000-8000-0000000000b1" })); assert_eq!((code.as_str(), message.as_str()), ("not_repeating", "Only a repeating to-do can be skipped."));}/// RULE (CONTRACT.md section 16, 22 Nov 2026; was read-only): while the only Google grant is read-only, a Google event's time and title are refused before anything is saved, asking to connect again; its mark, the person's note and alert are theirs and are written.#[test]fn a_google_event_keeps_its_time_and_takes_the_persons_own_additions() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle); sql(&handle, "INSERT INTO cotton_events (id, title, notes, starts_at, ends_at, all_day, gcal_id, sync_state, created_at, updated_at) VALUES ('00000000-0000-4000-8000-0000000000c1', 'Team sync', 'Google''s own description', '2026-11-23T10:00:00.000Z', '2026-11-23T10:30:00.000Z', 0, 'g-invented-1', 'synced', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");crate::phone::days_people::Heard::google(&handle.client(), &json!({ "available": true, "accounts": [{ "googleEmail": "walk@example.test", "canWrite": false, "calendar": { "phase": "synced" } }] }));let (code, message) = refused(&handle, "days.change", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000c1", "title": "Renamed", "timezone": ZONE })); assert_eq!((code.as_str(), message.as_str()), ("google_needs_write", "To save changes to Google Calendar, Days needs your permission once more."));let (code, _) = refused(&handle, "days.move", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000c1", "day": "2026-11-24", "timezone": ZONE })); assert_eq!(code, "google_needs_write"); ask(&handle, "days.change", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000c1", "mark": "laptop", "note": "Bring the figures", "alert": 30, "timezone": ZONE }));let sheet = ask(&handle, "days.item", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000c1", "timezone": ZONE, "today": TODAY })); assert_eq!(sheet["whose"], json!("google")); assert_eq!(sheet["says"], json!("From Google Calendar")); assert_eq!((sheet["mark"].clone(), sheet["note"].clone(), sheet["alert"].clone()), (json!("laptop"), json!("Bring the figures"), json!(30))); assert_eq!((sheet["time"].clone(), sheet["end"].clone()), (json!("10:00"), json!("10:30"))); assert_eq!(sheet["canChange"]["time"], json!(true), "Save asks to connect again");let row = &span(&handle, "2026-11-23", "2026-11-23")["days"][0]["rows"][0]; assert_eq!((row["mark"].clone(), row["whose"].clone()), (json!({ "kind": "drawn", "id": "laptop" }), json!("google"))); assert_eq!(refused(&handle, "days.change", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000c1", "mark": "not-a-mark" })).0, "bad_request");}/// RULE (DECISIONS.md: adding is one line): the line is read for the pill, and adding makes an event of the person's own with a time, a to-do without one on the day in view, and a to-do with no day from Sometime; the mark given is kept.#[test]fn one_line_adds_an_event_with_a_time_and_a_todo_without() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);let pill = ask(&handle, "days.read_line", json!({ "words": "Dinner with Rose Thursday 7pm", "timezone": ZONE, "today": TODAY, "where": "days" })); assert_eq!((pill["title"].clone(), pill["pill"].clone(), pill["kind"].clone()), (json!("Dinner with Rose"), json!("Thu 26 Nov · 19:00"), json!("event"))); assert_eq!(pill["marks"], json!(["fork-knife"]));let made = ask(&handle, "days.add", json!({ "words": "Dinner with Rose Thursday 7pm", "timezone": ZONE, "today": TODAY, "where": "days", "mark": "fork-knife" })); assert_eq!(made["table"], json!("event")); ask(&handle, "days.add", json!({ "words": "Renew passport form", "timezone": ZONE, "today": TODAY, "where": "days", "dayInView": "2026-11-24" })); ask(&handle, "days.add", json!({ "words": "Fix the bathroom tap", "timezone": ZONE, "today": TODAY, "where": "sometime" })); assert_eq!( lines(&span(&handle, "2026-11-24", "2026-11-26")), ["2026-11-24: ○ Renew passport form", "25 · a quiet day", "2026-11-26: 19:00 [fork-knife] Dinner with Rose to 20:00"] );let sometime = ask(&handle, "days.sometime", json!({})); assert_eq!(sometime["groups"][0]["name"], json!("No group")); assert_eq!(sometime["groups"][0]["rows"][0]["words"], json!("Fix the bathroom tap"));}/// RULE (DECISIONS.md, Structure): the month sheet gives each day the drawn marks there (a birthday its cake) and whether anything else is on it, a many-day event on every day it covers.#[test]fn the_month_gives_each_day_its_marks_and_whether_anything_else_is_there() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle); sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, created_at, updated_at) VALUES ('ev-trip', 'Away', '2026-11-10T00:00:00.000Z', '2026-11-11T23:59:59.999Z', 1, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"); sql(&handle, "UPDATE cotton_events SET mark = 'suitcase' WHERE id = 'ev-trip'"); sql(&handle, "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at) VALUES ('td-x', '$WS', 'Something', 'open', '2026-11-11T00:00:00.000Z', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"); sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, created_at, updated_at) VALUES ('pe-m', '$WS', 'MeenakshiInvented', 11, 21, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");let answer = ask(&handle, "days.month", json!({ "timezone": ZONE, "today": TODAY, "month": "2026-11" })); assert_eq!(answer["title"], json!("November 2026"));let day = |n: usize| answer["days"][n - 1].clone(); assert_eq!(day(10), json!({ "day": "2026-11-10", "marks": ["suitcase"], "other": false, "today": false }));// The undone to-do of the 11th is on today now, not on its own day. assert_eq!(day(11), json!({ "day": "2026-11-11", "marks": ["suitcase"], "other": false, "today": false })); assert_eq!(day(20), json!({ "day": "2026-11-20", "marks": [], "other": true, "today": true })); assert_eq!(day(21)["marks"], json!(["cake"])); assert_eq!(answer["days"].as_array().unwrap().len(), 30);}pub(crate) fn todo_in(handle: &CottonHandle, id: &str, title: &str, due: Option<&str>) {let due = due.map_or("NULL".to_string(), |due| format!("'{due}'")); sql(handle, &format!("INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at) VALUES ('{id}', '$WS', '{title}', 'open', {due}, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"));}/// RULE (DECISIONS.md, 20 Nov 2026): Sometime lists every to-do with no day, under the groups with their counts, No group last; two groups with one name are one (the oldest's id, both groups' to-dos) and nothing is deleted; choosing a group shows only its to-dos in Days, the month and Sometime, events and birthdays hidden; a to-do added while a group is chosen goes into it; days.change files a to-do into a group and out of the others.#[test]fn groups_fold_by_name_filter_every_view_and_take_what_is_added() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);for n in0..5 { todo_in(&handle, &format!("00000000-0000-4000-8000-00000000010{n}"), &format!("Home thing {n}"), None); } todo_in(&handle, "00000000-0000-4000-8000-000000000200", "Loose end", None); todo_in(&handle, "00000000-0000-4000-8000-000000000201", "Paint the door", Some("2026-11-21T00:00:00.000Z")); todo_in(&handle, "00000000-0000-4000-8000-000000000202", "Buy stamps", Some("2026-11-21T00:00:00.000Z")); sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, created_at, updated_at) VALUES ('ev-g', 'Dinner', '2026-11-21T19:00:00.000Z', '2026-11-21T20:00:00.000Z', 0, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"); sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, created_at, updated_at) VALUES ('pe-g', '$WS', 'AkashInvented', 11, 21, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");let home = ask(&handle, "groups.create", json!({ "table": "todo", "name": "Home", "records": ["00000000-0000-4000-8000-000000000100", "00000000-0000-4000-8000-000000000101", "00000000-0000-4000-8000-000000000102","00000000-0000-4000-8000-000000000201" ] }));let home = home["id"].as_str().or_else(|| home["group"]["id"].as_str()).expect("a group id").to_string();// The same name made again on another device, later: one group to the person. sql(&handle, "INSERT INTO cotton_groups (id, workspace_id, table_id, name, position, created_at, updated_at) VALUES ('gr-home-again', '$WS', 'todo', ' home ', 5, '2099-01-01T00:00:00.000Z', '2099-01-01T00:00:00.000Z')"); sql(&handle, "INSERT INTO cotton_group_members (id, workspace_id, group_id, record_id, place, created_at, updated_at) VALUES ('gm-1', '$WS', 'gr-home-again', '00000000-0000-4000-8000-000000000103', 1, '2099-01-01T00:00:00.000Z', '2099-01-01T00:00:00.000Z'), ('gm-2', '$WS', 'gr-home-again', '00000000-0000-4000-8000-000000000104', 2, '2099-01-01T00:00:00.000Z', '2099-01-01T00:00:00.000Z')");let groups = ask(&handle, "days.groups", json!({ "timezone": ZONE, "today": TODAY })); assert_eq!(groups["all"], json!("All")); assert_eq!(groups["count"], json!(8)); assert_eq!(groups["groups"], json!([{ "id": home, "name": "Home", "count": 6 }]), "{groups}");let sometime = ask(&handle, "days.sometime", json!({ "timezone": ZONE, "today": TODAY }));let heads: Vec<(String, i64, usize)> = sometime["groups"] .as_array() .unwrap() .iter() .map(|g| (g["name"].as_str().unwrap().to_string(), g["count"].as_i64().unwrap(), g["rows"].as_array().unwrap().len())) .collect(); assert_eq!(heads, [("Home".to_string(), 5, 5), ("No group".to_string(), 1, 1)], "{sometime}"); assert!(sometime["groups"][0].get("more").is_none());// The filter, by either id of the fold.for asked in [home.as_str(), "gr-home-again"] {let only = ask(&handle, "days.span", json!({ "timezone": ZONE, "today": TODAY, "from": "2026-11-21", "to": "2026-11-21", "group": asked })); assert_eq!(lines(&only), ["2026-11-21: ○ Paint the door"], "{only}"); }let month = ask(&handle, "days.month", json!({ "timezone": ZONE, "today": TODAY, "month": "2026-11", "group": home })); assert_eq!(month["days"][20], json!({ "day": "2026-11-21", "marks": [], "other": true, "today": false }));let all = ask(&handle, "days.month", json!({ "timezone": ZONE, "today": TODAY, "month": "2026-11" })); assert_eq!(all["days"][20]["marks"], json!(["cake"]));let one = ask(&handle, "days.sometime", json!({ "timezone": ZONE, "today": TODAY, "group": "gr-home-again" })); assert_eq!((one["groups"].as_array().unwrap().len(), one["count"].clone()), (1, json!(5)));// Added while Home is chosen: into Home, a to-do even with a time.let made = ask(&handle, "days.add", json!({ "words": "Fix the gate Saturday 10am", "timezone": ZONE, "today": TODAY, "where": "days", "group": "gr-home-again" })); assert_eq!((made["table"].clone(), made["day"].clone(), made["time"].clone()), (json!("todo"), json!("2026-11-21"), json!("10:00")));let only = ask(&handle, "days.span", json!({ "timezone": ZONE, "today": TODAY, "from": "2026-11-21", "to": "2026-11-21", "group": home })); assert_eq!(lines(&only), ["2026-11-21: 10:00 ○ Fix the gate | ○ Paint the door"], "{only}");// Filed by the sheet: into Home (the oldest), then out of every group.let stamps = "00000000-0000-4000-8000-000000000202"; ask(&handle, "days.change", json!({ "table": "todo", "id": stamps, "group": "gr-home-again", "timezone": ZONE }));let sheet = ask(&handle, "days.item", json!({ "table": "todo", "id": stamps, "timezone": ZONE, "today": TODAY })); assert_eq!(sheet["group"], json!({ "id": home, "name": "Home" })); ask(&handle, "days.change", json!({ "table": "todo", "id": stamps, "group": null, "timezone": ZONE }));let sheet = ask(&handle, "days.item", json!({ "table": "todo", "id": stamps, "timezone": ZONE, "today": TODAY })); assert_eq!(sheet["group"], Value::Null);let groups = ask(&handle, "days.groups", json!({ "timezone": ZONE, "today": TODAY })); assert_eq!(groups["groups"][0]["count"], json!(7), "both Home groups still stand: {groups}");}/// RULE (DECISIONS.md, 20 Nov 2026): a birthday is a month and a day with no time and no zone: in India, the UK and the US west alike it is on its own date in the list and in the month, and the month's cakes sit on the list's days.#[test]fn a_birthday_is_on_its_date_in_every_zone_in_the_list_and_the_month() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle); sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, created_at, updated_at) VALUES ('pe-a', '$WS', 'AshaInvented', 11, 21, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'), ('pe-b', '$WS', 'BilalInvented', 11, 23, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'), ('pe-c', '$WS', 'ChenInvented', 12, 1, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')"); sql(&handle, "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, created_at, updated_at) VALUES ('pe-d', '$WS', 'DaraInvented', 11, 23, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");for zone in ["Asia/Kolkata", "Europe/London", "America/Los_Angeles"] {let list = ask(&handle, "days.span", json!({ "timezone": zone, "today": TODAY, "from": "2026-11-21", "to": "2026-12-01" })); assert_eq!( lines(&list), ["2026-11-21: [cake] Asha Invented's birthday","22 · a quiet day","2026-11-23: [cake] Bilal Invented's birthday | [cake] Dara Invented's birthday","24 – 30 · seven quiet days","2026-12-01: [cake] Chen Invented's birthday", ],"{zone}" );let month = ask(&handle, "days.month", json!({ "timezone": zone, "today": TODAY, "month": "2026-11" }));let cakes: Vec<&str> = month["days"].as_array().unwrap().iter().filter(|d| d["marks"] == json!(["cake"])).map(|d| d["day"].as_str().unwrap()).collect(); assert_eq!(cakes, ["2026-11-21", "2026-11-23"], "{zone}");// November 2026 begins on a Sunday: six blank cells in a week from Monday, none from Sunday; six weeks always. assert_eq!((month["lead"].clone(), month["weeks"].clone()), (json!(6), json!(6)), "{zone}");let sunday = ask(&handle, "days.month", json!({ "timezone": zone, "today": TODAY, "month": "2026-11", "weekStart": 7 })); assert_eq!(sunday["lead"], json!(0)); }}/// RULE (DECISIONS.md, 20 Nov 2026): an evening past midnight is one row on its first day, and the marks offered are only drawn ones, matches first.#[test]fn an_evening_past_midnight_is_one_row_and_marks_come_drawn() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle); sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, created_at, updated_at) VALUES ('ev-late', 'Party at Rose''s', '2026-11-21T22:00:00.000Z', '2026-11-22T02:00:00.000Z', 0, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");// Nothing lies after the party: the list ends on its day, with no fold after it (21 Nov 2026).let party = span(&handle, "2026-11-21", "2026-11-22"); assert_eq!(lines(&party), ["2026-11-21: 22:00 · Party at Rose's to 2:00"]); assert_eq!(party["end"]["after"], json!("2026-11-21"));let offered = ask(&handle, "days.marks", json!({ "words": "Dentist at 4" })); assert_eq!(offered["marks"][0]["id"], json!("tooth")); assert!(offered["marks"].as_array().unwrap().iter().all(|m| m["strokes"].as_array().is_some_and(|s| !s.is_empty())));}/// RULE (STALE, 21 Nov 2026): a note saved from a sheet opened on an older note, while another device or the assistant changed it, is/// merged into the newer one line by line (`note_base`, the note the sheet loaded) and the person is told; a sheet that sends no base/// saves as before.#[test]fn a_note_saved_from_an_older_sheet_is_merged_into_the_newer_note() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);let made = ask(&handle, "days.add", json!({ "words": "Pack for Hampi", "timezone": ZONE, "today": TODAY, "where": "sometime" }));let id = made["id"].as_str().expect("the todo's id").to_string();let old = "- [ ] Torch\n- [ ] Hat"; ask(&handle, "days.change", json!({ "table": "todo", "id": id, "note": old, "timezone": ZONE }));// The assistant adds a line while the sheet stands open on `old`. sql(&handle, &format!("UPDATE cotton_todos SET notes = '- [ ] Torch\n- [ ] Hat\n- [ ] Water bottle' WHERE id = '{id}'"));let saved = ask(&handle, "days.change", json!({ "table": "todo", "id": id, "note": "- [x] Torch\n- [ ] Hat", "note_base": old, "timezone": ZONE })); assert_eq!(saved["merged"], json!(true), "{saved}"); assert_eq!(saved["said"], json!("This changed on another device while you were writing. Your changes are added to it."));let sheet = ask(&handle, "days.item", json!({ "table": "todo", "id": id, "timezone": ZONE, "today": TODAY })); assert_eq!(sheet["note"], json!("- [x] Torch\n- [ ] Hat\n- [ ] Water bottle"), "the tick and the newer line");// With no base, the sheet's note is the note.let plain = ask(&handle, "days.change", json!({ "table": "todo", "id": id, "note": "Just the torch", "timezone": ZONE })); assert!(plain.get("merged").is_none()); assert_eq!(ask(&handle, "days.item", json!({ "table": "todo", "id": id, "timezone": ZONE, "today": TODAY }))["note"], json!("Just the torch"));}#[test]fn a_sheet_opened_on_no_note_keeps_the_note_the_assistant_wrote_since() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);let made = ask(&handle, "days.add", json!({ "words": "Plan the Coorg drive", "timezone": ZONE, "today": TODAY, "where": "sometime" }));let id = made["id"].as_str().expect("the todo's id").to_string();// The sheet opens on no note; the assistant writes one meanwhile. sql(&handle, &format!("UPDATE cotton_todos SET notes = 'Fill up at Mysore' WHERE id = '{id}'"));let saved = ask(&handle, "days.change", json!({ "table": "todo", "id": id, "note": "Leave by six", "note_base": "", "timezone": ZONE })); assert_eq!(saved["merged"], json!(true), "{saved}");let note = ask(&handle, "days.item", json!({ "table": "todo", "id": id, "timezone": ZONE, "today": TODAY }))["note"].as_str().unwrap_or_default().to_string(); assert!(note.contains("Leave by six") && note.contains("Fill up at Mysore"), "both writers' words: {note}");// Emptied on an old copy: the words the assistant added since stay. sql(&handle, &format!("UPDATE cotton_todos SET notes = 'Leave by six\nFill up at Mysore\nTolls take cash' WHERE id = '{id}'")); ask(&handle, "days.change", json!({ "table": "todo", "id": id, "note": null, "note_base": "Leave by six\nFill up at Mysore", "timezone": ZONE }));let left = ask(&handle, "days.item", json!({ "table": "todo", "id": id, "timezone": ZONE, "today": TODAY })); assert_eq!(left["note"], json!("Tolls take cash"), "{left}");}/// RULE (LAUNCH.md, 22 Nov 2026): Days asks leave to notify at the moment an item first earns a reminder, never at a/// launch: an add or a move that gives an item an alert answers `platform_action: request_notifications` on a phone/// that never asked; one that gives none (a to-do with only a day) does not; once the platform says it asked, never again.#[test]fn leave_to_notify_is_asked_when_an_item_first_earns_a_reminder() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);// Two days ahead by the clock: the reminder pass reads the real now.let ahead = (chrono::Utc::now().date_naive() + chrono::Duration::days(2)).to_string();let add = |words: &str, time: Option<&str>| {letmut request = json!({ "words": words, "timezone": ZONE, "today": TODAY, "where": "days", "day": ahead });ifletSome(time) = time { request["time"] = json!(time); } ask(&handle, "days.add", request) };let quiet = add("Invented plant the bulbs", None); assert_eq!(quiet["table"], json!("todo")); assert!(quiet.get("platform_action").is_none(), "a to-do with only a day never alerts: {quiet}");let moved = ask(&handle, "days.move", json!({ "table": "todo", "id": quiet["id"], "day": ahead, "time": "09:30", "timezone": ZONE, "today": TODAY })); assert_eq!(moved["platform_action"], json!("request_notifications"), "given a time, it alerts: {moved}");let timed = add("Invented dentist", Some("10:00")); assert_eq!(timed["table"], json!("event")); assert_eq!(timed["platform_action"], json!("request_notifications"), "{timed}");// Why comes with the ask, for the phone to show before the OS asks. assert_eq!(timed["leave"]["title"], json!("Reminders"), "{timed}"); assert!(timed["leave"]["body"].as_str().is_some_and(|body| body.contains("remind you")), "{timed}"); assert_eq!(timed["leave"]["go"], json!("Continue"), "{timed}"); assert_eq!(timed["leave"]["notNow"], json!("Not now"), "{timed}"); assert!(quiet.get("leave").is_none(), "{quiet}"); ask(&handle, "device.notifications.asked", json!({ "at": chrono::Utc::now().to_rfc3339() }));let after = add("Invented call the plumber", Some("11:00")); assert!(after.get("platform_action").is_none(), "asked once, never again: {after}");}/// RULE (DECISIONS.md, Alerts): the pass that schedules (`reminders.reconcile`, what both phones apply) keeps Days'/// rule too: a to-do with only a day never alerts; a to-do given a time and an event do. Only `reminders.desired`/// knew it, so every day-only to-do was scheduled for nine in the morning.#[test]fn the_scheduling_pass_keeps_a_day_only_todo_quiet_in_days() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);let ahead = (chrono::Utc::now().date_naive() + chrono::Duration::days(2)).to_string();let add = |words: &str, time: Option<&str>| {letmut request = json!({ "words": words, "timezone": ZONE, "today": TODAY, "where": "days", "day": ahead });ifletSome(time) = time { request["time"] = json!(time); } ask(&handle, "days.add", request) };let quiet = add("Invented plant the bulbs", None);let event = add("Invented dentist", Some("10:00"));let plan = ask(&handle, "reminders.reconcile", json!({ "args": { "timeZone": ZONE, "held": [], "prefs": {} } }));let named: Vec<String> = plan["schedule"].as_array().unwrap().iter() .map(|row| row.to_string()).collect(); assert!(named.iter().any(|row| row.contains(event["id"].as_str().unwrap())), "the event is scheduled: {plan}"); assert!(!named.iter().any(|row| row.contains(quiet["id"].as_str().unwrap())), "the day-only to-do is not: {plan}");}/// RULE (DECISIONS.md, Alerts): an event's sheet marks the alert that stands: one with no alert stored shows the ten/// minutes it reminds at; "No alert" is stored as none, shown as No alert, and the event earns no reminder; null takes it/// back to the ten minutes; a lead the sheet does not offer (an assistant's 15) is placed among its choices.#[test]fn an_events_sheet_marks_the_alert_that_stands_and_no_alert_is_kept() {let dir = TempDir::new().unwrap();let handle = phone(&dir); zone(&handle);// Two days ahead by the clock: the reminder pass reads the real now.let ahead = (chrono::Utc::now().date_naive() + chrono::Duration::days(2)).to_string();let event = ask(&handle, "days.add", json!({ "words": "Invented dentist", "time": "10:00", "timezone": ZONE, "today": TODAY, "where": "days", "day": ahead }));let id = event["id"].clone();let sheet = || ask(&handle, "days.item", json!({ "table": "event", "id": id, "timezone": ZONE, "today": TODAY }));let on = |sheet: &Value| -> Vec<Value> { sheet["alerts"].as_array().expect("alert choices").iter().filter(|choice| choice["on"] == json!(true)).map(|choice| choice["alert"].clone()).collect() };let offered = |sheet: &Value| -> Vec<Value> { sheet["alerts"].as_array().expect("alert choices").iter().map(|choice| choice["alert"].clone()).collect() };let reminded = || -> bool {let due = crate::phone::reminders::call(&handle, &json!({ "args": { "timeZone": ZONE } })).expect("reminders"); due["reminders"].as_array().into_iter().flatten().any(|reminder| reminder["recordId"] == id) };let fresh = sheet(); assert_eq!((fresh["alert"].clone(), on(&fresh)), (json!(10), vec![json!(10)]), "{fresh}"); assert_eq!(offered(&fresh), [json!("none"), json!(0), json!(10), json!(30), json!(60)]); assert!(reminded(), "no alert stored reminds at the ten minutes"); ask(&handle, "days.change", json!({ "table": "event", "id": id, "alert": "none", "timezone": ZONE }));let quiet = sheet(); assert_eq!((quiet["alert"].clone(), on(&quiet)), (json!("none"), vec![json!("none")]), "{quiet}"); assert!(!reminded(), "No alert earns no reminder"); ask(&handle, "days.change", json!({ "table": "event", "id": id, "alert": null, "timezone": ZONE })); assert_eq!(on(&sheet()), [json!(10)]); assert!(reminded(), "back to the default, it reminds again"); sql(&handle, &format!("UPDATE cotton_events SET alert = 15 WHERE id = '{}'", id.as_str().unwrap()));let odd = sheet(); assert_eq!(offered(&odd), [json!("none"), json!(0), json!(10), json!(15), json!(30), json!(60)]); assert_eq!(on(&odd), [json!(15)]); assert_eq!(refused(&handle, "days.change", json!({ "table": "event", "id": id, "alert": "never", "timezone": ZONE })).0, "bad_request");}