//! The record tools an assistant edits by hand — todos, events, notes and the //! journal, people and comments. //! //! Every case that exercises one of this group's 32 tools is here; a case for //! another group's tool belongs in that group's file. //! //! It drives `dispatch::call_tool` over a fake `ToolServices` on a real file //! rather than the server's `/v1/mcp` endpoint, because the handlers live in //! this crate and the phone links them without ever building the server — so //! what is under test is still the answer an assistant actually receives. mod support; use std::sync::atomic::{AtomicU64, Ordering}; use cotton_store::schema::ddl::SCHEMA_VERSION; use cotton_store::protocol::derived_id::{ link_id_for, note_attachment_id, project_link_id, record_link_id, LinkRow, }; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use support::harness::Harness; use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, mint_token, mint_token_ref}; /// When every seeded row says it was written. const AT: &str = "2026-08-22T10:00:00.000Z"; const KOLKATA: &str = "Asia/Kolkata"; /// 4 Sep 2026 in Kolkata: midnight and 09:00, as instants. const SEP4_MIDNIGHT: &str = "2026-09-03T18:30:00.000Z"; const SEP4_0900: &str = "2026-09-04T03:30:00.000Z"; // ── the fixture ───────────────────────────────────────────────────────────── /// An op the way a device would mint one. The ids are DERIVED from a /// per-process counter, never random. fn op(table: &str, row_id: &str, patch: Value) -> Value { static NEXT: AtomicU64 = AtomicU64::new(0); let n = NEXT.fetch_add(1, Ordering::Relaxed); json!({ "opId": format!("01J{:023}", n), "deviceId": "device:seed", "kind": "upsert", "table": table, "rowId": row_id, "patch": patch, "hlc": format!("1700000000{:03}:0000:device:seed", n), "schemaVersion": SCHEMA_VERSION, }) } /// Fold a batch of seed ops the way a device's push folds them. The server's /// copy of this went through `POST /v1/sync/push`; the fold under that route is /// what a suite about a TOOL actually needed of it, and a rejection is still a /// hard failure because a seed that half-landed makes every assertion after it /// a lie. fn seed(h: &Harness, ops: Vec) { h.seed(&ops); } /// `cotton_news_settings.timezone` is the one workspace-scoped zone in the /// file, written straight in: nothing on the MCP surface sets it. fn seed_zone(h: &Harness, timezone: &str) { h.with(|db| { db.run( "INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at)\ \n VALUES (?, ?, ?, ?)", &[ SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(timezone.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) }) .expect("the zone lands"); } /// One text column of one row, read off the file itself. fn column(h: &Harness, table: &str, column: &str, id: &str) -> Option { h.with(|db| { db.get( &format!("SELECT {column} AS value FROM {table} WHERE id = ?"), &[SqlValue::Text(id.to_string())], ) }) .expect("the read runs") .and_then(|row| row.text("value").map(str::to_string)) } fn number(h: &Harness, table: &str, name: &str, id: &str) -> Option { h.with(|db| { db.get( &format!("SELECT {name} AS value FROM {table} WHERE id = ?"), &[SqlValue::Text(id.to_string())], ) }) .expect("the read runs") .and_then(|row| row.int("value")) } fn due_of(h: &Harness, id: &str) -> Option { column(h, "cotton_todos", "due_at", id) } /// A uuid-shaped id a fixture can name. DERIVED, never random. fn fixture_id(label: &str) -> String { support::harness::synthetic_uuid(label) } struct Seeded { h: Harness, secret: String, timed: String, date_only: String, undated: String, timed_too: String, } fn seeded_harness(zone: Option<&str>) -> Seeded { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); if let Some(zone) = zone { seed_zone(&h, zone); } let timed = fixture_id("todo-timed"); let date_only = fixture_id("todo-date-only"); let undated = fixture_id("todo-undated"); let timed_too = fixture_id("todo-timed-too"); let base = |title: &str, due: Option<&str>| -> Value { json!({ "title": title, "status": "open", "priority": 0, "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, "due_at": due, }) }; seed( &h, vec![ op( "cotton_todos", &timed, base("call the bank", Some(SEP4_0900)), ), op( "cotton_todos", &date_only, base("water the plants", Some(SEP4_MIDNIGHT)), ), op("cotton_todos", &undated, base("read the sqlite book", None)), // 10 Sep, 18:00 Kolkata. op( "cotton_todos", &timed_too, base("file the return", Some("2026-09-10T12:30:00.000Z")), ), ], ); Seeded { h, secret, timed, date_only, undated, timed_too, } } fn id_of(value: &Value) -> String { value["id"].as_str().expect("an id").to_string() } // ── update_todo — the due as a day and a time ─────────────────────────────── #[test] fn drops_the_time_and_keeps_the_day_due_time_null() { let s = seeded_harness(Some(KOLKATA)); let result = call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueTime": Value::Null }), ); assert_eq!(result["due_at"], SEP4_MIDNIGHT); assert_eq!(result["dueDate"], "2026-09-04"); assert_eq!(result["dueTime"], Value::Null); assert_eq!(due_of(&s.h, &s.timed).as_deref(), Some(SEP4_MIDNIGHT)); } #[test] fn sets_an_hour_on_a_date_only_todo_and_keeps_its_day() { let s = seeded_harness(Some(KOLKATA)); let result = call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.date_only, "dueTime": "18:00" }), ); assert_eq!(result["dueDate"], "2026-09-04"); assert_eq!(result["dueTime"], "18:00"); assert_eq!( due_of(&s.h, &s.date_only).as_deref(), Some("2026-09-04T12:30:00.000Z") ); } #[test] fn moves_the_day_and_keeps_the_hour_due_date_alone() { let s = seeded_harness(Some(KOLKATA)); call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueDate": "2026-09-10" }), ); assert_eq!( due_of(&s.h, &s.timed).as_deref(), Some("2026-09-10T03:30:00.000Z") ); } #[test] fn gives_an_undated_todo_a_day_and_due_date_null_clears_everything() { let s = seeded_harness(Some(KOLKATA)); call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.undated, "dueDate": "2026-09-04" }), ); assert_eq!(due_of(&s.h, &s.undated).as_deref(), Some(SEP4_MIDNIGHT)); call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.undated, "dueDate": Value::Null }), ); assert_eq!(due_of(&s.h, &s.undated), None); } #[test] fn reads_the_pair_in_the_zone_the_call_named_over_the_workspaces() { let s = seeded_harness(Some(KOLKATA)); // 09:00 Kolkata is 23:30 the evening before in New York. let result = call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueTime": "08:00", "timezone": "America/New_York" }), ); assert_eq!(result["dueDate"], "2026-09-03"); assert_eq!(result["dueTime"], "08:00"); assert_eq!( due_of(&s.h, &s.timed).as_deref(), Some("2026-09-03T12:00:00.000Z") ); } #[test] fn refuses_an_hour_on_an_undated_todo_both_spellings_at_once_and_a_bad_clock() { let s = seeded_harness(Some(KOLKATA)); let no_day = call_tool_raw( &s.h, &s.secret, "update_todo", json!({ "id": s.undated, "dueTime": "09:00" }), ); assert!(no_day.is_error); assert!( no_day.text.contains("a time needs a day"), "{}", no_day.text ); let both = call_tool_raw( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueAt": SEP4_0900, "dueDate": "2026-09-04" }), ); assert!(both.is_error); assert!(both.text.contains("not both"), "{}", both.text); let clock = call_tool_raw( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueTime": "9am" }), ); assert!(clock.is_error); assert!(clock.text.contains("HH:mm"), "{}", clock.text); } #[test] fn refuses_a_day_when_the_file_has_no_zone_and_none_was_named_never_utc() { let s = seeded_harness(None); let refused = call_tool_raw( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueTime": Value::Null }), ); assert!(refused.is_error); assert!(refused.text.contains("timezone"), "{}", refused.text); // The raw instant still works without a zone — it names the moment itself. call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueAt": SEP4_MIDNIGHT }), ); assert_eq!(due_of(&s.h, &s.timed).as_deref(), Some(SEP4_MIDNIGHT)); } #[test] fn still_takes_due_at_and_answers_the_pair_beside_it() { let s = seeded_harness(Some(KOLKATA)); let result = call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.undated, "dueAt": SEP4_0900 }), ); assert_eq!(result["due_at"], SEP4_0900); assert_eq!(result["dueDate"], "2026-09-04"); assert_eq!(result["dueTime"], "09:00"); } // ── create_todo — a day is enough ─────────────────────────────────────────── #[test] fn files_a_date_only_todo_at_the_days_local_midnight() { let s = seeded_harness(Some(KOLKATA)); let made = call_tool( &s.h, &s.secret, "create_todo", json!({ "title": "renew the passport", "dueDate": "2026-09-04" }), ); assert_eq!(made["due_at"], SEP4_MIDNIGHT); assert_eq!(made["dueDate"], "2026-09-04"); assert_eq!(made["dueTime"], Value::Null); assert_eq!(due_of(&s.h, &id_of(&made)).as_deref(), Some(SEP4_MIDNIGHT)); } #[test] fn files_a_timed_todo_from_the_pair_and_anchors_a_repeating_one_on_it() { let s = seeded_harness(Some(KOLKATA)); let made = call_tool( &s.h, &s.secret, "create_todo", json!({ "title": "stand-up", "dueDate": "2026-09-04", "dueTime": "09:00" }), ); assert_eq!(due_of(&s.h, &id_of(&made)).as_deref(), Some(SEP4_0900)); let series = call_tool( &s.h, &s.secret, "create_todo", json!({ "title": "rent", "dueDate": "2026-09-02", "rrule": "FREQ=MONTHLY" }), ); assert_eq!(series["repeats"], "FREQ=MONTHLY"); assert_eq!(series["due_at"], "2026-09-01T18:30:00.000Z"); } #[test] fn refuses_a_time_without_a_day_and_a_null_where_nothing_is_to_clear() { let s = seeded_harness(Some(KOLKATA)); let time_only = call_tool_raw( &s.h, &s.secret, "create_todo", json!({ "title": "x", "dueTime": "09:00" }), ); assert!(time_only.is_error); assert!( time_only.text.contains("dueTime needs dueDate"), "{}", time_only.text ); let nulled = call_tool_raw( &s.h, &s.secret, "create_todo", json!({ "title": "x", "dueDate": Value::Null }), ); assert!(nulled.is_error); } // ── list_todos answers the pair ───────────────────────────────────────────── #[test] fn lists_due_date_due_time_in_the_workspaces_zone_and_names_the_zone() { let s = seeded_harness(Some(KOLKATA)); let listed = call_tool(&s.h, &s.secret, "list_todos", json!({})); assert_eq!(listed["timezone"], KOLKATA); let todos = listed["todos"].as_array().expect("todos").clone(); let find = |id: &str| -> Value { todos .iter() .find(|todo| todo["id"] == id) .cloned() .unwrap_or(Value::Null) }; let timed = find(&s.timed); assert_eq!(timed["dueDate"], "2026-09-04"); assert_eq!(timed["dueTime"], "09:00"); let date_only = find(&s.date_only); assert_eq!(date_only["dueDate"], "2026-09-04"); assert_eq!(date_only["dueTime"], Value::Null); let undated = find(&s.undated); assert!(undated.is_object(), "the undated todo is listed"); assert!(undated.get("dueDate").is_none()); } #[test] fn answers_only_the_raw_instant_when_the_file_has_no_zone() { let s = seeded_harness(None); let listed = call_tool(&s.h, &s.secret, "list_todos", json!({})); assert!(listed.get("timezone").is_none()); let todos = listed["todos"].as_array().expect("todos").clone(); let timed = todos .iter() .find(|todo| todo["id"] == s.timed) .expect("the timed todo"); assert_eq!(timed["dueAt"], SEP4_0900); assert!(timed.get("dueDate").is_none()); } // ── update_todos — one patch, many todos ──────────────────────────────────── #[test] fn drops_the_time_from_every_one_each_keeping_its_own_day() { let s = seeded_harness(Some(KOLKATA)); let result = call_tool( &s.h, &s.secret, "update_todos", json!({ "ids": [s.timed, s.timed_too, s.date_only], "dueTime": Value::Null }), ); let updated: Vec = result["updated"] .as_array() .expect("updated") .iter() .map(id_of) .collect(); assert_eq!( updated, vec![s.timed.clone(), s.timed_too.clone(), s.date_only.clone()] ); assert_eq!(due_of(&s.h, &s.timed).as_deref(), Some(SEP4_MIDNIGHT)); assert_eq!( due_of(&s.h, &s.timed_too).as_deref(), Some("2026-09-09T18:30:00.000Z") ); assert_eq!(due_of(&s.h, &s.date_only).as_deref(), Some(SEP4_MIDNIGHT)); assert!(result.get("missing").is_none()); } #[test] fn files_a_batch_onto_a_day_and_clears_a_batchs_dues() { let s = seeded_harness(Some(KOLKATA)); call_tool( &s.h, &s.secret, "update_todos", json!({ "ids": [s.undated, s.timed], "dueDate": "2026-09-10" }), ); assert_eq!( due_of(&s.h, &s.undated).as_deref(), Some("2026-09-09T18:30:00.000Z") ); // The timed one keeps its hour on the new day. assert_eq!( due_of(&s.h, &s.timed).as_deref(), Some("2026-09-10T03:30:00.000Z") ); call_tool( &s.h, &s.secret, "update_todos", json!({ "ids": [s.undated, s.timed], "dueDate": Value::Null }), ); assert_eq!(due_of(&s.h, &s.undated), None); assert_eq!(due_of(&s.h, &s.timed), None); } #[test] fn reports_a_missing_id_and_a_refused_row_and_still_changes_the_rest() { let s = seeded_harness(Some(KOLKATA)); let ghost = fixture_id("todo-ghost"); let result = call_tool( &s.h, &s.secret, "update_todos", json!({ "ids": [s.date_only, ghost, s.undated], "dueTime": "18:00" }), ); let updated: Vec = result["updated"] .as_array() .expect("updated") .iter() .map(id_of) .collect(); assert_eq!(updated, vec![s.date_only.clone()]); assert_eq!(result["missing"], json!([ghost])); let refused = result["refused"].as_array().expect("refused"); assert_eq!(refused.len(), 1); assert_eq!(refused[0]["id"], s.undated); assert!( refused[0]["reason"] .as_str() .is_some_and(|reason| reason.contains("a time needs a day")), "{}", refused[0] ); assert_eq!( due_of(&s.h, &s.date_only).as_deref(), Some("2026-09-04T12:30:00.000Z") ); assert_eq!(due_of(&s.h, &s.undated), None); } #[test] fn completes_and_re_prioritises_a_batch_completed_at_moving_in_step() { let s = seeded_harness(Some(KOLKATA)); call_tool( &s.h, &s.secret, "update_todos", json!({ "ids": [s.timed, s.date_only], "status": "done", "priority": "high" }), ); for id in [&s.timed, &s.date_only] { assert_eq!( column(&s.h, "cotton_todos", "status", id).as_deref(), Some("done") ); assert_eq!(number(&s.h, "cotton_todos", "priority", id), Some(1)); assert!(column(&s.h, "cotton_todos", "completed_at", id).is_some()); } } #[test] fn every_change_is_a_sync_op_the_phone_pulls() { let s = seeded_harness(Some(KOLKATA)); let before = s.h.cursors(); call_tool( &s.h, &s.secret, "update_todos", json!({ "ids": [s.timed, s.timed_too], "dueTime": Value::Null }), ); let todo_ops: Vec> = s.h.ops_since(&before) .into_iter() .filter(|op| op["tbl"] == "cotton_todos") .collect(); let mut rows: Vec = todo_ops .iter() .map(|op| op["row_id"].as_str().unwrap_or_default().to_string()) .collect(); rows.sort_unstable(); rows.dedup(); let mut expected = vec![s.timed.clone(), s.timed_too.clone()]; expected.sort_unstable(); assert_eq!(rows, expected); // Stamped by the FILE's author (`_meta.author_id`, slice 2c). let author = s.h.file_author(); assert!(todo_ops.iter().all(|op| op["device_id"] == author.as_str())); } #[test] fn refuses_a_title_an_empty_patch_a_bad_id_and_an_empty_list_out_loud() { let s = seeded_harness(Some(KOLKATA)); let titled = call_tool_raw( &s.h, &s.secret, "update_todos", json!({ "ids": [s.timed], "title": "all of them" }), ); assert!(titled.is_error); assert!(titled.text.contains("no title"), "{}", titled.text); let empty = call_tool_raw(&s.h, &s.secret, "update_todos", json!({ "ids": [s.timed] })); assert!(empty.is_error); assert!(empty.text.contains("nothing to change"), "{}", empty.text); let bad_id = call_tool_raw( &s.h, &s.secret, "update_todos", json!({ "ids": ["not-a-uuid"], "dueTime": Value::Null }), ); assert!(bad_id.is_error); assert!(bad_id.text.contains("uuid"), "{}", bad_id.text); let none = call_tool_raw( &s.h, &s.secret, "update_todos", json!({ "ids": [], "dueTime": Value::Null }), ); assert!(none.is_error); } // ── list_todos and update_todo, from `mcpToolGaps.test.ts` ────────────────── #[test] fn shows_the_undated_todo_today_agenda_never_can_and_hides_the_done_one() { let s = seeded_harness(Some(KOLKATA)); call_tool(&s.h, &s.secret, "complete_todo", json!({ "id": s.timed })); let listed = call_tool(&s.h, &s.secret, "list_todos", json!({})); let ids: Vec = listed["todos"] .as_array() .expect("todos") .iter() .map(id_of) .collect(); assert!(ids.contains(&s.undated), "the undated todo is listed"); assert!(!ids.contains(&s.timed), "the completed todo is not"); } #[test] fn filters_by_status_and_a_due_window_drops_the_undated() { let s = seeded_harness(Some(KOLKATA)); call_tool(&s.h, &s.secret, "complete_todo", json!({ "id": s.timed })); let done = call_tool(&s.h, &s.secret, "list_todos", json!({ "status": "done" })); let done_ids: Vec = done["todos"] .as_array() .expect("todos") .iter() .map(id_of) .collect(); assert_eq!(done_ids, vec![s.timed.clone()]); let window = call_tool( &s.h, &s.secret, "list_todos", json!({ "dueAfter": "2026-09-01T00:00:00.000Z", "dueBefore": "2026-09-08T00:00:00.000Z" }), ); let window_ids: Vec = window["todos"] .as_array() .expect("todos") .iter() .map(id_of) .collect(); assert!(window_ids.contains(&s.date_only)); assert!( !window_ids.contains(&s.undated), "a due window is a question about SCHEDULED todos" ); } // ── list_todos pages, and answers one project's todos ─────────────────────── // // A workspace with three hundred open todos, most of them in no project, was // unreadable through this tool: `more: true` with no handle and no project // filter left an assistant planning off whatever fifty rows came first. /// A workspace with more todos than one page — six dated, three undated, and a /// project holding three of them. struct Paged { h: Harness, secret: String, /// The dated todos in the order `list_todos` answers them: soonest first. dated: Vec, /// The undated ones in the order it answers them: newest filed first. undated: Vec, /// The project's members, in the order one page of it reads. filed: Vec, } fn paged_harness() -> Paged { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); let mut ops: Vec = Vec::new(); let mut dated = Vec::new(); for n in 0..6 { let id = fixture_id(&format!("paged-dated-{n}")); ops.push(op( "cotton_todos", &id, json!({ "title": format!("dated {n}"), "status": "open", "priority": 0, "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, "due_at": format!("2026-09-0{}T04:00:00.000Z", n + 1), }), )); dated.push(id); } let mut undated = Vec::new(); for n in 0..3 { let id = fixture_id(&format!("paged-undated-{n}")); ops.push(op( "cotton_todos", &id, json!({ "title": format!("undated {n}"), "status": "open", "priority": 0, "workspace_id": h.workspace_id, "created_at": format!("2026-08-0{}T00:00:00.000Z", n + 1), "updated_at": AT, "due_at": Value::Null, }), )); undated.push(id); } // The undated read newest FIRST, so the last one filed is the first one out. undated.reverse(); let project = fixture_id("paged-project"); ops.push(op( "cotton_memory_projects", &project, json!({ "slug": "clinic", "name": "Clinic", "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), )); let filed = vec![dated[1].clone(), dated[4].clone(), undated[0].clone()]; for id in &filed { ops.push(op( "cotton_project_links", &project_link_id(&project, "todo", id), json!({ "project_id": project, "record_kind": "todo", "record_id": id, "applied_by": "user", "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), )); } seed(&h, ops); Paged { h, secret, dated, undated, filed, } } /// Walk `list_todos` to the end, one page at a time, and hand back every id in /// the order it arrived. fn walk_todos(p: &Paged, filters: Value) -> Vec { let mut walked: Vec = Vec::new(); let mut cursor: Option = None; let mut pages = 0; loop { let mut args = filters.clone(); if let Some(cursor) = &cursor { args["cursor"] = Value::from(cursor.clone()); } let page = call_tool(&p.h, &p.secret, "list_todos", args); pages += 1; assert!(pages <= 20, "the walk does not end: {page}"); walked.extend(page["todos"].as_array().expect("todos").iter().map(id_of)); if page["more"] != Value::Bool(true) { assert!( page.get("nextCursor").is_none(), "a last page hands out no cursor" ); break; } cursor = Some( page["nextCursor"] .as_str() .expect("more: true carries a cursor") .to_string(), ); } assert!(pages > 2, "two at a page is more than two pages here"); walked } #[test] fn pages_the_whole_list_through_next_cursor_and_names_no_todo_twice() { let p = paged_harness(); let walked = walk_todos(&p, json!({ "limit": 2 })); let mut expected = p.dated.clone(); expected.extend(p.undated.clone()); assert_eq!(walked, expected); } #[test] fn answers_one_projects_todos_and_names_the_projects_each_is_in() { let p = paged_harness(); let listed = call_tool(&p.h, &p.secret, "list_todos", json!({ "project": "clinic" })); let ids: Vec = listed["todos"] .as_array() .expect("todos") .iter() .map(id_of) .collect(); assert_eq!(ids, p.filed); assert_eq!(listed["more"], Value::Bool(false)); for todo in listed["todos"].as_array().expect("todos") { assert_eq!(todo["projects"], json!(["clinic"])); } } #[test] fn a_project_filter_pages_too_rather_than_stopping_at_one_page() { let p = paged_harness(); // The membership test cannot be a `WHERE`, so this is the path where the // page is cut in Rust — the one a `LIMIT` would have cut in the wrong place. let walked = walk_todos(&p, json!({ "unfiled": true, "limit": 2 })); let expected: Vec = p .dated .iter() .chain(p.undated.iter()) .filter(|id| !p.filed.contains(id)) .cloned() .collect(); assert_eq!(walked, expected); } #[test] fn unfiled_answers_the_todos_in_no_project_and_none_says_the_same() { let p = paged_harness(); let unfiled = call_tool(&p.h, &p.secret, "list_todos", json!({ "unfiled": true })); let ids: Vec = unfiled["todos"] .as_array() .expect("todos") .iter() .map(id_of) .collect(); assert_eq!(ids.len(), 6); assert!( !ids.iter().any(|id| p.filed.contains(id)), "a todo in a project is not unfiled" ); for todo in unfiled["todos"].as_array().expect("todos") { assert_eq!(todo["projects"], json!([])); } let none = call_tool(&p.h, &p.secret, "list_todos", json!({ "project": "none" })); let none_ids: Vec = none["todos"] .as_array() .expect("todos") .iter() .map(id_of) .collect(); assert_eq!(none_ids, ids); } #[test] fn refuses_a_cursor_it_never_handed_out() { let p = paged_harness(); let answer = call_tool_raw( &p.h, &p.secret, "list_todos", json!({ "cursor": "not-a-cursor-this-tool-minted" }), ); assert!(answer.is_error, "a made-up cursor is refused"); assert!( answer.text.contains("nextCursor"), "the refusal says where a real one comes from: {}", answer.text ); } #[test] fn refuses_a_project_and_unfiled_in_one_call() { let p = paged_harness(); let answer = call_tool_raw( &p.h, &p.secret, "list_todos", json!({ "project": "clinic", "unfiled": true }), ); assert!(answer.is_error, "the two questions contradict each other"); assert!(answer.text.contains("clinic"), "{}", answer.text); } #[test] fn reschedules_a_todo_and_the_change_is_a_sync_op_the_phone_pulls() { let s = seeded_harness(Some(KOLKATA)); let before = s.h.cursors(); let result = call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueAt": "2026-09-11T04:30:00.000Z", "notes": "ask for the form" }), ); assert_eq!(result["due_at"], "2026-09-11T04:30:00.000Z"); assert_eq!(result["notes"], "ask for the form"); let op = s.h.ops_since(&before) .into_iter() .find(|op| op["row_id"] == s.timed) .expect("the todo's own op"); // Stamped by the FILE's author (`_meta.author_id`, slice 2c). assert_eq!(op["device_id"], s.h.file_author().as_str()); assert_eq!(op["tbl"], "cotton_todos"); } #[test] fn clears_a_due_date_with_null_and_moves_status_with_completed_at_in_step() { let s = seeded_harness(Some(KOLKATA)); call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "dueAt": Value::Null }), ); assert_eq!(due_of(&s.h, &s.timed), None); call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "status": "done" }), ); assert!(column(&s.h, "cotton_todos", "completed_at", &s.timed).is_some()); call_tool( &s.h, &s.secret, "update_todo", json!({ "id": s.timed, "status": "open" }), ); assert_eq!(column(&s.h, "cotton_todos", "completed_at", &s.timed), None); } #[test] fn refuses_an_unknown_id_and_an_empty_patch_out_loud() { let s = seeded_harness(Some(KOLKATA)); let ghost = fixture_id("todo-nowhere"); let missing = call_tool_raw( &s.h, &s.secret, "update_todo", json!({ "id": ghost, "notes": "anything" }), ); assert!(missing.is_error); assert!(missing.text.contains("no todo with id"), "{}", missing.text); let empty = call_tool_raw(&s.h, &s.secret, "update_todo", json!({ "id": s.timed })); assert!(empty.is_error); assert!(empty.text.contains("nothing to change"), "{}", empty.text); } #[test] fn complete_todo_stamps_the_moment_and_refuses_an_id_that_is_not_there() { let s = seeded_harness(Some(KOLKATA)); let done = call_tool(&s.h, &s.secret, "complete_todo", json!({ "id": s.timed })); assert_eq!(done["status"], "done"); assert!(done["completed_at"].is_string()); let ghost = fixture_id("todo-gone"); let missing = call_tool_raw(&s.h, &s.secret, "complete_todo", json!({ "id": ghost })); assert!(missing.is_error); assert!(missing.text.contains("no todo with id"), "{}", missing.text); } // ── the calendar: a series, two moved occurrences and a cancellation ──────── // // The shapes are the owner's own calendar, exactly as `mcpEvents.test.ts` has // them: a weekly "Vicky" whose 4 Sep and 11 Sep occurrences were moved, and a // weekly "Call with Bella" with 23 Sep cancelled. /// Where this database lives — never the host's zone, which is UTC. const ZONE: &str = "Europe/London"; const VICKY_GCAL: &str = "7pfkedoofe98utr5qbffl34oab"; const BELLA_GCAL: &str = "m4rbfl24nhk6kqpdu284dcsmu0"; /// The whole of September, both ends inside the window. const SEPTEMBER_FROM: &str = "2026-09-01T00:00:00.000Z"; const SEPTEMBER_TO: &str = "2026-09-30T23:59:59.000Z"; struct Calendar { h: Harness, secret: String, calendar: String, vicky: String, vicky_moved_to_the_8th: String, vicky_moved_to_the_12th: String, bella: String, dinner: String, } /// The calendar above. `zoned: false` builds the same file with NO timezone /// named — the one thing every writer here has to refuse rather than guess. fn calendar_of(zoned: bool) -> Calendar { calendar_with(zoned, true) } /// The same calendar made here, with no Google identity: since Days (20 Nov /// 2026) a Google event's time, title, place, notes and repeat are Google's /// and refused here, so the series logic is driven on the person's own events. fn local_calendar(zoned: bool) -> Calendar { calendar_with(zoned, false) } fn calendar_with(zoned: bool, google: bool) -> Calendar { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); let calendar = fixture_id("calendar"); let vicky = fixture_id("vicky"); let vicky_moved_to_the_8th = fixture_id("vicky-8th"); let vicky_moved_to_the_12th = fixture_id("vicky-12th"); let bella = fixture_id("bella"); let dinner = fixture_id("dinner"); let mut ops = vec![op( "cotton_collections", &calendar, json!({ "kind": "calendar", "name": "Personal", "is_default": true, "workspace_id": h.workspace_id, "created_at": AT, }), )]; if zoned { ops.push(op( "cotton_news_settings", &h.workspace_id, json!({ "workspace_id": h.workspace_id, "timezone": ZONE, "created_at": AT, "updated_at": AT, }), )); } ops.push(op( "cotton_events", &vicky, json!({ "collection_id": calendar, "title": "Vicky", "starts_at": "2026-09-04T06:30:00.000Z", "ends_at": "2026-09-04T07:30:00.000Z", "all_day": false, "rrule": "FREQ=WEEKLY", "gcal_id": VICKY_GCAL, "sync_state": "synced", "created_at": AT, "updated_at": AT, }), )); ops.push(op( "cotton_events", &vicky_moved_to_the_8th, json!({ "collection_id": calendar, "title": "Vicky", "starts_at": "2026-09-08T06:30:00.000Z", "ends_at": "2026-09-08T07:30:00.000Z", "all_day": false, "series_id": vicky, "original_starts_at": "2026-09-04T06:30:00.000Z", "gcal_id": format!("{VICKY_GCAL}_20260904T063000Z"), "sync_state": "synced", "created_at": AT, "updated_at": AT, }), )); ops.push(op( "cotton_events", &vicky_moved_to_the_12th, json!({ "collection_id": calendar, "title": "Vicky", "starts_at": "2026-09-12T06:30:00.000Z", "ends_at": "2026-09-12T07:30:00.000Z", "all_day": false, "series_id": vicky, "original_starts_at": "2026-09-11T06:30:00.000Z", "gcal_id": format!("{VICKY_GCAL}_20260911T063000Z"), "sync_state": "synced", "created_at": AT, "updated_at": AT, }), )); ops.push(op( "cotton_events", &bella, json!({ "collection_id": calendar, "title": "Call with Bella", "starts_at": "2026-09-16T09:00:00.000Z", "ends_at": "2026-09-16T09:30:00.000Z", "all_day": false, "rrule": "FREQ=WEEKLY", "exdates": ["2026-09-23T09:00:00.000Z"], "gcal_id": BELLA_GCAL, "sync_state": "synced", "created_at": AT, "updated_at": AT, }), )); ops.push(op( "cotton_events", &dinner, json!({ "collection_id": calendar, "title": "dinner with amma", "starts_at": "2026-09-05T14:00:00.000Z", "ends_at": "2026-09-05T16:00:00.000Z", "all_day": false, "created_at": AT, "updated_at": AT, }), )); if !google { for one in ops.iter_mut().filter(|one| one["table"] == "cotton_events") { if let Some(row) = one["patch"].as_object_mut() { row.remove("gcal_id"); row.remove("sync_state"); } } } seed(&h, ops); Calendar { h, secret, calendar, vicky, vicky_moved_to_the_8th, vicky_moved_to_the_12th, bella, dinner, } } /// One column of one event row, straight off the file. fn ev(cal: &Calendar, name: &str, id: &str) -> Option { column(&cal.h, "cotton_events", name, id) } fn exdates_of(cal: &Calendar, id: &str) -> Vec { let raw = ev(cal, "exdates", id).unwrap_or_else(|| "[]".to_string()); serde_json::from_str(&raw).expect("exdates is a JSON array") } fn occurrences_in(cal: &Calendar, from: &str, to: &str) -> Vec { let result = call_tool( &cal.h, &cal.secret, "list_events", json!({ "from": from, "to": to, "expand": true }), ); assert_eq!(result["expanded"], true); result["events"].as_array().expect("events").clone() } fn occurrences(cal: &Calendar) -> Vec { occurrences_in(cal, SEPTEMBER_FROM, SEPTEMBER_TO) } fn starts(drawn: &[Value]) -> Vec { drawn .iter() .map(|o| o["startsAt"].as_str().unwrap_or_default().to_string()) .collect() } fn of_series<'a>(drawn: &'a [Value], series: &str) -> Vec<&'a Value> { drawn.iter().filter(|o| o["seriesId"] == series).collect() } // ── list_events { expand: true } ──────────────────────────────────────────── #[test] fn draws_a_moved_occurrence_once_on_the_day_it_moved_to_and_never_on_the_day_it_left() { let cal = calendar_of(true); let drawn = occurrences(&cal); assert_eq!( starts(&drawn), vec![ "2026-09-05T14:00:00.000Z", // dinner with amma — no series at all "2026-09-08T06:30:00.000Z", // Vicky, the 4th moved forward "2026-09-12T06:30:00.000Z", // Vicky, the 11th moved forward "2026-09-16T09:00:00.000Z", // Call with Bella "2026-09-18T06:30:00.000Z", "2026-09-25T06:30:00.000Z", "2026-09-30T09:00:00.000Z", ] ); // The two days the occurrences LEFT draw nothing. assert!(!starts(&drawn).contains(&"2026-09-04T06:30:00.000Z".to_string())); assert!(!starts(&drawn).contains(&"2026-09-11T06:30:00.000Z".to_string())); } #[test] fn addresses_a_moved_occurrence_by_the_instant_it_replaces_not_the_time_it_moved_to() { let cal = calendar_of(true); let drawn = occurrences(&cal); let moved = drawn .iter() .find(|o| o["id"] == cal.vicky_moved_to_the_8th) .expect("the moved occurrence"); assert_eq!(moved["startsAt"], "2026-09-08T06:30:00.000Z"); assert_eq!(moved["occurrenceAt"], "2026-09-04T06:30:00.000Z"); assert_eq!(moved["seriesId"], cal.vicky); assert_eq!(moved["isException"], true); assert_eq!(moved["repeats"], "FREQ=WEEKLY"); } #[test] fn never_draws_a_cancelled_occurrence_however_many_times_it_is_asked() { let cal = calendar_of(true); let drawn = occurrences(&cal); let bella: Vec = of_series(&drawn, &cal.bella) .iter() .map(|o| o["startsAt"].as_str().unwrap_or_default().to_string()) .collect(); assert_eq!( bella, vec!["2026-09-16T09:00:00.000Z", "2026-09-30T09:00:00.000Z"] ); } #[test] fn shows_nothing_from_an_event_that_has_been_deleted() { let cal = calendar_of(true); call_tool( &cal.h, &cal.secret, "delete_event", json!({ "id": cal.dinner }), ); call_tool( &cal.h, &cal.secret, "delete_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-18T06:30:00.000Z", "scope": "all" }), ); let drawn = occurrences(&cal); assert_eq!( starts(&drawn), vec!["2026-09-16T09:00:00.000Z", "2026-09-30T09:00:00.000Z"] ); // The master is only MARKED deleted — the sync has to remove it at Google // before the row can go — and its moved occurrences go with it. assert!(ev(&cal, "trashed_at", &cal.vicky).is_some()); } // ── list_events (the series-row form) ─────────────────────────────────────── #[test] fn lists_each_series_once_with_what_it_skips_and_how_many_occurrences_moved() { let cal = calendar_of(true); let result = call_tool( &cal.h, &cal.secret, "list_events", json!({ "from": SEPTEMBER_FROM, "to": SEPTEMBER_TO }), ); assert_eq!(result["expanded"], false); let listed = result["events"].as_array().expect("events").clone(); // The two moved occurrences are NOT rows of their own here. let ids: Vec = listed.iter().map(id_of).collect(); assert_eq!( ids, vec![cal.vicky.clone(), cal.dinner.clone(), cal.bella.clone()] ); assert_eq!(listed[0]["repeats"], "FREQ=WEEKLY"); assert_eq!(listed[0]["exceptions"], 2); assert_eq!(listed[0]["synced"], true); assert!(listed[0].get("skips").is_none()); assert_eq!(listed[2]["skips"], json!(["2026-09-23T09:00:00.000Z"])); assert!(listed[2].get("exceptions").is_none()); // Said the other way round, because it is the whole point of the form: an // exception is COUNTED on its series and never listed beside it. assert!(!ids.contains(&cal.vicky_moved_to_the_12th)); } #[test] fn leaves_out_an_event_that_has_been_deleted() { let cal = calendar_of(true); call_tool( &cal.h, &cal.secret, "delete_event", json!({ "id": cal.bella, "occurrenceAt": "2026-09-16T09:00:00.000Z", "scope": "all" }), ); let result = call_tool( &cal.h, &cal.secret, "list_events", json!({ "from": SEPTEMBER_FROM, "to": SEPTEMBER_TO }), ); let ids: Vec = result["events"] .as_array() .expect("events") .iter() .map(id_of) .collect(); assert_eq!(ids, vec![cal.vicky.clone(), cal.dinner.clone()]); } // ── update_event, scope "this" ────────────────────────────────────────────── #[test] fn gives_one_occurrence_a_row_of_its_own_and_leaves_the_rest_of_the_series_alone() { let cal = local_calendar(true); let result = call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-18T06:30:00.000Z", "scope": "this", "startsAt": "2026-09-18T10:00:00.000Z", "title": "Vicky (later)", }), ); assert_eq!(result["seriesId"], cal.vicky); assert_eq!(result["occurrenceAt"], "2026-09-18T06:30:00.000Z"); assert_eq!(result["created"], true); assert!(result.get("synced").is_none(), "an event made here claims no sync: {result}"); assert_eq!(result["title"], "Vicky (later)"); assert_eq!(result["starts_at"], "2026-09-18T10:00:00.000Z"); let written = id_of(&result); assert_eq!( ev(&cal, "series_id", &written).as_deref(), Some(&cal.vicky[..]) ); assert_eq!( ev(&cal, "original_starts_at", &written).as_deref(), Some("2026-09-18T06:30:00.000Z") ); // An exception does not repeat, and nothing marks it for a push // (nothing writes to Google: Days, 20 Nov 2026). assert_eq!(ev(&cal, "rrule", &written), None); assert_eq!(ev(&cal, "gcal_id", &written), None); assert_eq!(ev(&cal, "sync_state", &written), None); // The occurrence keeps the series' length: one hour, carried across. assert_eq!( ev(&cal, "ends_at", &written).as_deref(), Some("2026-09-18T11:00:00.000Z") ); let drawn = occurrences(&cal); assert!(starts(&drawn).contains(&"2026-09-18T10:00:00.000Z".to_string())); assert!(!starts(&drawn).contains(&"2026-09-18T06:30:00.000Z".to_string())); assert_eq!(of_series(&drawn, &cal.vicky).len(), 4); } #[test] fn changes_the_row_it_already_made_rather_than_claiming_the_same_occurrence_twice() { let cal = local_calendar(true); let first = call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-25T06:30:00.000Z", "scope": "this", "location": "the studio", }), ); assert_eq!(first["created"], true); let second = call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, // The same instant, spelled without the milliseconds an assistant drops. "occurrenceAt": "2026-09-25T06:30:00Z", "scope": "this", "notes": "bring the folder", }), ); assert_eq!(second["created"], false); assert_eq!(second["id"], first["id"]); assert_eq!(second["location"], "the studio"); assert_eq!(second["notes"], "bring the folder"); } #[test] fn edits_the_occurrence_a_moved_copy_already_claims_not_a_second_row_beside_it() { let cal = local_calendar(true); let result = call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-04T06:30:00.000Z", "scope": "this", "title": "Vicky (rescheduled again)", }), ); assert_eq!(result["id"], cal.vicky_moved_to_the_8th); assert_eq!(result["created"], false); // Nothing is marked for a push (nothing writes to Google: Days, 20 Nov 2026). assert_eq!(ev(&cal, "sync_state", &cal.vicky_moved_to_the_8th), None); } // ── update_event, scope "all" ─────────────────────────────────────────────── #[test] fn moves_the_whole_series_when_the_series_own_start_moves() { let cal = local_calendar(true); call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.bella, "occurrenceAt": "2026-09-16T09:00:00.000Z", "scope": "all", "startsAt": "2026-09-16T11:00:00.000Z", "endsAt": "2026-09-16T11:30:00.000Z", }), ); let drawn = occurrences(&cal); let bella: Vec = of_series(&drawn, &cal.bella) .iter() .map(|o| o["startsAt"].as_str().unwrap_or_default().to_string()) .collect(); assert_eq!( bella, vec!["2026-09-16T11:00:00.000Z", "2026-09-30T11:00:00.000Z"] ); assert_eq!(ev(&cal, "sync_state", &cal.bella), None, "nothing is marked for a push"); // A cancelled occurrence stays cancelled: the skipped instant moved with // the series rather than being left pointing at a slot the rule no longer // produces, which would have brought the 23rd back. assert_eq!( exdates_of(&cal, &cal.bella), vec!["2026-09-23T11:00:00.000Z"] ); } #[test] fn carries_the_claims_of_its_moved_occurrences_with_it_so_none_is_drawn_twice() { let cal = local_calendar(true); call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "startsAt": "2026-09-04T08:30:00.000Z", "endsAt": "2026-09-04T09:30:00.000Z", }), ); // Each exception still claims the instant it replaces — two hours later. assert_eq!( ev(&cal, "original_starts_at", &cal.vicky_moved_to_the_8th).as_deref(), Some("2026-09-04T08:30:00.000Z") ); // …and keeps the time the person moved it TO, which is untouched. assert_eq!( ev(&cal, "starts_at", &cal.vicky_moved_to_the_8th).as_deref(), Some("2026-09-08T06:30:00.000Z") ); let drawn = occurrences(&cal); let vicky: Vec = of_series(&drawn, &cal.vicky) .iter() .map(|o| o["startsAt"].as_str().unwrap_or_default().to_string()) .collect(); assert_eq!( vicky, vec![ "2026-09-08T06:30:00.000Z", "2026-09-12T06:30:00.000Z", "2026-09-18T08:30:00.000Z", "2026-09-25T08:30:00.000Z", ] ); } #[test] fn stops_an_event_repeating_when_rrule_is_cleared() { let cal = local_calendar(true); call_tool( &cal.h, &cal.secret, "update_event", json!({ "id": cal.bella, "rrule": Value::Null }), ); let drawn = occurrences(&cal); let bella: Vec<&Value> = drawn .iter() .filter(|o| o["id"] == cal.bella || o["seriesId"] == cal.bella) .collect(); let at: Vec<&str> = bella .iter() .map(|o| o["startsAt"].as_str().unwrap_or_default()) .collect(); assert_eq!(at, vec!["2026-09-16T09:00:00.000Z"]); assert_eq!(bella[0]["seriesId"], Value::Null); } // ── update_event refusals ─────────────────────────────────────────────────── #[test] fn will_not_guess_between_one_occurrence_and_the_whole_series() { let cal = calendar_of(true); let no_scope = call_tool_raw( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-18T06:30:00.000Z", "title": "Vicky" }), ); assert!(no_scope.is_error); assert!( no_scope .text .contains("scope is required with occurrenceAt"), "{}", no_scope.text ); let no_instant = call_tool_raw( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "scope": "this", "title": "Vicky" }), ); assert!(no_instant.is_error); assert!( no_instant.text.contains("occurrenceAt"), "{}", no_instant.text ); } #[test] fn says_an_event_that_does_not_repeat_has_no_occurrences_to_name() { let cal = calendar_of(true); let refused = call_tool_raw( &cal.h, &cal.secret, "update_event", json!({ "id": cal.dinner, "occurrenceAt": "2026-09-05T14:00:00.000Z", "scope": "this", "title": "dinner", }), ); assert!(refused.is_error); assert!(refused.text.contains("does not repeat"), "{}", refused.text); } #[test] fn refuses_a_repeat_rule_on_one_occurrence_and_one_it_cannot_expand_anywhere() { let cal = calendar_of(true); let on_one = call_tool_raw( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-18T06:30:00.000Z", "scope": "this", "rrule": "FREQ=DAILY", }), ); assert!(on_one.is_error); assert!( on_one .text .contains("rrule cannot be set on one occurrence"), "{}", on_one.text ); let nonsense = call_tool_raw( &cal.h, &cal.secret, "update_event", json!({ "id": cal.vicky, "rrule": "FREQ=FORTNIGHTLY" }), ); assert!(nonsense.is_error); assert!( nonsense.text.contains("rrule is not a repeat rule"), "{}", nonsense.text ); } // ── delete_event, scope "this" ────────────────────────────────────────────── #[test] fn cancels_one_occurrence_by_adding_it_to_what_the_series_skips() { let cal = local_calendar(true); let result = call_tool( &cal.h, &cal.secret, "delete_event", json!({ "id": cal.bella, "occurrenceAt": "2026-09-30T09:00:00.000Z", "scope": "this" }), ); assert_eq!(result["cancelled"], true); assert_eq!(result["alreadyCancelled"], false); assert!(result.get("synced").is_none(), "an event made here claims no sync: {result}"); assert_eq!( exdates_of(&cal, &cal.bella), vec!["2026-09-23T09:00:00.000Z", "2026-09-30T09:00:00.000Z"] ); assert_eq!(ev(&cal, "sync_state", &cal.bella), None, "nothing is marked for a push"); let drawn = occurrences(&cal); let bella: Vec<&str> = of_series(&drawn, &cal.bella) .iter() .map(|o| o["startsAt"].as_str().unwrap_or_default()) .collect(); assert_eq!(bella, vec!["2026-09-16T09:00:00.000Z"]); } #[test] fn takes_the_moved_copy_with_it_so_a_cancelled_occurrence_leaves_nothing_standing() { let cal = calendar_of(true); call_tool( &cal.h, &cal.secret, "delete_event", json!({ "id": cal.vicky, "occurrenceAt": "2026-09-04T06:30:00.000Z", "scope": "this" }), ); // The moved row is Google's too, so it is MARKED deleted rather than // dropped: the sync has an instance to remove up there. assert!(ev(&cal, "trashed_at", &cal.vicky_moved_to_the_8th).is_some()); let drawn = starts(&occurrences(&cal)); assert!(!drawn.contains(&"2026-09-08T06:30:00.000Z".to_string())); assert!(!drawn.contains(&"2026-09-04T06:30:00.000Z".to_string())); } #[test] fn says_so_rather_than_growing_the_list_when_the_occurrence_is_already_cancelled() { let cal = calendar_of(true); let again = call_tool( &cal.h, &cal.secret, "delete_event", json!({ "id": cal.bella, "occurrenceAt": "2026-09-23T09:00:00.000Z", "scope": "this" }), ); assert_eq!(again["alreadyCancelled"], true); assert_eq!( exdates_of(&cal, &cal.bella), vec!["2026-09-23T09:00:00.000Z"] ); } // ── create_event ──────────────────────────────────────────────────────────── #[test] fn creates_a_repeating_event_that_expands_from_the_day_it_starts() { let cal = calendar_of(true); let made = call_tool( &cal.h, &cal.secret, "create_event", json!({ "title": "swim", "startsAt": "2026-09-07T06:00:00.000Z", "endsAt": "2026-09-07T07:00:00.000Z", "notes": "goggles", "rrule": "RRULE:FREQ=WEEKLY", }), ); // The `RRULE:` prefix is not stored — one spelling in the column. assert_eq!(made["repeats"], "FREQ=WEEKLY"); let drawn = occurrences(&cal); let swims: Vec<&str> = drawn .iter() .filter(|o| o["id"] == made["id"]) .map(|o| o["startsAt"].as_str().unwrap_or_default()) .collect(); assert_eq!( swims, vec![ "2026-09-07T06:00:00.000Z", "2026-09-14T06:00:00.000Z", "2026-09-21T06:00:00.000Z", "2026-09-28T06:00:00.000Z", ] ); } #[test] fn widens_an_all_day_event_to_the_days_it_covers_in_the_databases_own_zone() { let cal = calendar_of(true); let made = call_tool( &cal.h, &cal.secret, "create_event", json!({ "title": "Chennai", "startsAt": "2026-09-10T13:00:00.000Z", "endsAt": "2026-09-11T13:00:00.000Z", "allDay": true, }), ); // Europe/London is UTC+1 in September, so the 10th starts at 23:00Z on the // 9th and the 11th ends a millisecond before 23:00Z on the 11th. assert_eq!(made["starts_at"], "2026-09-09T23:00:00.000Z"); assert_eq!(made["ends_at"], "2026-09-11T22:59:59.999Z"); } /// RULE: A day said with no time ("tea tomorrow") is a whole-day event on that day in the writer's zone, never UTC midnight (5:30 am in Kolkata, the day before anywhere west of Greenwich). #[test] fn a_bare_day_is_a_whole_day_event_on_that_day_in_the_writers_zone() { let cal = calendar_of(true); for (zone, starts) in [("Asia/Kolkata", "2026-10-05T18:30:00.000Z"), ("America/New_York", "2026-10-06T04:00:00.000Z")] { let made = call_tool( &cal.h, &cal.secret, "create_event", json!({ "title": "tea", "startsAt": "2026-10-06", "timezone": zone }), ); assert_eq!(made["all_day"], true, "{zone}"); assert_eq!(made["starts_at"], starts, "{zone}"); } let refused = call_tool_raw( &cal.h, &cal.secret, "create_event", json!({ "title": "tea", "startsAt": "2026-10-06", "allDay": false }), ); assert!(refused.is_error && refused.text.contains("give it a time"), "{}", refused.text); } #[test] fn refuses_an_all_day_event_when_no_timezone_is_named_anywhere() { let cal = calendar_of(false); let refused = call_tool_raw( &cal.h, &cal.secret, "create_event", json!({ "title": "Chennai", "startsAt": "2026-09-10T13:00:00.000Z", "allDay": true }), ); assert!(refused.is_error); assert!( refused .text .contains("which timezone this database lives in"), "{}", refused.text ); // The call is answered by the ARGUMENT too, without touching the file. let named = call_tool( &cal.h, &cal.secret, "create_event", json!({ "title": "Chennai", "startsAt": "2026-09-10T13:00:00.000Z", "allDay": true, "timezone": "Asia/Kolkata", }), ); assert_eq!(named["starts_at"], "2026-09-09T18:30:00.000Z"); // An ordinary timed event needs no zone at all, and is not refused. let timed = call_tool( &cal.h, &cal.secret, "create_event", json!({ "title": "call", "startsAt": "2026-09-10T13:00:00.000Z" }), ); assert_eq!(timed["starts_at"], "2026-09-10T13:00:00.000Z"); } // ── update_events ─────────────────────────────────────────────────────────── #[test] fn shifts_every_event_by_the_same_number_of_minutes() { let cal = local_calendar(true); let result = call_tool( &cal.h, &cal.secret, "update_events", json!({ "ids": [cal.dinner, cal.bella], "shift": { "minutes": -30 } }), ); assert_eq!(result["updated"], 2); assert_eq!(result["failed"], 0); assert_eq!( ev(&cal, "starts_at", &cal.dinner).as_deref(), Some("2026-09-05T13:30:00.000Z") ); assert_eq!( ev(&cal, "ends_at", &cal.dinner).as_deref(), Some("2026-09-05T15:30:00.000Z") ); // A repeating event among the ids takes the whole series. assert_eq!( ev(&cal, "starts_at", &cal.bella).as_deref(), Some("2026-09-16T08:30:00.000Z") ); } #[test] fn moves_events_to_another_day_each_keeping_the_time_it_happens_at() { let cal = local_calendar(true); call_tool( &cal.h, &cal.secret, "update_events", json!({ "ids": [cal.dinner, cal.vicky_moved_to_the_8th], "moveTo": { "date": "2026-09-21" }, }), ); // 14:00Z is 15:00 in London, and it is still 15:00 in London on the 21st. assert_eq!( ev(&cal, "starts_at", &cal.dinner).as_deref(), Some("2026-09-21T14:00:00.000Z") ); assert_eq!( ev(&cal, "ends_at", &cal.dinner).as_deref(), Some("2026-09-21T16:00:00.000Z") ); assert_eq!( ev(&cal, "starts_at", &cal.vicky_moved_to_the_8th).as_deref(), Some("2026-09-21T06:30:00.000Z") ); } #[test] fn applies_one_patch_to_every_id() { let cal = local_calendar(true); call_tool( &cal.h, &cal.secret, "update_events", json!({ "ids": [cal.dinner, cal.bella], "patch": { "location": "home" } }), ); assert_eq!(ev(&cal, "location", &cal.dinner).as_deref(), Some("home")); assert_eq!(ev(&cal, "location", &cal.bella).as_deref(), Some("home")); } #[test] fn answers_for_each_id_on_its_own_one_that_fails_never_stops_the_rest() { let cal = calendar_of(true); let ghost = fixture_id("event-ghost"); let result = call_tool( &cal.h, &cal.secret, "update_events", json!({ "ids": [cal.dinner, ghost], "patch": { "title": "supper" } }), ); assert_eq!(result["updated"], 1); assert_eq!(result["failed"], 1); let results = result["results"].as_array().expect("results").clone(); let ok = results .iter() .find(|r| r["id"] == cal.dinner) .expect("the dinner's answer"); assert_eq!(ok["ok"], true); let failed = results .iter() .find(|r| r["id"] == ghost) .expect("the ghost's answer"); assert!( failed["error"] .as_str() .is_some_and(|error| error.contains("no event with id")), "{failed}" ); assert_eq!(ev(&cal, "title", &cal.dinner).as_deref(), Some("supper")); } #[test] fn refuses_two_ways_of_moving_an_event_in_one_call() { let cal = calendar_of(true); let refused = call_tool_raw( &cal.h, &cal.secret, "update_events", json!({ "ids": [cal.dinner], "shift": { "minutes": 30 }, "moveTo": { "date": "2026-09-21" }, }), ); assert!(refused.is_error); assert!( refused .text .contains("exactly one of patch, shift or moveTo"), "{}", refused.text ); } // ── delete_events ─────────────────────────────────────────────────────────── #[test] fn bins_a_cotton_only_event_and_marks_a_synced_one_answering_for_each_id() { let cal = calendar_of(true); let ghost = fixture_id("event-nowhere"); let result = call_tool( &cal.h, &cal.secret, "delete_events", json!({ "ids": [cal.dinner, cal.bella, ghost] }), ); assert_eq!(result["deleted"], 2); assert_eq!(result["failed"], 1); // Both wait in the bin, the Cotton-only one as much as the synced one. assert!(ev(&cal, "trashed_at", &cal.dinner).is_some()); assert!(ev(&cal, "trashed_at", &cal.bella).is_some()); let results = result["results"].as_array().expect("results").clone(); let missing = results .iter() .find(|r| r["id"] == ghost) .expect("the ghost's answer"); assert_eq!(missing["ok"], false); } /// RULE (27 Oct 2026): an event is the database's, never its calendar's — the /// object keeps no calendars and files none — so a new event names none, even /// in a file that holds one, and no calendar is made for it. #[test] fn a_new_event_names_no_calendar_and_none_is_made() { let cal = calendar_of(true); let made = call_tool( &cal.h, &cal.secret, "create_event", json!({ "title": "coffee", "startsAt": "2026-09-09T10:00:00.000Z" }), ); assert_eq!(ev(&cal, "collection_id", &id_of(&made)), None); assert!(made.get("calendar").is_none(), "{made}"); } // ── people and places ─────────────────────────────────────────────────────── // // From `packages/server/__tests__/mcpPeoplePlaces.test.ts`. People and places // stop being read-only (the 2026-08-29 primitives registry): an assistant told // about a new person or place can finally file them, and correct them later — // asserted against the FILE, history rows included. struct People { h: Harness, secret: String, ravi: String, archived: String, } fn people_harness() -> People { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); let ravi = fixture_id("person-ravi"); let archived = fixture_id("person-archived"); seed( &h, vec![ op( "cotton_people", &ravi, json!({ "full_name": "Ravi Uncle", "contact_source": "manual", "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), ), // A phone is a handle row since v90. op( "cotton_person_handles", &fixture_id("handle-person-ravi-0"), json!({ "workspace_id": h.workspace_id, "person_id": ravi, "kind": "phone", "value": "919812345678", "normalised": "919812345678", "source": "manual", "position": 0, "created_at": AT, "updated_at": AT, }), ), op( "cotton_people", &archived, json!({ "full_name": "Old Vendor", "contact_source": "manual", "archived_at": AT, "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), ), ], ); People { h, secret, ravi, archived, } } fn count(h: &Harness, sql: &str, params: &[SqlValue]) -> i64 { h.with(|db| db.get(sql, params)) .expect("the read runs") .and_then(|row| row.int("n")) .unwrap_or(0) } // ── create_person ─────────────────────────────────────────────────────────── #[test] fn files_a_person_with_everything_the_user_said_and_the_row_lands_in_the_file() { let p = people_harness(); let result = call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Meera Sharma", "phones": ["919900112233"], "emails": ["meera@example.com"], "org": "Sharma & Co", "roleTitle": "Partner", "city": "Pune", "birthday": { "month": 3, "day": 14 }, "timezone": "Asia/Kolkata", }), ); assert_eq!(result["full_name"], "Meera Sharma"); let id = id_of(&result); assert_eq!( column(&p.h, "cotton_people", "full_name", &id).as_deref(), Some("Meera Sharma") ); assert_eq!( column(&p.h, "cotton_people", "org", &id).as_deref(), Some("Sharma & Co") ); assert_eq!(number(&p.h, "cotton_people", "birth_month", &id), Some(3)); assert_eq!(number(&p.h, "cotton_people", "birth_year", &id), None); assert_eq!( column(&p.h, "cotton_people", "contact_source", &id).as_deref(), Some("manual") ); } #[test] fn refuses_a_duplicate_name_names_the_existing_row_and_yields_to_allow_duplicate_name() { let p = people_harness(); let refused = call_tool_raw( &p.h, &p.secret, "create_person", json!({ "fullName": "Ravi Uncle" }), ); assert!(refused.is_error); assert!(refused.text.contains(&p.ravi), "{}", refused.text); assert!(refused.text.contains("update_person"), "{}", refused.text); let second = call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Ravi Uncle", "allowDuplicateName": true, "city": "Chennai" }), ); assert_ne!(second["id"], Value::from(p.ravi.clone())); } #[test] fn refuses_how_we_met_and_names_the_verb_that_writes_the_prose_instead() { let p = people_harness(); let refused = call_tool_raw( &p.h, &p.secret, "create_person", json!({ "fullName": "Ravi Iyer", "howWeMet": "at the timber expo" }), ); assert!(refused.is_error); assert!(refused.text.contains("update_summary"), "{}", refused.text); // And nothing was filed on the way to the refusal. assert_eq!( count( &p.h, "SELECT COUNT(*) AS n FROM cotton_people WHERE full_name = ?", &[SqlValue::Text("Ravi Iyer".to_string())], ), 0 ); } #[test] fn still_creates_a_person_when_the_retired_field_is_simply_absent() { // The other half of the refusal: it must not have broken the tool for // every honest call. let p = people_harness(); let created = call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Ravi Iyer", "city": "Coimbatore" }), ); assert_eq!(created["full_name"], "Ravi Iyer"); assert_eq!(created["city"], "Coimbatore"); } // ── list_people ───────────────────────────────────────────────────────────── #[test] fn enumerates_the_contact_book_with_a_total_excluding_archived_people_by_default() { let p = people_harness(); let answer = call_tool(&p.h, &p.secret, "list_people", json!({})); assert_eq!(answer["total"], 1); assert_eq!(answer["more"], false); let listed = answer["people"].as_array().expect("people").clone(); assert_eq!(listed.len(), 1); assert_eq!(listed[0]["id"], p.ravi); assert_eq!(listed[0]["name"], "Ravi Uncle"); assert_eq!(listed[0]["phones"], json!(["919812345678"])); assert_eq!(listed[0]["emails"], json!([])); assert!(listed[0].get("archived").is_none()); } #[test] fn include_archived_brings_archived_people_back_marked_and_counted_in_the_total() { let p = people_harness(); let answer = call_tool( &p.h, &p.secret, "list_people", json!({ "includeArchived": true }), ); assert_eq!(answer["total"], 2); let listed = answer["people"].as_array().expect("people").clone(); let archived = listed .iter() .find(|person| person["id"] == p.archived) .expect("the archived person"); assert_eq!(archived["name"], "Old Vendor"); assert_eq!(archived["archived"], true); let active = listed .iter() .find(|person| person["id"] == p.ravi) .expect("the live person"); assert!(active.get("archived").is_none()); } #[test] fn q_matches_a_name_substring_case_insensitively_the_sweep_search_records_cannot_do() { let p = people_harness(); call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Dr. Meera Sharma" }), ); // "eera" is not a word boundary anywhere — whole-word FTS would answer // nothing for it; this tool exists so a cleanup sweep still finds her. let answer = call_tool(&p.h, &p.secret, "list_people", json!({ "q": "EERA" })); assert_eq!(answer["total"], 1); assert_eq!(answer["people"][0]["name"], "Dr. Meera Sharma"); let none = call_tool(&p.h, &p.secret, "list_people", json!({ "q": "zzz" })); assert_eq!(none["total"], 0); assert_eq!(none["people"], json!([])); } #[test] fn pages_with_offset_over_a_stable_name_sort_and_total_spans_every_page() { let p = people_harness(); for name in ["Anita Rao", "Bala Iyer", "Chitra Devi"] { call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": name }), ); } let first = call_tool(&p.h, &p.secret, "list_people", json!({ "limit": 2 })); assert_eq!(first["total"], 4); assert_eq!(first["more"], true); assert_eq!(first["offset"], 0); let names: Vec<&str> = first["people"] .as_array() .expect("people") .iter() .map(|person| person["name"].as_str().unwrap_or_default()) .collect(); assert_eq!(names, vec!["Anita Rao", "Bala Iyer"]); let second = call_tool( &p.h, &p.secret, "list_people", json!({ "limit": 2, "offset": 2 }), ); assert_eq!(second["total"], 4); assert_eq!(second["more"], false); let names: Vec<&str> = second["people"] .as_array() .expect("people") .iter() .map(|person| person["name"].as_str().unwrap_or_default()) .collect(); assert_eq!(names, vec!["Chitra Devi", "Ravi Uncle"]); } #[test] fn an_empty_contact_book_answers_honestly_zero_no_rows_no_more() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read"], "Claude"); let answer = call_tool(&h, &secret, "list_people", json!({})); assert_eq!(answer["total"], 0); assert_eq!(answer["people"], json!([])); assert_eq!(answer["more"], false); } #[test] fn refuses_a_negative_offset_with_a_sentence_not_a_crash() { let p = people_harness(); let refused = call_tool_raw(&p.h, &p.secret, "list_people", json!({ "offset": -1 })); assert!(refused.is_error); assert!(refused.text.contains("offset"), "{}", refused.text); } // ── update_person ─────────────────────────────────────────────────────────── #[test] fn corrects_fields_replaces_phones_whole_and_the_edit_earns_a_history_row() { let p = people_harness(); let result = call_tool( &p.h, &p.secret, "update_person", json!({ "id": p.ravi, "org": "Retired", "phones": ["919812345678", "914412345678"], "birthday": { "month": 11, "day": 2, "year": 1958 }, }), ); assert_eq!(result["org"], "Retired"); // A phone is a handle row since v90; the list's order is `position`. let phones: Vec = p .h .with(|db| { db.all( "SELECT value FROM cotton_person_handles \ WHERE person_id = ? AND kind = 'phone' ORDER BY position", &[SqlValue::Text(p.ravi.clone())], ) }) .expect("the read runs") .iter() .map(|row| row.text("value").unwrap_or_default().to_string()) .collect(); assert_eq!(phones, vec!["919812345678", "914412345678"]); assert_eq!( number(&p.h, "cotton_people", "birth_year", &p.ravi), Some(1958) ); // The registry says person edits are versioned — hold it end to end. assert!( count( &p.h, "SELECT count(*) AS n FROM cotton_changes WHERE kind = 'person' AND record_id = ?", &[SqlValue::Text(p.ravi.clone())], ) >= 1 ); } /// RULE: addPhones/addEmails append to what the person holds when the write runs and never take a handle away — the contacts tidy writes its gains from a plan read earlier, and a replacement list would drop a number added since. #[test] fn add_phones_append_to_what_the_person_holds_and_remove_nothing() { let p = people_harness(); call_tool(&p.h, &p.secret, "update_person", json!({ "id": p.ravi, "phones": ["5550000101"] })); // Added on another device after the tidy read its plan. call_tool(&p.h, &p.secret, "update_person", json!({ "id": p.ravi, "phones": ["5550000101", "5550000102"] })); call_tool( &p.h, &p.secret, "update_person", json!({ "id": p.ravi, "addPhones": ["5550000103", "555 000 0101"], "addEmails": ["ravi.card@example.invalid"] }), ); let values = |kind: &str| -> Vec { p.h.with(|db| { db.all( "SELECT value FROM cotton_person_handles WHERE person_id = ? AND kind = ? ORDER BY position", &[SqlValue::Text(p.ravi.clone()), SqlValue::Text(kind.to_string())], ) }) .expect("the read runs") .iter() .map(|row| row.text("value").unwrap_or_default().to_string()) .collect() }; assert_eq!(values("phone"), ["5550000101", "5550000102", "5550000103"]); assert!(values("email").contains(&"ravi.card@example.invalid".to_string())); let both = call_tool_raw(&p.h, &p.secret, "update_person", json!({ "id": p.ravi, "phones": [], "addPhones": ["5550000104"] })); assert!(both.is_error, "a whole list and an addition together is refused"); } #[test] fn refuses_a_rename_onto_another_persons_name_and_yields_to_allow_duplicate_name() { let p = people_harness(); // Renaming someone to the name they already carry is not a collision. let self_rename = call_tool( &p.h, &p.secret, "update_person", json!({ "id": p.ravi, "fullName": "Ravi Uncle" }), ); assert_eq!(self_rename["full_name"], "Ravi Uncle"); let second = call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Meera Sharma" }), ); let refused = call_tool_raw( &p.h, &p.secret, "update_person", json!({ "id": id_of(&second), "fullName": "Ravi Uncle" }), ); assert!(refused.is_error); assert!(refused.text.contains(&p.ravi), "{}", refused.text); let allowed = call_tool( &p.h, &p.secret, "update_person", json!({ "id": id_of(&second), "fullName": "Ravi Uncle", "allowDuplicateName": true, }), ); assert_eq!(allowed["full_name"], "Ravi Uncle"); } #[test] fn a_photograph_can_only_be_taken_off_here_never_put_on() { // The asymmetry is the design. Setting a face means BYTES, and bytes reach // the file through `capture.avatar` on the owner's own device — so a tool // that could write this column would let an assistant point a person at any // object key in the database. Removing one costs nothing and is a verb the // owner may well ask for out loud. let p = people_harness(); let pointed = call_tool_raw( &p.h, &p.secret, "update_person", json!({ "id": p.ravi, "avatarKey": "ws/people/someone/abc.jpg" }), ); assert!(pointed.is_error); assert!(pointed.text.contains("capture.avatar"), "{}", pointed.text); // Seeded straight into the row, because the only writer that can put one // there is a method this crate does not carry. run_sql( &p.h, "UPDATE cotton_people SET avatar_key = ? WHERE id = ?", &[ SqlValue::Text(format!("{}/people/{}/abc.jpg", p.h.workspace_id, p.ravi)), SqlValue::Text(p.ravi.clone()), ], ); call_tool( &p.h, &p.secret, "update_person", json!({ "id": p.ravi, "avatarKey": null }), ); // Removing the object key removes the photograph. assert_eq!(column(&p.h, "cotton_people", "avatar_key", &p.ravi), None); } #[test] fn update_person_refuses_how_we_met_the_summary_is_update_summarys() { // Schema v15 folded "how we met" into the person's summary, which has // provenance and one writer. Removed means removed: there is no // accept-and-ignore, because a caller whose field was silently dropped // believes it landed. let p = people_harness(); let refused = call_tool_raw( &p.h, &p.secret, "update_person", json!({ "id": p.ravi, "howWeMet": "at the timber expo" }), ); assert!(refused.is_error); assert!(refused.text.contains("update_summary"), "{}", refused.text); } #[test] fn refuses_an_unknown_id_and_an_archived_person() { let p = people_harness(); let ghost = call_tool_raw( &p.h, &p.secret, "update_person", json!({ "id": fixture_id("person-nowhere"), "city": "Nowhere" }), ); assert!(ghost.is_error); let archived = call_tool_raw( &p.h, &p.secret, "update_person", json!({ "id": p.archived, "city": "Nowhere" }), ); assert!(archived.is_error); assert!(archived.text.contains("archived"), "{}", archived.text); } // ── merge_people ──────────────────────────────────────────────────────────── /// As `op`, but stamped AFTER "now" — for patching a row the server just /// wrote, whose HLC would otherwise win the LWW race against a past-stamped op. fn late_op(table: &str, row_id: &str, patch: Value) -> Value { static NEXT: AtomicU64 = AtomicU64::new(0); let n = NEXT.fetch_add(1, Ordering::Relaxed); json!({ "opId": format!("01K{:023}", n), "deviceId": "device:seed", "kind": "upsert", "table": table, "rowId": row_id, "patch": patch, // 100 seconds after the harness clock's fixed instant. "hlc": format!("178886{:07}:0000:device:seed", 1700000 + n), "schemaVersion": SCHEMA_VERSION, }) } struct Merge { h: Harness, secret: String, survivor: String, duplicate: String, note: String, project: String, msg_contact: String, account: String, todo: String, } /// Two people plus every kind of thing that can point at the duplicate. fn merge_fixture() -> Merge { let p = people_harness(); let survivor = id_of(&call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Meera Sharma", "phones": ["919900112233"], "emails": ["meera@example.com"], "city": "Pune", }), )); let duplicate = id_of(&call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Dr. Meera", // Since v90 a handle names ONE person, so the duplicate's card // carries only handles the survivor does not. "phones": ["918888777666"], "emails": ["dr.meera@clinic.example"], "instagram": ["@Dr.Meera.Clinic"], "org": "The Clinic", "roleTitle": "Doctor", }), )); let note = fixture_id("person-note"); let project = fixture_id("project-clinic"); let msg_contact = fixture_id("msg-contact"); let account = fixture_id("money-account"); let todo = fixture_id("merge-todo"); let workspace = p.h.workspace_id.clone(); seed( &p.h, vec![ op( "cotton_person_notes", ¬e, json!({ "person_id": duplicate, "body": "Met at the clinic", "noted_at": AT, "created_at": AT, }), ), op( "cotton_msg_contacts", &msg_contact, json!({ "phone_e164": "918888777666", "person_id": duplicate, "workspace_id": workspace, "created_at": AT, "updated_at": AT, }), ), op( "cotton_money_accounts", &account, json!({ "kind": "bank", "subtype": "receivable", "name": "Dr. Meera owes", "currency": "INR", "counterparty_person_id": duplicate, "workspace_id": workspace, "created_at": AT, "updated_at": AT, }), ), op( "cotton_memory_projects", &project, json!({ "slug": "clinic", "name": "Clinic", "workspace_id": workspace, "created_at": AT, "updated_at": AT, }), ), op( "cotton_project_links", &project_link_id(&project, "person", &duplicate), json!({ "project_id": project, "record_kind": "person", "record_id": duplicate, "applied_by": "user", "workspace_id": workspace, "created_at": AT, "updated_at": AT, }), ), op( "cotton_todos", &todo, json!({ "title": "Call about the reports", "status": "open", "workspace_id": workspace, "created_at": AT, "updated_at": AT, }), ), op( "cotton_links", &record_link_id("todo", &todo, "person", &duplicate), json!({ "workspace_id": workspace, "from_kind": "todo", "from_id": todo, "to_kind": "person", "to_id": duplicate, "created_at": AT, }), ), // An edge between the two people themselves — must collapse, not repoint. op( "cotton_links", &record_link_id("person", &survivor, "person", &duplicate), json!({ "workspace_id": workspace, "from_kind": "person", "from_id": survivor, "to_kind": "person", "to_id": duplicate, "created_at": AT, }), ), ], ); Merge { h: p.h, secret: p.secret, survivor, duplicate, note, project, msg_contact, account, todo, } } #[test] fn folds_the_duplicate_in_whole_union_snapshot_comment_every_repoint_then_the_archive() { let m = merge_fixture(); let answer = call_tool( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); // The union: the duplicate's handles move to the survivor (v90), empty // fields fill, held fields stay. assert_eq!( answer["survivor"]["phones"], json!(["919900112233", "918888777666"]) ); assert_eq!( answer["survivor"]["emails"], json!(["meera@example.com", "dr.meera@clinic.example"]) ); assert_eq!(answer["survivor"]["instagram"], json!(["@Dr.Meera.Clinic"])); assert_eq!(answer["survivor"]["org"], "The Clinic"); assert_eq!(answer["survivor"]["city"], "Pune"); assert_eq!(answer["duplicate"]["archived"], true); assert_eq!(answer["deviceCard"], "none"); assert!(column(&m.h, "cotton_people", "archived_at", &m.duplicate).is_some()); // The snapshot comment sits on the SURVIVOR and names the duplicate. let comment = m.h.with(|db| { db.get( "SELECT body FROM cotton_comments WHERE record_kind = 'person' AND record_id = ? \ AND body LIKE 'Merged in%'", &[SqlValue::Text(m.survivor.clone())], ) }) .expect("the read runs") .and_then(|row| row.text("body").map(str::to_string)) .expect("the snapshot comment"); assert!(comment.contains("Dr. Meera"), "{comment}"); assert!(comment.contains(&m.duplicate), "{comment}"); // Every satellite now points at the survivor. assert_eq!( column(&m.h, "cotton_msg_contacts", "person_id", &m.msg_contact).as_deref(), Some(&m.survivor[..]) ); assert_eq!( column( &m.h, "cotton_money_accounts", "counterparty_person_id", &m.account ) .as_deref(), Some(&m.survivor[..]) ); let project_link = m.h.with(|db| { db.get( "SELECT record_id AS value FROM cotton_project_links WHERE project_id = ? \ AND record_kind = 'person'", &[SqlValue::Text(m.project.clone())], ) }) .expect("the read runs") .and_then(|row| row.text("value").map(str::to_string)); assert_eq!(project_link.as_deref(), Some(&m.survivor[..])); let todo_edge = m.h.with(|db| { db.get( "SELECT to_id AS value FROM cotton_links WHERE from_kind = 'todo' AND from_id = ?", &[SqlValue::Text(m.todo.clone())], ) }) .expect("the read runs") .and_then(|row| row.text("value").map(str::to_string)); assert_eq!(todo_edge.as_deref(), Some(&m.survivor[..])); // The person↔person edge between the two collapsed rather than becoming // a self-edge, and nothing points at the duplicate any more. assert_eq!( count( &m.h, "SELECT COUNT(*) AS n FROM cotton_links WHERE (from_kind = 'person' AND from_id = ?) \ OR (to_kind = 'person' AND to_id = ?)", &[ SqlValue::Text(m.duplicate.clone()), SqlValue::Text(m.duplicate.clone()), ], ), 0 ); assert_eq!(answer["repointed"]["cotton_person_notes"], 1); assert_eq!(answer["repointed"]["cotton_msg_contacts"], 1); // RULE: merge_people carries every handle of the duplicate to the survivor. assert_eq!(answer["repointed"]["cotton_person_handles"], 3); assert_eq!(answer["repointed"]["cotton_money_accounts"], 1); assert_eq!(answer["repointed"]["cotton_project_links"], 1); assert_eq!(answer["repointed"]["cotton_links"], 2); } /// Who the owner is, the object says (apps/business/src/owner.ts — it follows /// a merged owner by number): a merge on a device leaves the workspace's link /// as it was, and moves nothing of the workspace row. #[test] fn merge_people_leaves_the_owner_link_to_the_object() { let m = merge_fixture(); let workspace = m.h.workspace_id.clone(); m.h.with(|db| { db.run( "UPDATE cotton_workspaces SET owner_person_id = ? WHERE id = ?", &[ SqlValue::Text(m.duplicate.clone()), SqlValue::Text(workspace.clone()), ], ) }) .expect("the owner link is seeded"); let answer = call_tool( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); let owner = m.h.with(|db| { db.get( "SELECT owner_person_id AS value FROM cotton_workspaces WHERE id = ?", &[SqlValue::Text(workspace.clone())], ) }) .expect("the read runs") .and_then(|row| row.text("value").map(str::to_string)); assert_eq!(owner.as_deref(), Some(&m.duplicate[..])); assert!(answer["repointed"].get("cotton_workspaces").is_none(), "{answer}"); } /// A row a schema move carried over with no receipt of its own — the v90 /// move folded `cotton_people.phones`/`emails` into `cotton_person_handles` /// that way on the serving Mac. Written straight in, past the receipts, and /// the merge is then called WITHOUT the harness's reconcile, because that /// reconcile is exactly what the real file never had. fn carried_handle(m: &Merge, person: &str, kind: &str, value: &str) -> String { let id = fixture_id(&format!("carried-{kind}-{value}")); m.h.db .run( "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, \ position, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'contacts', 0, ?, ?)", &[ SqlValue::Text(id.clone()), SqlValue::Text(m.h.workspace_id.clone()), SqlValue::Text(person.to_string()), SqlValue::Text(kind.to_string()), SqlValue::Text(value.to_string()), SqlValue::Text(value.to_string()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ) .expect("the carried handle is written"); id } /// GUARD (data safety, architect 21 Oct 2026): merge_people keeps every /// handle of both people on the survivor. On the owner's Personal (Mac 160) /// a merge answered `cotton_person_handles: 2` and both handles were gone /// from every person: the duplicate's handles had been carried by the v90 /// move with no receipt, the repoint minted a bare change, and a row whose /// receipts hold no create is not live — the fold took it out of the table. #[test] fn merge_people_keeps_every_handle_even_one_a_move_carried_without_a_receipt() { let m = merge_fixture(); let phone = carried_handle(&m, &m.duplicate, "phone", "15550001111"); let email = carried_handle(&m, &m.duplicate, "email", "me@usa.example"); let answer = support::mcp::call_tool_in_prepared_file( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ) .json(); for (id, value) in [(&phone, "15550001111"), (&email, "me@usa.example")] { assert_eq!( column(&m.h, "cotton_person_handles", "person_id", id).as_deref(), Some(&m.survivor[..]), "{value} moved to the survivor, not out of the file" ); assert_eq!(column(&m.h, "cotton_person_handles", "value", id).as_deref(), Some(value)); } let phones = answer["survivor"]["phones"].as_array().expect("phones").clone(); let emails = answer["survivor"]["emails"].as_array().expect("emails").clone(); assert!(phones.contains(&json!("15550001111")), "{phones:?}"); assert!(phones.contains(&json!("919900112233")), "{phones:?}"); assert!(emails.contains(&json!("me@usa.example")), "{emails:?}"); assert!(emails.contains(&json!("meera@example.com")), "{emails:?}"); // The survivor's own handle and the duplicate's created one are kept too. assert_eq!( count( &m.h, "SELECT COUNT(*) AS n FROM cotton_person_handles WHERE person_id = ?", &[SqlValue::Text(m.survivor.clone())], ), 2 + 3 + 2 ); } /// A money row whose receipts still say what it held before the 139 move /// (`status = 'posted'`) while the move rewrote the row itself to `actual`. /// The CHECK is lifted only to plant the old receipt, as the old schema took /// it; the rewrite after it is the move's, with no receipt. fn transaction_from_before_139(m: &Merge, rewritten_to: Option<&str>) -> String { let id = fixture_id(&format!("txn-before-139-{rewritten_to:?}")); m.h.db.run("PRAGMA ignore_check_constraints = ON", &[]).expect("the pragma"); seed( &m.h, vec![op( "cotton_money_transactions", &id, json!({ "workspace_id": m.h.workspace_id, "occurred_on": "2026-09-01", "description": "Lunch", "amount_minor": 50000, "currency": "INR", "status": "posted", "counterparty_person_id": m.duplicate, "created_at": AT, "updated_at": AT, }), )], ); if let Some(status) = rewritten_to { m.h.db .run( "UPDATE cotton_money_transactions SET status = ? WHERE id = ?", &[SqlValue::Text(status.to_string()), SqlValue::Text(id.clone())], ) .expect("the move's rewrite"); } m.h.db.run("PRAGMA ignore_check_constraints = OFF", &[]).expect("the pragma"); id } /// A repoint moves the link column and nothing else: a transaction the 139 /// move rewrote (its receipts still say `posted`) keeps the `actual` the /// table holds. On Mac 160 this merge was refused by the fold with /// "CHECK constraint failed: status IN ('actual','expected')". #[test] fn merge_people_repoints_a_moved_transaction_without_rewriting_its_status() { let m = merge_fixture(); let transaction = transaction_from_before_139(&m, Some("actual")); let answer = support::mcp::call_tool_in_prepared_file( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!( column(&m.h, "cotton_money_transactions", "counterparty_person_id", &transaction).as_deref(), Some(&m.survivor[..]) ); assert_eq!(column(&m.h, "cotton_money_transactions", "status", &transaction).as_deref(), Some("actual")); } /// GUARD (data safety, architect 21 Oct 2026): a refused merge leaves no /// write behind. On Mac 160 a merge refused by the fold had already moved the /// duplicate's handles, msg contacts and the workspace's owner, each step /// committed on its own — so the refusal said nothing happened while half of /// it had. Here a row the file's own CHECK refuses (a transaction still /// `posted`, never moved) makes the repoint fail after every earlier step. #[test] fn a_refused_merge_leaves_no_write_behind() { let m = merge_fixture(); let workspace = m.h.workspace_id.clone(); m.h.db .run( "UPDATE cotton_workspaces SET owner_person_id = ? WHERE id = ?", &[SqlValue::Text(m.duplicate.clone()), SqlValue::Text(workspace.clone())], ) .expect("the owner link"); let transaction = transaction_from_before_139(&m, None); let survivor_before = column(&m.h, "cotton_people", "org", &m.survivor); let comments_before = count(&m.h, "SELECT COUNT(*) AS n FROM cotton_comments", &[]); let refused = support::mcp::call_tool_in_prepared_file( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert!(refused.is_error, "{}", refused.text); assert!(refused.text.contains("CHECK"), "{}", refused.text); // Nothing moved: handles, msg contact, owner, money, notes, the archive. assert_eq!( count( &m.h, "SELECT COUNT(*) AS n FROM cotton_person_handles WHERE person_id = ?", &[SqlValue::Text(m.duplicate.clone())], ), 3 ); assert_eq!( column(&m.h, "cotton_msg_contacts", "person_id", &m.msg_contact).as_deref(), Some(&m.duplicate[..]) ); assert_eq!( column(&m.h, "cotton_workspaces", "owner_person_id", &workspace).as_deref(), Some(&m.duplicate[..]) ); assert_eq!( column(&m.h, "cotton_money_accounts", "counterparty_person_id", &m.account).as_deref(), Some(&m.duplicate[..]) ); assert_eq!( column(&m.h, "cotton_money_transactions", "counterparty_person_id", &transaction).as_deref(), Some(&m.duplicate[..]) ); assert_eq!( column(&m.h, "cotton_person_notes", "person_id", &m.note).as_deref(), Some(&m.duplicate[..]) ); assert_eq!(column(&m.h, "cotton_people", "archived_at", &m.duplicate), None); assert_eq!(column(&m.h, "cotton_people", "org", &m.survivor), survivor_before); assert_eq!(count(&m.h, "SELECT COUNT(*) AS n FROM cotton_comments", &[]), comments_before); } /// A link from the duplicate into another database keeps that database when /// it moves to the survivor: the file is part of the edge, so the moved row's /// id is `link_id_for`'s five-part one, and a link to the same id in this file /// stays a separate row. #[test] fn merging_two_people_keeps_each_links_target_file() { let m = merge_fixture(); let workspace = m.h.workspace_id.clone(); let elsewhere = "22222222-2222-4222-8222-222222222222"; let document = fixture_id("document-elsewhere"); let ends = |from_id: &str, to_database: Option<&'static str>| -> String { link_id_for( &LinkRow { from_kind: "person", from_id, to_kind: "document", to_id: &document, to_database, }, m.h.file.id(), ) }; let link = |from_id: &str, to_database: Option<&str>| -> Value { json!({ "workspace_id": workspace, "from_kind": "person", "from_id": from_id, "to_kind": "document", "to_id": document, "to_database": to_database, "created_at": AT, }) }; seed( &m.h, vec![ op( "cotton_links", &ends(&m.duplicate, Some(elsewhere)), link(&m.duplicate, Some(elsewhere)), ), // The survivor already links the same id in THIS file: another edge. op( "cotton_links", &ends(&m.survivor, None), link(&m.survivor, None), ), ], ); call_tool( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); let moved = ends(&m.survivor, Some(elsewhere)); assert_ne!(moved, ends(&m.survivor, None)); assert_eq!( column(&m.h, "cotton_links", "to_database", &moved).as_deref(), Some(elsewhere), "the moved link keeps its target file" ); assert_eq!(column(&m.h, "cotton_links", "from_id", &moved).as_deref(), Some(&m.survivor[..])); assert_eq!( column(&m.h, "cotton_links", "to_id", &ends(&m.survivor, None)).as_deref(), Some(&document[..]), "the survivor's own link to the same id in this file is untouched" ); assert_eq!( count( &m.h, "SELECT COUNT(*) AS n FROM cotton_links WHERE from_kind = 'person' AND from_id = ? \ AND to_kind = 'document'", &[SqlValue::Text(m.survivor.clone())], ), 2 ); assert!(column(&m.h, "cotton_links", "id", &ends(&m.duplicate, Some(elsewhere))).is_none()); } #[test] fn refuses_when_both_people_hold_the_same_money_claim_touching_nothing() { let m = merge_fixture(); seed( &m.h, vec![op( "cotton_money_accounts", &fixture_id("money-account-survivor"), json!({ "kind": "bank", "subtype": "receivable", "name": "Meera owes", "currency": "INR", "counterparty_person_id": m.survivor, "workspace_id": m.h.workspace_id, "created_at": AT, "updated_at": AT, }), )], ); let refused = call_tool_raw( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert!(refused.is_error); assert!(refused.text.contains("receivable"), "{}", refused.text); assert_eq!( column(&m.h, "cotton_people", "archived_at", &m.duplicate), None ); assert_eq!( column(&m.h, "cotton_person_notes", "person_id", &m.note).as_deref(), Some(&m.duplicate[..]) ); } #[test] fn moves_the_iphone_contact_link_to_the_survivor_when_only_the_duplicate_held_one() { let m = merge_fixture(); seed( &m.h, vec![late_op( "cotton_people", &m.duplicate, json!({ "device_contact_id": "AB12:ZZ", "device_contact_snapshot": { "fullName": "Dr. Meera", "phones": ["918888777666"] }, }), )], ); let answer = call_tool( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert_eq!(answer["deviceCard"], "moved"); assert_eq!( column(&m.h, "cotton_people", "device_contact_id", &m.survivor).as_deref(), Some("AB12:ZZ") ); assert_eq!( column(&m.h, "cotton_people", "device_contact_id", &m.duplicate), None ); } #[test] fn reports_the_duplicates_iphone_contact_as_orphaned_when_both_were_linked() { let m = merge_fixture(); seed( &m.h, vec![ late_op( "cotton_people", &m.survivor, json!({ "device_contact_id": "SURV:1", "device_contact_snapshot": { "fullName": "Meera Sharma" }, }), ), late_op( "cotton_people", &m.duplicate, json!({ "device_contact_id": "DUP:2", "device_contact_snapshot": { "fullName": "Dr. Meera" }, }), ), ], ); let answer = call_tool( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert_eq!(answer["deviceCard"], "orphaned"); assert_eq!(answer["orphanedDeviceContactId"], "DUP:2"); assert_eq!( column(&m.h, "cotton_people", "device_contact_id", &m.survivor).as_deref(), Some("SURV:1") ); } #[test] fn refuses_an_archived_survivor_and_the_degenerate_same_id_pair() { let m = merge_fixture(); let same_pair = call_tool_raw( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.survivor }), ); assert!(same_pair.is_error); assert!(same_pair.text.contains("same person"), "{}", same_pair.text); call_tool( &m.h, &m.secret, "archive_person", json!({ "id": m.survivor }), ); let archived_survivor = call_tool_raw( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert!(archived_survivor.is_error); assert!( archived_survivor.text.contains("unarchive_person"), "{}", archived_survivor.text ); } /// GUARD (data safety, T8, 22 Oct 2026): what a merge moves is derived from /// the database's definitions, so a tool a person imports with a person link /// is moved onto the survivor with no code change. Before, merge walked a /// hand list of twelve tables and an imported tool's link (and a story, a /// face's "maybe") kept pointing at the archived duplicate. #[test] fn merge_people_moves_an_imported_tables_person_link() { use base64::{engine::general_purpose::STANDARD, Engine}; use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition}; let m = merge_fixture(); let tool: ToolDefinition = serde_json::from_value(json!({ "id": "clinic", "name": "Clinic", "picture": "tool-clinic", "tables": ["clinic_patient"], "instructions": "Synthetic clinic for a merge guard. All records are invented.", "automations": [], "author": { "device": "synthetic-clinic-fixture", "name": "Invented" }, "signature": null, })) .expect("a synthetic tool"); let table: TableDefinition = serde_json::from_value(json!({ "id": "clinic_patient", "name": "Patient", "plural": "Patients", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "name", "name": "Name", "type": "text", "required": true }, { "key": "patient", "name": "Patient", "type": "link", "link_to": "person" }, ], "title": "name", "date": null, "project": null, "order": null, "slip": { "title": "name", "subtitle": null, "trailing": null }, "tile": { "face": "polaroid-grid" }, "page": [{ "heading": null, "columns": ["name", "patient"] }], "instructions": "Invented patients. Links hold record ids.", })) .expect("a synthetic table"); let package = ToolPackage { board: None, tool, tables: vec![table], pictures: Default::default(), samples: Default::default() }; let bytes = cotton_core::definitions::package::encode_unsigned_package(&package).expect("packs"); call_tool(&m.h, &m.secret, "import_tool", json!({ "bytes": STANDARD.encode(bytes) })); let created = call_tool( &m.h, &m.secret, "create_record", json!({ "table": "clinic_patient", "data": { "name": "Invented visit", "patient": m.duplicate } }), ); let record = created["record"]["id"].as_str().expect("an id").to_string(); let answer = call_tool( &m.h, &m.secret, "merge_people", json!({ "survivorId": m.survivor, "duplicateId": m.duplicate }), ); assert_eq!(answer["repointed"]["cotton_clinic_patient"], 1, "{answer}"); assert_eq!( column(&m.h, "cotton_clinic_patient", "patient", &record).as_deref(), Some(m.survivor.as_str()) ); } // ── archive_person / unarchive_person ─────────────────────────────────────── #[test] fn archives_out_of_the_contact_book_idempotently_and_unarchive_restores() { let p = people_harness(); let archived = call_tool(&p.h, &p.secret, "archive_person", json!({ "id": p.ravi })); assert_eq!(archived["name"], "Ravi Uncle"); assert_eq!(archived["alreadyArchived"], false); let listed = call_tool(&p.h, &p.secret, "list_people", json!({})); assert_eq!(listed["total"], 0); let again = call_tool(&p.h, &p.secret, "archive_person", json!({ "id": p.ravi })); assert_eq!(again["alreadyArchived"], true); let restored = call_tool(&p.h, &p.secret, "unarchive_person", json!({ "id": p.ravi })); assert_eq!(restored["alreadyLive"], false); let relisted = call_tool(&p.h, &p.secret, "list_people", json!({})); assert_eq!(relisted["total"], 1); } #[test] fn archive_person_refuses_an_unknown_person_with_a_sentence() { let p = people_harness(); let missing = call_tool_raw( &p.h, &p.secret, "archive_person", json!({ "id": fixture_id("person-vanished") }), ); assert!(missing.is_error); assert!(missing.text.contains("no person"), "{}", missing.text); } // ── the 2026-08-29 tool-surface fill ──────────────────────────────────────── // // From `packages/server/__tests__/mcpToolGaps.test.ts`: the tools that closed // the gaps where a primitive could be created but never listed, corrected or // removed. Only this group's share is here; money's two live with money's. struct Gaps { h: Harness, secret: String, calendar: String, local_event: String, gcal_event: String, note: String, } fn gaps_harness() -> Gaps { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); let calendar = fixture_id("gaps-calendar"); let local_event = fixture_id("gaps-local-event"); let gcal_event = fixture_id("gaps-gcal-event"); let note = fixture_id("gaps-note"); seed( &h, vec![ op( "cotton_collections", &calendar, json!({ "kind": "calendar", "name": "Personal", "is_default": true, "workspace_id": h.workspace_id, "created_at": AT, }), ), op( "cotton_events", &local_event, json!({ "collection_id": calendar, "title": "dinner with amma", "starts_at": "2026-09-02T14:00:00.000Z", "ends_at": "2026-09-02T16:00:00.000Z", "all_day": false, "created_at": AT, "updated_at": AT, }), ), op( "cotton_events", &gcal_event, json!({ "collection_id": calendar, "title": "quarterly review", "starts_at": "2026-09-03T05:00:00.000Z", "all_day": false, "gcal_id": "gcal-123", "sync_state": "synced", "created_at": AT, "updated_at": AT, }), ), op( "cotton_notes", ¬e, json!({ "title": "old plan", "body": "the plan that got shelved", "kind": "note", "archived_at": AT, "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), ), ], ); Gaps { h, secret, calendar, local_event, gcal_event, note, } } #[test] fn answers_a_window_with_calendar_names_the_synced_flag_and_the_more_marker() { let g = gaps_harness(); let result = call_tool( &g.h, &g.secret, "list_events", json!({ "from": "2026-09-01T00:00:00.000Z", "to": "2026-09-10T00:00:00.000Z" }), ); let events = result["events"].as_array().expect("events").clone(); let ids: Vec = events.iter().map(id_of).collect(); assert_eq!(ids, vec![g.local_event.clone(), g.gcal_event.clone()]); assert_eq!(events[0]["calendar"], "Personal"); assert!(events[0].get("synced").is_none()); assert_eq!(events[1]["synced"], true); } #[test] fn moves_an_event_and_refuses_a_window_that_ends_before_it_starts() { let g = gaps_harness(); let result = call_tool( &g.h, &g.secret, "update_event", json!({ "id": g.local_event, "startsAt": "2026-09-02T15:00:00.000Z", "endsAt": "2026-09-02T17:00:00.000Z", "location": "Saravana Bhavan", }), ); assert_eq!(result["starts_at"], "2026-09-02T15:00:00.000Z"); let backwards = call_tool_raw( &g.h, &g.secret, "update_event", json!({ "id": g.local_event, "endsAt": "2026-09-02T10:00:00.000Z" }), ); assert!(backwards.is_error); assert!(backwards.text.contains("endsAt"), "{}", backwards.text); } /// RULE (Days, 20 Nov 2026): a Google event's time and title are Google's. Nothing writes to Google, so an edit /// here would be undone by the next pull: it is refused in the sentence a phone shows, and nothing is written or marked. #[test] fn refuses_a_google_events_title_and_writes_nothing() { let g = gaps_harness(); let refused = call_tool_raw( &g.h, &g.secret, "update_event", json!({ "id": g.gcal_event, "title": "quarterly review (moved)" }), ); assert!(refused.is_error, "{}", refused.text); assert!(refused.text.contains(cotton_tools::mcp::handlers::records_1::events::GOOGLE_READ_ONLY), "{}", refused.text); assert_eq!( column(&g.h, "cotton_events", "sync_state", &g.gcal_event).as_deref(), Some("synced") ); assert_eq!( column(&g.h, "cotton_events", "title", &g.gcal_event).as_deref(), Some("quarterly review") ); } #[test] fn bins_a_local_event_and_marks_a_google_linked_one_deleted_for_the_sync() { // Until schema v32 the second half of this was a REFUSAL: there was no rail // to delete a Google-linked event, so the tool declined and the owner had to // go to Google. There is one now — the row goes to the bin. Since Days (20 // Nov 2026) nothing writes to Google, so it is not marked for a push. Since // 5 Oct 2026 a local one waits in the bin too. let g = gaps_harness(); let result = call_tool( &g.h, &g.secret, "delete_event", json!({ "id": g.local_event }), ); assert_eq!(result["deleted"], true); // A local event waits in the bin too, and goes nowhere else. assert_eq!(result["trashed"], true); assert!(column(&g.h, "cotton_events", "trashed_at", &g.local_event).is_some()); assert_eq!(column(&g.h, "cotton_events", "sync_state", &g.local_event), None); let synced = call_tool( &g.h, &g.secret, "delete_event", json!({ "id": g.gcal_event }), ); assert_eq!(synced["deleted"], true); assert_eq!(synced["trashed"], true); assert_eq!(synced["synced"], true); assert!(column(&g.h, "cotton_events", "trashed_at", &g.gcal_event).is_some()); // Nothing is marked for a push (nothing writes to Google: Days, 20 Nov 2026). assert_eq!( column(&g.h, "cotton_events", "sync_state", &g.gcal_event).as_deref(), Some("synced") ); // And it is out of every read from the moment it is marked. let listed = call_tool( &g.h, &g.secret, "list_events", json!({ "from": "2026-09-01T00:00:00.000Z", "to": "2026-09-10T00:00:00.000Z" }), ); assert_eq!(listed["events"], json!([])); } #[test] fn brings_an_archived_note_back_and_a_second_call_is_a_no_op_that_says_so() { let g = gaps_harness(); let result = call_tool(&g.h, &g.secret, "unarchive_note", json!({ "id": g.note })); assert_eq!(result["alreadyLive"], false); assert_eq!(column(&g.h, "cotton_notes", "archived_at", &g.note), None); let again = call_tool(&g.h, &g.secret, "unarchive_note", json!({ "id": g.note })); assert_eq!(again["alreadyLive"], true); let missing = call_tool_raw( &g.h, &g.secret, "unarchive_note", json!({ "id": fixture_id("note-nowhere") }), ); assert!(missing.is_error); } #[test] fn upsert_managed_note_refuses_tags_by_name_on_a_call_that_is_otherwise_valid() { // Q5: the fifth tag writer. Every argument here is well-formed — // `externalId` and `managedBy` are the required pair and both are present — // so the ONLY thing this call can fail on is `tags`. That matters: a call // missing a required field is refused whether or not tags were ever // retired, and a test written that way proves nothing. let g = gaps_harness(); let answer = call_tool_raw( &g.h, &g.secret, "upsert_managed_note", json!({ "externalId": "reading-list", "managedBy": "reading-list-sync", "title": "Reading list", "body": "Nothing yet.", "tags": ["Travel"], }), ); assert!(answer.is_error); assert!(answer.text.contains("tags were retired"), "{}", answer.text); assert!(answer.text.contains("link_to_project"), "{}", answer.text); // And nothing landed: a refused call writes no note at all, so a sync // script cannot half-succeed and then re-send a "changed" body forever. assert_eq!( count( &g.h, "SELECT COUNT(*) AS n FROM cotton_notes WHERE external_id = ?", &[SqlValue::Text("reading-list".to_string())], ), 0 ); } #[test] fn and_takes_the_same_call_without_them() { // The other half, and the reason the case above is not just an assertion // that the tool is broken: drop `tags` and the very same call succeeds. let g = gaps_harness(); let ok = call_tool( &g.h, &g.secret, "upsert_managed_note", json!({ "externalId": "reading-list", "managedBy": "reading-list-sync", "title": "Reading list", "body": "Nothing yet.", }), ); assert_eq!(ok["status"], "created"); assert_eq!( count( &g.h, "SELECT COUNT(*) AS n FROM cotton_notes WHERE external_id = ? AND title = ?", &[ SqlValue::Text("reading-list".to_string()), SqlValue::Text("Reading list".to_string()), ], ), 1 ); } /// A created event names no calendar, and is listed beside the events that /// name the file's own: what lists an event is the database, never a calendar. #[test] fn a_created_event_names_no_calendar_and_is_listed() { let g = gaps_harness(); let made = call_tool( &g.h, &g.secret, "create_event", json!({ "title": "walk", "startsAt": "2026-09-04T07:00:00.000Z" }), ); assert_eq!(column(&g.h, "cotton_events", "collection_id", &id_of(&made)), None); let listed = call_tool( &g.h, &g.secret, "list_events", json!({ "from": "2026-09-01T00:00:00.000Z", "to": "2026-09-10T00:00:00.000Z" }), ); let walk = listed["events"].as_array().expect("events").iter().find(|event| event["id"] == id_of(&made)).cloned().expect("the walk is listed"); assert_eq!(walk["calendar"], Value::Null); } // ── the write tools, from `mcp.test.ts` ───────────────────────────────────── // // Does what an assistant writes become a change every device pulls? Seeded // through the server's own sync endpoint rather than by INSERTing rows, so the // fixtures travel the same path a phone's would. struct Writes { h: Harness, secret: String, todo: String, } fn writes_harness() -> Writes { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); let todo = fixture_id("writes-todo"); let note = fixture_id("writes-note"); seed( &h, vec![ op( "cotton_todos", &todo, json!({ "title": "buy cardamom", "notes": "the green ones", "status": "open", "priority": 0, "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), ), op( "cotton_notes", ¬e, json!({ "title": "kitchen rebuild", "body": "cardamom shelf goes above the hob", "kind": "note", "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), ), ], ); Writes { h, secret, todo } } /// Every materialized occurrence in the file, oldest first. fn occurrences_of(h: &Harness) -> Vec<(String, String)> { h.with(|db| { db.all( "SELECT title, occurrence_at FROM cotton_todos WHERE recurrence_id IS NOT NULL \ ORDER BY occurrence_at", &[], ) }) .expect("the read runs") .iter() .map(|row| { ( row.text("title").unwrap_or_default().to_string(), row.text("occurrence_at").unwrap_or_default().to_string(), ) }) .collect() } // ── recurring todos ───────────────────────────────────────────────────────── /// RULE (decision 7, 7 Nov 2026): a todo rule is read strictly — a key a /// repeating todo does not keep is refused in words, never silently re-read. #[test] fn a_todo_rule_with_a_key_a_todo_does_not_keep_is_refused_in_words() { let w = writes_harness(); seed_zone(&w.h, KOLKATA); let refused = call_tool_raw( &w.h, &w.secret, "create_todo", json!({ "title": "Pay the rent", "dueAt": "2026-09-02T04:00:00.000Z", "rrule": "FREQ=MONTHLY;BYMONTHDAY=2" }), ); assert!(refused.is_error); assert!(refused.text.contains("RRULE BYMONTHDAY is not kept"), "{}", refused.text); assert!(occurrences_of(&w.h).is_empty()); } #[test] fn creates_a_repeating_todo_and_materializes_its_first_occurrence() { // This path was BROKEN on the server and said nothing about it: the shared // materializer guarded its mark with a PostgREST `.or(...lt...)` filter the // file's query adapter does not implement, so every rrule create threw. let w = writes_harness(); seed_zone(&w.h, KOLKATA); let result = call_tool( &w.h, &w.secret, "create_todo", json!({ "title": "Pay the rent", "dueAt": "2026-09-02T04:00:00.000Z", "rrule": "FREQ=MONTHLY", }), ); assert!(result["id"].is_string()); // And the rows are actually THERE. Asserting only the absence of an error // let this test pass through the whole zone change while materializing // nothing at all. let rows = occurrences_of(&w.h); assert!(!rows.is_empty()); assert_eq!(rows[0].0, "Pay the rent"); // Exactly one, at dtstart. Note what this does NOT prove: the first // occurrence IS dtstart, so it lands on the same instant in every zone. assert_eq!(rows[0].1, "2026-09-02T04:00:00.000Z"); } #[test] fn creates_the_series_but_materializes_nothing_when_no_zone_is_recorded() { // ONE PRODUCER PER STATE. The server used to floor to UTC here while the // phone expanded in the device's zone — two halves minting occurrences at // different instants, and because the row id is derived from the instant, // two rows for every occurrence. Now the server rests and says so. let w = writes_harness(); let result = call_tool( &w.h, &w.secret, "create_todo", json!({ "title": "Pay the rent", "dueAt": "2026-09-02T04:00:00.000Z", "rrule": "FREQ=MONTHLY", }), ); // The series exists — the ask is not refused, only the guessing is. assert!(result["id"].is_string()); assert_eq!(result["repeats"], "FREQ=MONTHLY"); // And the caller is TOLD, rather than left to wonder where the rows went. assert_eq!( result["note"], "occurrences appear once the app sets the workspace timezone" ); assert_eq!(occurrences_of(&w.h), Vec::new()); // The template is real, so the phone's sweep picks it up unprompted. assert_eq!( count( &w.h, "SELECT COUNT(*) AS n FROM cotton_todo_recurrences", &[], ), 1 ); } // ── write tools ───────────────────────────────────────────────────────────── #[test] fn dates_an_undated_journal_append_by_the_workspaces_zone_not_utc() { // Same defect as today_agenda's UTC default, on the write side: between // 00:00 and 05:30 IST an undated append landed on YESTERDAY's page, while // the same words typed into the app landed on today's. // // A FIXED clock, at an instant where the two calendars actually DISAGREE: // 19:00Z on the 2nd is 00:30 IST on the 3rd. An assertion taken at any // other hour agrees with a UTC regression 18.5 hours a day. let w = writes_harness(); w.h.clock.set( chrono::DateTime::parse_from_rfc3339("2026-09-02T19:00:00Z") .expect("a literal instant") .with_timezone(&chrono::Utc), ); seed_zone(&w.h, KOLKATA); let result = call_tool( &w.h, &w.secret, "append_journal", json!({ "text": "wrote the server's timezone default" }), ); assert_eq!(result["journal_date"], "2026-09-03"); assert_ne!(result["journal_date"], "2026-09-02"); } #[test] fn still_honours_an_explicit_journal_date() { let w = writes_harness(); let result = call_tool( &w.h, &w.secret, "append_journal", json!({ "text": "backfilled", "date": "2026-08-01" }), ); assert_eq!(result["journal_date"], "2026-08-01"); } #[test] fn creates_a_todo_that_lands_in_the_file_and_in_the_op_log() { let w = writes_harness(); let before = w.h.cursors(); let result = call_tool( &w.h, &w.secret, "create_todo", json!({ "title": "order more cardamom" }), ); let id = id_of(&result); assert_eq!( column(&w.h, "cotton_todos", "title", &id).as_deref(), Some("order more cardamom") ); // The part that matters for the product: an assistant's write is a sync op, // so the phone pulls it like any other change. let todo_ops: Vec> = w.h.ops_since(&before) .into_iter() .filter(|op| op["tbl"] == "cotton_todos") .collect(); assert!(!todo_ops.is_empty()); // Stamped by the FILE's author (`_meta.author_id`, slice 2c). assert_eq!(todo_ops[0]["device_id"], w.h.file_author().as_str()); } #[test] fn completes_a_todo() { let w = writes_harness(); call_tool(&w.h, &w.secret, "complete_todo", json!({ "id": w.todo })); assert_eq!( column(&w.h, "cotton_todos", "status", &w.todo).as_deref(), Some("done") ); } #[test] fn creates_a_note_stamped_with_the_connections_name() { let w = writes_harness(); let result = call_tool( &w.h, &w.secret, "create_note", json!({ "title": "from the assistant", "body": "written over MCP" }), ); let id = id_of(&result); assert_eq!( column(&w.h, "cotton_notes", "author_kind", &id).as_deref(), Some("agent") ); assert_eq!( column(&w.h, "cotton_notes", "author_label", &id).as_deref(), Some("Claude") ); } #[test] fn records_version_history_when_it_edits_a_note_the_triggers_job() { let w = writes_harness(); let created = call_tool( &w.h, &w.secret, "create_note", json!({ "title": "v1", "body": "first" }), ); let note = id_of(&created); call_tool( &w.h, &w.secret, "update_note", json!({ "id": note, "body": "second" }), ); let versions = w.h.with(|db| { db.all( "SELECT after, before FROM cotton_changes WHERE record_id = ? AND before IS NOT NULL", &[SqlValue::Text(note.clone())], ) }) .expect("the read runs"); assert_eq!(versions.len(), 1); assert!(versions[0].text("after").is_some(), "an update, not a delete"); // History holds what the row WAS, which is the whole point of keeping it. let data: Value = serde_json::from_str(versions[0].text("before").unwrap_or("{}")) .expect("the version payload is JSON"); assert_eq!(data["body"], "first"); } #[test] fn bumps_updated_at_on_edit_moddatetimes_job() { let w = writes_harness(); call_tool(&w.h, &w.secret, "complete_todo", json!({ "id": w.todo })); assert_ne!( column(&w.h, "cotton_todos", "updated_at", &w.todo).as_deref(), Some(AT) ); } // ── append_journal with a project ─────────────────────────────────────────── // // The per-project journal: a page belongs to a CONTEXT — the owner's own // journal, or one project — and `append_journal`'s optional `project` is the // only writer of the project side. struct Journal { h: Harness, secret: String, project: String, } /// A workspace with the project "pyro" in it. /// /// The TypeScript makes the project with `create_project`; that tool belongs to /// the projects group, so this seeds the row through sync instead — which is /// also how the app would make one. fn with_project() -> Journal { let w = writes_harness(); let project = fixture_id("project-pyro"); seed( &w.h, vec![op( "cotton_memory_projects", &project, json!({ "slug": "pyro", "name": "Pyro", "workspace_id": w.h.workspace_id, "created_at": AT, "updated_at": AT, }), )], ); Journal { h: w.h, secret: w.secret, project, } } /// Every journal page in the file, so a test can say which is whose. fn journal_rows(h: &Harness) -> Vec> { h.with(|db| { db.all( "SELECT id, journal_date, project_id, body, author_kind, author_label \ FROM cotton_notes WHERE kind = 'journal' ORDER BY journal_date, project_id", &[], ) }) .expect("the read runs") .iter() .map(|row| { let mut out = Map::new(); for name in [ "id", "journal_date", "project_id", "body", "author_kind", "author_label", ] { out.insert( name.to_string(), row.text(name).map_or(Value::Null, Value::from), ); } out }) .collect() } fn link_rows(h: &Harness) -> Vec> { h.with(|db| { db.all( "SELECT id, record_id, applied_by, project_id FROM cotton_project_links \ WHERE record_kind = 'journal'", &[], ) }) .expect("the read runs") .iter() .map(|row| { let mut out = Map::new(); for name in ["id", "record_id", "applied_by", "project_id"] { out.insert( name.to_string(), row.text(name).map_or(Value::Null, Value::from), ); } out }) .collect() } fn run_sql(h: &Harness, sql: &str, params: &[SqlValue]) { h.with(|db| db.run(sql, params)) .expect("the statement runs"); } #[test] fn creates_the_projects_page_stamps_the_agent_and_mirrors_the_link_row() { let j = with_project(); let result = call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "Landed the migration; the dry-run is clean.", }), ); assert_eq!(result["created"], true); assert_eq!(result["project"], "pyro"); assert_eq!(result["journal_date"], "2026-09-02"); let pages = journal_rows(&j.h); assert_eq!(pages.len(), 1); assert_eq!(pages[0]["project_id"], j.project); assert_eq!(pages[0]["author_kind"], "agent"); assert_eq!( pages[0]["body"], "Landed the migration; the dry-run is clean." ); assert!(pages[0]["author_label"] .as_str() .is_some_and(|l| !l.is_empty())); // The mirror rides the DERIVED id, so a replay converges on this row. let links = link_rows(&j.h); assert_eq!(links.len(), 1); assert_eq!( links[0]["id"], project_link_id( &j.project, "journal", pages[0]["id"].as_str().unwrap_or_default() ) ); assert_eq!(links[0]["record_id"], pages[0]["id"]); assert_eq!(links[0]["applied_by"], "agent"); } #[test] fn appends_a_second_entry_the_same_day_to_the_same_row_and_does_not_duplicate_the_link() { let j = with_project(); call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "Morning: the migration landed." }), ); let result = call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "Evening: the server deployed." }), ); assert_eq!(result["created"], false); assert_eq!(result["project"], "pyro"); let pages = journal_rows(&j.h); assert_eq!(pages.len(), 1); assert_eq!( pages[0]["body"], "Morning: the migration landed.\n\nEvening: the server deployed." ); assert_eq!(link_rows(&j.h).len(), 1); } #[test] fn keeps_his_page_and_the_projects_page_separate_on_the_same_day() { // The regression pair. Before the context column an assistant's project // entry and his own words shared one row for the day — and afterwards, a // lookup that filtered on neither would still have merged them. let j = with_project(); call_tool( &j.h, &j.secret, "append_journal", json!({ "date": "2026-09-02", "text": "his own words" }), ); call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "the project's progress" }), ); // ...and in the other order too: an owner append must never pick up a // project page that already exists for the day. call_tool( &j.h, &j.secret, "append_journal", json!({ "date": "2026-09-03", "text": "more of his own" }), ); let pages = journal_rows(&j.h); assert_eq!(pages.len(), 3); let own: Vec<&Value> = pages .iter() .filter(|page| page["project_id"].is_null()) .map(|page| &page["body"]) .collect(); assert_eq!(own, vec!["his own words", "more of his own"]); let scoped: Vec<&Value> = pages .iter() .filter(|page| page["project_id"] == j.project) .map(|page| &page["body"]) .collect(); assert_eq!(scoped, vec!["the project's progress"]); // Only the project's page is mirrored into the links table; his own pages // join no project by being written. assert_eq!(link_rows(&j.h).len(), 1); } #[test] fn appends_to_a_page_he_wrote_without_restamping_it_as_the_assistants() { let j = with_project(); // An app-written page: `author_kind = 'user'`, no label — the shape the // phone writes, which no MCP fixture can produce. run_sql( &j.h, "INSERT INTO cotton_notes \ (id, workspace_id, kind, body, journal_date, author_kind, author_label, created_at, updated_at) \ VALUES ('his-page', ?, 'journal', 'what he wrote', '2026-09-02', 'user', NULL, ?, ?)", &[ SqlValue::Text(j.h.workspace_id.clone()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ); let result = call_tool( &j.h, &j.secret, "append_journal", json!({ "date": "2026-09-02", "text": "an assistant's line" }), ); assert_eq!(result["id"], "his-page"); assert_eq!(result["created"], false); let page = journal_rows(&j.h).remove(0); assert_eq!(page["body"], "what he wrote\n\nan assistant's line"); // The APPEND branch writes the body and clears `archived_at`, and nothing // else. The page stays HIS, so the editor's byline keeps saying so — an // assistant adding a line to his day does not take the day off him. assert_eq!(page["author_kind"], "user"); assert_eq!(page["author_label"], Value::Null); } #[test] fn saves_the_text_and_reports_a_failed_mirror_rather_than_throwing_over_it() { // The order of the two writes decides what a failure may do. Before the // note write, throwing is honest: nothing landed. After it, a thrown error // reaches the assistant as "the call failed" — and the natural response to // a failed append is to send it again, which puts the SAME paragraph on the // page twice. The mirror is derived and self-healing; the words are not. let j = with_project(); let first = call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "one" }), ); let note = id_of(&first); // A REAL failure, not a mock: a link row for the same // (project, kind, record) under a foreign id — an older producer's row. // `ensure_journal_mirror` reads by the DERIVED id, misses it, and its // insert then hits the table's `UNIQUE (project_id, record_kind, // record_id)`. run_sql( &j.h, "DELETE FROM cotton_project_links WHERE record_id = ?", &[SqlValue::Text(note.clone())], ); run_sql( &j.h, "INSERT INTO cotton_project_links \ (id, workspace_id, project_id, record_kind, record_id, note, applied_by, created_at, updated_at) \ VALUES ('squatter', ?, ?, 'journal', ?, NULL, 'user', ?, ?)", &[ SqlValue::Text(j.h.workspace_id.clone()), SqlValue::Text(j.project.clone()), SqlValue::Text(note.clone()), SqlValue::Text(AT.to_string()), SqlValue::Text(AT.to_string()), ], ); let second = call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "two" }), ); // Success, with the mirror named as the part that did not happen. assert!( second["link"] .as_str() .is_some_and(|link| link.contains("failed")), "{second}" ); assert_eq!(journal_rows(&j.h)[0]["body"], "one\n\ntwo"); // …and once the obstruction is gone the next entry converges the mirror by // itself, on the derived id, with the text appended exactly once more. run_sql( &j.h, "DELETE FROM cotton_project_links WHERE id = 'squatter'", &[], ); let third = call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "date": "2026-09-02", "text": "three" }), ); assert!(third.get("link").is_none(), "{third}"); assert_eq!(journal_rows(&j.h)[0]["body"], "one\n\ntwo\n\nthree"); let links = link_rows(&j.h); assert_eq!(links.len(), 1); assert_eq!( links[0]["id"], project_link_id(&j.project, "journal", ¬e) ); } #[test] fn refuses_project_null_rather_than_quietly_writing_his_own_page() { // The absent case has a NAME — omitting the argument — and `null` is not // it. An assistant that templates the argument and has no value for it // emits null; treating that as "his own journal" would put a project's // progress entry in the owner's diary, silently, which is the one mistake // this parameter exists to make impossible. let j = with_project(); let refused = call_tool_raw( &j.h, &j.secret, "append_journal", json!({ "project": Value::Null, "text": "should not land anywhere" }), ); assert!(refused.is_error); assert!(refused.text.contains("slug"), "{}", refused.text); // …and the refusal names the way to write his page on purpose. assert!(refused.text.contains("omit project"), "{}", refused.text); assert!(journal_rows(&j.h).is_empty()); assert!(link_rows(&j.h).is_empty()); } #[test] fn refuses_an_unknown_slug_and_writes_nothing_at_all() { let j = with_project(); let refused = call_tool_raw( &j.h, &j.secret, "append_journal", json!({ "project": "nope", "text": "should not land" }), ); assert!(refused.is_error); assert!(refused.text.contains("nope"), "{}", refused.text); assert!(journal_rows(&j.h).is_empty()); assert!(link_rows(&j.h).is_empty()); } #[test] fn dates_an_undated_project_append_by_the_workspaces_zone_too() { // A FIXED clock at an instant the two calendars disagree on: 19:00Z on the // 2nd is 00:30 IST on the 3rd. Any other hour would pass a UTC regression. let j = with_project(); j.h.clock.set( chrono::DateTime::parse_from_rfc3339("2026-09-02T19:00:00Z") .expect("a literal instant") .with_timezone(&chrono::Utc), ); seed_zone(&j.h, KOLKATA); let result = call_tool( &j.h, &j.secret, "append_journal", json!({ "project": "pyro", "text": "no date named" }), ); assert_eq!(result["journal_date"], "2026-09-03"); assert_ne!(result["journal_date"], "2026-09-02"); assert_eq!(journal_rows(&j.h)[0]["project_id"], j.project); } // ── the tools with no suite of their own in the TypeScript ────────────────── // // `archive_note`, `list_managed_notes` and `resolve_comment` are // exercised only in passing over there — through the projects and calls suites, // which belong to other groups. One behaviour test each, so this group's floor // holds without borrowing another group's fixture. #[test] fn archives_a_note_out_of_the_live_list_idempotently() { let w = writes_harness(); let made = call_tool( &w.h, &w.secret, "create_note", json!({ "title": "shelved", "body": "for later" }), ); let id = id_of(&made); let archived = call_tool(&w.h, &w.secret, "archive_note", json!({ "id": id })); assert_eq!(archived["alreadyArchived"], false); assert!(column(&w.h, "cotton_notes", "archived_at", &id).is_some()); let again = call_tool(&w.h, &w.secret, "archive_note", json!({ "id": id })); assert_eq!(again["alreadyArchived"], true); let missing = call_tool_raw( &w.h, &w.secret, "archive_note", json!({ "id": fixture_id("note-gone") }), ); assert!(missing.is_error); } #[test] fn lists_only_the_notes_a_named_script_manages() { let w = writes_harness(); for (external, managed_by, title) in [ ("reading-list", "reading-list-sync", "Reading list"), ("watchlist", "reading-list-sync", "Watchlist"), ("stocks", "another-script", "Stocks"), ] { call_tool( &w.h, &w.secret, "upsert_managed_note", json!({ "externalId": external, "managedBy": managed_by, "title": title, "body": "…", }), ); } let mine = call_tool( &w.h, &w.secret, "list_managed_notes", json!({ "managedBy": "reading-list-sync" }), ); let externals: Vec<&str> = mine["notes"] .as_array() .expect("notes") .iter() .map(|note| note["externalId"].as_str().unwrap_or_default()) .collect(); assert_eq!(externals, vec!["reading-list", "watchlist"]); // A hand-written note is nobody's to sync, so the other script's index // does not carry it either — `managedBy` is required precisely so that a // manager can never be handed somebody else's pages. call_tool( &w.h, &w.secret, "create_note", json!({ "title": "by hand", "body": "mine" }), ); let other = call_tool( &w.h, &w.secret, "list_managed_notes", json!({ "managedBy": "another-script" }), ); let externals: Vec<&str> = other["notes"] .as_array() .expect("notes") .iter() .map(|note| note["externalId"].as_str().unwrap_or_default()) .collect(); assert_eq!(externals, vec!["stocks"]); let unnamed = call_tool_raw(&w.h, &w.secret, "list_managed_notes", json!({})); assert!(unnamed.is_error); assert!(unnamed.text.contains("managedBy"), "{}", unnamed.text); } // ── whose comment is it ───────────────────────────────────────────────────── // // `author_kind` is read by two things that cannot ask anybody: the app draws // the byline from it, and the server's assistant worker matches // `author_kind = 'user'` when it looks for a question the owner asked back on // an answer the assistant wrote. A comment the owner typed on their own phone // and stamped `agent` is a question nobody ever answers, under a byline that // reads as a device id. The whole of the difference is the write context. /// The device id the owner's own app calls under here — synthetic. const OWNER_DEVICE: &str = "device:01M26AHE3JBSN1BKDVJ9ZEQH8F"; // ── no label: groups sort todos ───────────────────────────────────────────── #[test] fn every_todo_verb_refuses_a_label_and_the_list_answers_none() { let s = seeded_harness(Some(KOLKATA)); for (tool, args) in [ ("create_todo", json!({ "title": "Renew the invented passport", "label": "Renew passport" })), ("update_todo", json!({ "id": s.timed, "label": "Stand up" })), ("update_todo", json!({ "id": s.timed, "label": Value::Null })), ("update_todos", json!({ "ids": [s.timed, s.undated], "label": "Same words" })), ] { let refused = call_tool_raw(&s.h, &s.secret, tool, args.clone()); assert!(refused.is_error, "{tool} {args} was taken: {}", refused.text); assert!(refused.text.contains("create_group"), "{tool} points at groups: {}", refused.text); } let listed = call_tool(&s.h, &s.secret, "list_todos", json!({})); assert!( listed["todos"].as_array().expect("todos").iter().all(|todo| todo.get("label").is_none()), "{listed}" ); } // ── a note's pictures (schema v32) ────────────────────────────────────────── // // A picture on a note is a REFERENCE to a record that already exists, held in // `cotton_note_attachments`. Three rules are what these cases are about: the // list an update sends is the WHOLE list, a row that did not move keeps its // clock, and a picture removed from the library leaves its attachment row // standing so the note still says it was there. struct Attached { h: Harness, secret: String, note: String, photo: String, video: String, document: String, } /// A 64-character content hash, distinct per letter. fn media_hash(letter: char) -> String { std::iter::repeat_n(letter, 64).collect() } fn attachments_harness() -> Attached { let h = Harness::new(); let secret = mint_token_ref(&h, &["read", "write"], "Claude"); let note = fixture_id("attach-note"); let photo = format!("photo:{}", media_hash('a')); let video = format!("video:{}", media_hash('b')); let document = fixture_id("attach-document"); seed( &h, vec![ op( "cotton_notes", ¬e, json!({ "title": "kitchen rebuild", "body": "the hob wall, before and after", "kind": "note", "workspace_id": h.workspace_id, "created_at": AT, "updated_at": AT, }), ), op( "cotton_photos", &photo, json!({ "workspace_id": h.workspace_id, "key": format!("{}/photos/{}.jpg", h.workspace_id, media_hash('a')), "sha256": media_hash('a'), "content_type": "image/jpeg", "size_bytes": 4096, "width": 1200, "height": 900, "taken_at": AT, "caption": "the hob wall", "created_at": AT, "updated_at": AT, }), ), op( "cotton_videos", &video, json!({ "workspace_id": h.workspace_id, "key": format!("{}/videos/{}.mov", h.workspace_id, media_hash('b')), "poster_key": format!("{}/videos/{}-poster.jpg", h.workspace_id, media_hash('b')), "sha256": media_hash('b'), "content_type": "video/quicktime", "size_bytes": 8_000_000, "width": 1920, "height": 1080, "taken_at": AT, "created_at": AT, "updated_at": AT, }), ), op( "cotton_documents", &document, json!({ "workspace_id": h.workspace_id, "title": "Lease", "original_name": "lease.pdf", "mime": "application/pdf", "byte_size": 4096, "sha256": media_hash('c'), "storage_path": format!("{}/documents/lease.pdf", h.workspace_id), "status": "ready", "status_changed_at": AT, "facts": {}, "source": "app", "created_at": AT, "updated_at": AT, }), ), ], ); Attached { h, secret, note, photo, video, document, } } /// What `get_record` says the note shows. fn attachments_of(a: &Attached, note: &str) -> Vec { let record = call_tool( &a.h, &a.secret, "get_record", json!({ "kind": "note", "id": note }), ); record["attachments"] .as_array() .expect("attachments") .clone() } #[test] fn a_new_note_carries_the_pictures_it_was_given_in_that_order() { let a = attachments_harness(); let made = call_tool( &a.h, &a.secret, "create_note", json!({ "title": "the hob wall", "body": "![before](cotton:photo/{id})", "attachments": [ { "kind": "document", "id": a.document }, { "kind": "photo", "id": a.photo, "caption": "the wall before" }, ], }), ); let note = id_of(&made); let held = attachments_of(&a, ¬e); assert_eq!(held.len(), 2); assert_eq!(held[0]["kind"], "document"); assert_eq!(held[0]["position"], 0); assert_eq!(held[0]["title"], "Lease"); assert_eq!(held[0]["mime"], "application/pdf"); assert_eq!(held[0]["missing"], false); assert_eq!(held[0]["bytes"]["tool"], "get_document_bytes"); assert_eq!(held[0]["bytes"]["args"]["documentId"], json!(a.document)); assert_eq!(held[1]["kind"], "photo"); assert_eq!(held[1]["position"], 1); // The note's own words win over the picture's own caption. assert_eq!(held[1]["caption"], "the wall before"); assert_eq!(held[1]["contentType"], "image/jpeg"); assert_eq!(held[1]["width"], 1200); assert_eq!( held[1]["key"], json!(format!("{}/photos/{}.jpg", a.h.workspace_id, media_hash('a'))) ); assert_eq!(held[1]["bytes"]["tool"], "get_photo_bytes"); assert_eq!(held[1]["bytes"]["args"]["id"], json!(a.photo)); } #[test] fn a_video_names_its_poster_and_says_why_it_carries_no_bytes() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [{ "kind": "video", "id": a.video }] }), ); let held = attachments_of(&a, &a.note); assert_eq!(held[0]["kind"], "video"); assert_eq!( held[0]["key"], json!(format!( "{}/videos/{}-poster.jpg", a.h.workspace_id, media_hash('b') )) ); assert_eq!(held[0]["bytes"], Value::Null); assert!(held[0]["bytesNote"] .as_str() .unwrap_or_default() .contains("get_video")); } #[test] fn a_second_list_replaces_the_set_and_a_row_that_did_not_move_keeps_its_clock() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "photo", "id": a.photo }, { "kind": "video", "id": a.video }, ], }), ); let photo_row = note_attachment_id(&a.note, "photo", &a.photo); let video_row = note_attachment_id(&a.note, "video", &a.video); let photo_stamp = column(&a.h, "cotton_note_attachments", "updated_at", &photo_row); assert!(photo_stamp.is_some()); // The photo stays exactly where it was; the video goes and a document // takes its place. call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "photo", "id": a.photo }, { "kind": "document", "id": a.document }, ], }), ); let held = attachments_of(&a, &a.note); let named: Vec<&str> = held .iter() .map(|item| item["kind"].as_str().unwrap_or_default()) .collect(); assert_eq!(named, vec!["photo", "document"]); assert_eq!( column(&a.h, "cotton_note_attachments", "updated_at", &photo_row), photo_stamp, "the photo did not move, so its row must not have been rewritten" ); assert_eq!( column(&a.h, "cotton_note_attachments", "id", &video_row), None, "a picture the list no longer names is a row delete" ); } #[test] fn an_empty_list_takes_every_picture_off_and_an_absent_one_changes_nothing() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [{ "kind": "photo", "id": a.photo }] }), ); // An edit that says nothing about pictures leaves them alone. call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "body": "still the hob wall" }), ); assert_eq!(attachments_of(&a, &a.note).len(), 1); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [] }), ); assert!(attachments_of(&a, &a.note).is_empty()); } #[test] fn a_removed_picture_leaves_its_row_and_the_reader_says_it_is_missing() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [{ "kind": "photo", "id": a.photo, "caption": "the wall before" }], }), ); a.h.run( "DELETE FROM cotton_photos WHERE id = ?", &[SqlValue::Text(a.photo.clone())], ); let held = attachments_of(&a, &a.note); assert_eq!(held.len(), 1, "the attachment row outlives the picture"); assert_eq!(held[0]["missing"], true); assert_eq!(held[0]["key"], Value::Null); assert_eq!(held[0]["bytes"], Value::Null); // The note's own words survive the picture: it still says what was there. assert_eq!(held[0]["caption"], "the wall before"); } /// THE OTHER HALF OF THE MISSING RULE. The row stands, the list REPLACES, and /// every editor re-sends the whole list — so a note holding a removed picture /// has to stay editable. Checking a pair the note already holds refused the /// WHOLE call and made the note uneditable from the one screen that edits it. #[test] fn a_note_holding_a_removed_picture_can_still_be_edited() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [{ "kind": "photo", "id": a.photo, "caption": "the wall before" }], }), ); a.h.run( "DELETE FROM cotton_photos WHERE id = ?", &[SqlValue::Text(a.photo.clone())], ); // The phone re-sends what `get_record` gave it — the missing row included — // plus the document it is adding. call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "photo", "id": a.photo }, { "kind": "document", "id": a.document }, ], }), ); let held = attachments_of(&a, &a.note); assert_eq!(held.len(), 2, "the missing row stands and the new one is added"); assert_eq!(held[0]["kind"], "photo"); assert_eq!(held[0]["missing"], true); assert_eq!( held[0]["caption"], "the wall before", "a re-send that says nothing about the caption leaves it alone" ); assert_eq!(held[1]["kind"], "document"); assert_eq!(held[1]["missing"], false); } /// A pair the note does NOT hold is a new reference, and a new reference is /// still held honest — by name. #[test] fn a_new_attachment_whose_target_is_gone_is_still_refused_by_name() { let a = attachments_harness(); a.h.run( "DELETE FROM cotton_photos WHERE id = ?", &[SqlValue::Text(a.photo.clone())], ); let refused = call_tool_raw( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [{ "kind": "photo", "id": a.photo }] }), ); assert!(refused.is_error); assert!( refused.text.contains("no photo with id"), "the refusal names the kind and the id: {}", refused.text ); assert!(attachments_of(&a, &a.note).is_empty(), "and it wrote none of it"); } /// A CAPTION HAS THREE STATES, and the key left out is the one the phone sends. /// `get_record` hands the phone `{ kind, id }`-shaped rows, so reading an /// absent `caption` as null wiped every caption the owner had written the first /// time a note was reordered. #[test] fn a_caption_survives_a_kind_and_id_only_re_send_and_null_is_what_clears_it() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "photo", "id": a.photo, "caption": "the wall before" }, { "kind": "video", "id": a.video, "caption": "the wall after" }, ], }), ); // The phone reorders. It sends what it has: the pair, and nothing else. call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "video", "id": a.video }, { "kind": "photo", "id": a.photo }, ], }), ); let held = attachments_of(&a, &a.note); assert_eq!(held[0]["kind"], "video"); assert_eq!(held[0]["caption"], "the wall after", "the order moved, the words did not"); assert_eq!(held[1]["caption"], "the wall before"); // `null` is the instruction to take one off. call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "video", "id": a.video, "caption": null }, { "kind": "photo", "id": a.photo, "caption": "the wall, later" }, ], }), ); let held = attachments_of(&a, &a.note); assert_eq!(held[0]["caption"], Value::Null, "cleared"); assert_eq!(held[1]["caption"], "the wall, later", "and a string sets one"); } /// TWO CAPTIONS, NEVER ONE COLLAPSED: what the note said, and what the picture /// says about itself. The collapse is why the phone could not send one back. #[test] fn get_record_says_the_notes_caption_and_the_records_own_separately() { let a = attachments_harness(); call_tool( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": [ { "kind": "photo", "id": a.photo, "caption": "the wall before" }, { "kind": "video", "id": a.video }, { "kind": "document", "id": a.document }, ], }), ); let held = attachments_of(&a, &a.note); assert_eq!(held[0]["caption"], "the wall before"); assert_eq!( held[0]["recordCaption"], "the hob wall", "the photo's own caption, beside the note's words and not instead of them" ); assert_eq!(held[1]["caption"], Value::Null, "the note gave the video none"); assert_eq!(held[1]["recordCaption"], Value::Null, "and neither did the video"); assert_eq!(held[2]["caption"], Value::Null); assert_eq!( held[2]["recordCaption"], "Lease", "a document's own words for itself are its title" ); assert_eq!(held[2]["title"], "Lease", "and `title` still says so"); } #[test] fn refuses_an_attachment_list_by_name_and_writes_none_of_it() { let a = attachments_harness(); let refusals: Vec<(Value, &str)> = vec![ ( json!([{ "kind": "sketch", "id": a.photo }]), "attachment.kind must be one of", ), ( json!([ { "kind": "photo", "id": a.photo }, { "kind": "photo", "id": a.photo }, ]), "in the list twice", ), ( json!([{ "kind": "photo", "id": format!("photo:{}", media_hash('f')) }]), "no photo with id", ), ( json!([{ "kind": "photo", "id": "photo:not-a-hash" }]), "64-character content hash", ), ( json!([{ "kind": "document", "id": "lease.pdf" }]), "must be a document's uuid", ), (json!(null), "pass [] to take every picture off"), ]; for (attachments, says) in refusals { let refused = call_tool_raw( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": attachments }), ); assert!(refused.is_error, "accepted {attachments}"); assert!( refused.text.contains(says), "{} does not say {says}", refused.text ); } assert!(attachments_of(&a, &a.note).is_empty()); } #[test] fn refuses_more_attachments_than_a_note_may_carry() { // The cap is read from where it is DECLARED, not written here: version 33 of // the store's ladder raised it from fifty to five hundred so a converted // walkthrough — a screen per screen of the app — stays editable, and a copy // of the number in this file would have turned that into a failing test // instead of a passing one. let cap = cotton_tools::mcp::handlers::records_1::validate::MAX_ATTACHMENTS; let a = attachments_harness(); let many: Vec = (0..=cap) .map(|n| json!({ "kind": "photo", "id": format!("photo:{n:064x}") })) .collect(); let refused = call_tool_raw( &a.h, &a.secret, "update_note", json!({ "id": a.note, "attachments": many }), ); assert!(refused.is_error); assert!( refused.text.contains(&format!("at most {cap}")), "{}", refused.text ); } // ── a comment pinned to a picture ─────────────────────────────────────────── // ── handles (schema v90): a phone, an email or a social handle names one person ── /// RULE: create_person and update_person refuse a handle another person carries, however it is spelled, and name the holder. #[test] fn a_handle_another_person_carries_is_refused_on_create_and_update() { let p = people_harness(); let holder = id_of(&call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Kavya Rao", "phones": ["+91 90000 11111"], "instagram": ["kavya.makes"] }), )); let other = id_of(&call_tool(&p.h, &p.secret, "create_person", json!({ "fullName": "Kabir Rao" }))); for (tool, args) in [ ("create_person", json!({ "fullName": "K. Rao", "phones": ["919000011111"] })), ("update_person", json!({ "id": other, "instagram": ["https://instagram.com/Kavya.Makes"] })), ("update_person", json!({ "id": other, "phones": ["+919000011111"] })), ] { let failure = call_tool_raw(&p.h, &p.secret, tool, args); assert!(failure.is_error, "{tool} took a handle Kavya carries: {}", failure.text); assert!(failure.text.contains(&holder), "{tool}: {}", failure.text); } assert_eq!( count(&p.h, "SELECT COUNT(*) AS n FROM cotton_person_handles WHERE person_id = ?", &[SqlValue::Text(other.clone())]), 0 ); } /// RULE: the MCP people tools keep their phones/emails arguments and answers after the v90 fold — create, update and list read and write them as lists. #[test] fn phones_and_emails_still_go_in_and_come_out_of_the_people_tools() { let p = people_harness(); let id = id_of(&call_tool( &p.h, &p.secret, "create_person", json!({ "fullName": "Tara Iyer", "phones": ["+91 90000 22222"], "emails": ["Tara@Example.com"] }), )); call_tool(&p.h, &p.secret, "update_person", json!({ "id": id, "phones": ["+91 90000 22222", "+91 90000 33333"] })); let listed = call_tool(&p.h, &p.secret, "list_people", json!({})); let row = listed["people"] .as_array() .and_then(|rows| rows.iter().find(|row| row["id"] == id.as_str())) .cloned() .unwrap_or_else(|| panic!("Tara is listed: {listed}")); assert_eq!(row["phones"], json!(["+91 90000 22222", "+91 90000 33333"])); assert_eq!(row["emails"], json!(["Tara@Example.com"])); let record = call_tool(&p.h, &p.secret, "get_record", json!({ "kind": "person", "id": id })); assert_eq!(record["phones"], json!(["+91 90000 22222", "+91 90000 33333"]), "{record}"); assert_eq!( count(&p.h, "SELECT COUNT(*) AS n FROM cotton_person_handles WHERE person_id = ?", &[SqlValue::Text(id.clone())]), 3 ); }