Cotton code
300 lines · 12.3 KB · RustRaw
//! The alarm tools, end to end over `dispatch::call_tool` against a real store//! — the three verbs the owner's Alarms screen makes and no assistant sees.//!//! The rules asserted here: the two defaults, the weekday guard SQLite cannot//! express as a CHECK, the patch that moves only what it names, and the delete//! that really deletes.//!//! Called AS THE OWNER throughout (`call_tool_as_owner`), because that is the//! only caller these tools have. `mcp_owner.rs` holds the other half — that an//! assistant is refused every one of them, and that no `tools/list` names them//! — over the catalogue's own list of owner-scope tools, so these three are//! covered there without being written down twice.mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::call_tool_as_owner;/// The device id the owner's app writes under. Synthetic, like every fixture in/// this tree ([nothing-real-ever-goes-in-cotton-s-public-tree]).const DEVICE: &str = "device:00000000000000000000000000";fn alarm(h: &Harness, args: Value) -> Value {    let answer = call_tool_as_owner(h, DEVICE, "create_alarm", args);    assert!(!answer.is_error, "{}", answer.text);    answer.json()}fn stored(h: &Harness, id: &str) -> serde_json::Map<String, Value> {    h.one(        "SELECT id, label, hour, minute, repeat_days, enabled, sound FROM cotton_alarms \         WHERE id = ?",        &[SqlValue::Text(id.to_string())],    )    .expect("the alarm is in the file")}fn id_of(answer: &Value) -> String {    answer["id"].as_str().expect("an id").to_string()}// ── create ──────────────────────────────────────────────────────────────────#[test]fn an_alarm_you_just_set_is_one_you_want_and_one_you_want_to_hear() {    // The service's own two defaults, in its own words. Neither is a schema    // default this test is re-reading: both are decisions, and a caller that    // omits them means "on".    let h = Harness::new();    let created = alarm(&h, json!({ "hour": 6, "minute": 45 }));    assert_eq!(created["enabled"], json!(true));    assert_eq!(created["sound"], json!(true));    // An unnamed alarm carries the column's own empty string, never a word this    // layer invented — the screen decides what "no label" reads as.    assert_eq!(created["label"], json!(""));    assert_eq!(created["repeatDays"], json!([]));    assert_eq!(created["hour"], json!(6));    assert_eq!(created["minute"], json!(45));}#[test]fn an_empty_repeat_list_is_a_one_shot_rather_than_a_refusal() {    let h = Harness::new();    let created = alarm(&h, json!({ "hour": 7, "minute": 0, "repeatDays": [] }));    assert_eq!(created["repeatDays"], json!([]));    // `null` says the same thing, and refusing it would make the editor's own    // clear-the-days gesture an error.    let cleared = alarm(&h, json!({ "hour": 8, "minute": 0, "repeatDays": Value::Null }));    assert_eq!(cleared["repeatDays"], json!([]));}#[test]fn the_weekday_guard_sqlite_cannot_express_refuses_before_the_write() {    // Postgres had a CHECK that every entry was an ISO weekday; SQLite cannot    // express containment over a JSON array, so the guard moved into the    // service — and it moves here with it, BEFORE the write, rather than being    // lost.    let h = Harness::new();    for bad in [json!([0]), json!([8]), json!([1, 9]), json!(["mon"])] {        let answer =            call_tool_as_owner(&h, DEVICE, "create_alarm", json!({ "hour": 7, "minute": 0, "repeatDays": bad }));        assert!(answer.is_error, "{bad} was accepted");        assert!(            answer.text.contains("ISO weekdays 1–7"),            "{}",            answer.text        );    }    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_alarms", &[]), 0);}#[test]fn a_clock_the_column_s_check_would_reject_is_refused_with_a_sentence_instead() {    // The CHECK exists; what a caller gets from it is "constraint failed",    // which says nothing anybody could correct themselves from.    let h = Harness::new();    for (args, expect) in [        (json!({ "hour": 24, "minute": 0 }), "hour must be 0–23"),        (json!({ "hour": -1, "minute": 0 }), "hour must be 0–23"),        (json!({ "hour": 7, "minute": 60 }), "minute must be 0–59"),    ] {        let answer = call_tool_as_owner(&h, DEVICE, "create_alarm", args);        assert!(answer.is_error);        assert!(answer.text.contains(expect), "{}", answer.text);    }    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_alarms", &[]), 0);}#[test]fn the_row_the_scheduler_reads_is_what_the_tool_answered() {    let h = Harness::new();    let created = alarm(        &h,        json!({            "hour": 6,            "minute": 30,            "label": "Wake",            "repeatDays": [1, 2, 3, 4, 5],            "sound": false,        }),    );    let row = stored(&h, &id_of(&created));    assert_eq!(row.get("label").and_then(Value::as_str), Some("Wake"));    assert_eq!(row.get("hour").and_then(Value::as_i64), Some(6));    assert_eq!(row.get("minute").and_then(Value::as_i64), Some(30));    assert_eq!(created["repeatDays"], json!([1, 2, 3, 4, 5]));    assert_eq!(created["sound"], json!(false));    // Enabled was not named, so it took the default rather than the other    // field's value.    assert_eq!(created["enabled"], json!(true));}// ── update ──────────────────────────────────────────────────────────────────#[test]fn a_patch_moves_only_what_it_names() {    let h = Harness::new();    let created = alarm(        &h,        json!({ "hour": 6, "minute": 30, "label": "Wake", "repeatDays": [1, 2] }),    );    let id = id_of(&created);    // The switch on the row: one field, and nothing else moves.    let answer = call_tool_as_owner(&h, DEVICE, "update_alarm", json!({ "id": id, "enabled": false }));    assert!(!answer.is_error, "{}", answer.text);    let patched = answer.json();    assert_eq!(patched["enabled"], json!(false));    assert_eq!(patched["label"], json!("Wake"));    assert_eq!(patched["hour"], json!(6));    assert_eq!(patched["minute"], json!(30));    assert_eq!(patched["repeatDays"], json!([1, 2]));}#[test]fn the_editor_can_clear_the_days_and_cannot_clear_the_time() {    let h = Harness::new();    let id = id_of(&alarm(        &h,        json!({ "hour": 6, "minute": 30, "repeatDays": [1, 2] }),    ));    let cleared = call_tool_as_owner(        &h,        DEVICE,        "update_alarm",        json!({ "id": id, "repeatDays": [] }),    );    assert!(!cleared.is_error, "{}", cleared.text);    assert_eq!(cleared.json()["repeatDays"], json!([]));    // An alarm without a time is not an alarm, so `null` on the clock is a    // refusal rather than a write of nothing.    let refused =        call_tool_as_owner(&h, DEVICE, "update_alarm", json!({ "id": id, "hour": Value::Null }));    assert!(refused.is_error);    assert!(refused.text.contains("cannot be cleared"), "{}", refused.text);}#[test]fn an_update_naming_nothing_is_refused_rather_than_bumping_the_stamp() {    let h = Harness::new();    let id = id_of(&alarm(&h, json!({ "hour": 6, "minute": 30 })));    let refused = call_tool_as_owner(&h, DEVICE, "update_alarm", json!({ "id": id }));    assert!(refused.is_error);    assert!(refused.text.contains("nothing to change"), "{}", refused.text);}#[test]fn an_update_over_an_id_that_is_not_there_says_so_and_mints_nothing() {    // The writer UPSERTS, so an update over a missing id would otherwise create    // a half-filled row that fails the column's NOT NULLs — or worse, does not.    let h = Harness::new();    let refused = call_tool_as_owner(        &h,        DEVICE,        "update_alarm",        json!({ "id": support::synthetic_uuid("gone"), "enabled": false }),    );    assert!(refused.is_error);    assert!(refused.text.contains("no alarm"), "{}", refused.text);    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_alarms", &[]), 0);}// ── delete ──────────────────────────────────────────────────────────────────#[test]fn deleting_an_alarm_bins_it_and_names_what_went() {    // Every record a person deletes waits in the bin (5 Oct 2026); the phone's    // schedule read leaves a binned alarm out, so it never rings.    let h = Harness::new();    let id = id_of(&alarm(        &h,        json!({ "hour": 6, "minute": 30, "label": "Wake" }),    ));    let answer = call_tool_as_owner(&h, DEVICE, "delete_alarm", json!({ "id": id }));    assert!(!answer.is_error, "{}", answer.text);    let gone = answer.json();    assert_eq!(gone["deleted"], json!(true));    // The label rides back so the screen's receipt can name it — a deleted row    // cannot be read a second time to find out.    assert_eq!(gone["label"], json!("Wake"));    assert_eq!(h.count("SELECT COUNT(*) FROM cotton_alarms WHERE trashed_at IS NOT NULL", &[]), 1);}#[test]fn deleting_an_alarm_that_is_not_there_says_so() {    let h = Harness::new();    let refused = call_tool_as_owner(        &h,        DEVICE,        "delete_alarm",        json!({ "id": support::synthetic_uuid("gone") }),    );    assert!(refused.is_error);    assert!(refused.text.contains("no alarm"), "{}", refused.text);}// ── the ops the phone will push ─────────────────────────────────────────────#[test]fn every_alarm_write_leaves_an_op_so_the_owner_s_other_devices_see_it() {    // `cotton_alarms` is SYNCED — the durable list is the same on every device    // the owner has, and only the SCHEDULING is local. A write another device    // would never be handed is an alarm that exists on one phone.    //    // Asked a stage at a time, because there is no log to count entries in: the    // tables answer, so a create followed by a delete is ONE thing another    // device hears about, and the question worth asking is whether each write    // is discoverable while it stands.    let h = Harness::new();    let before = h.cursors();    let id = id_of(&alarm(&h, json!({ "hour": 6, "minute": 30 })));    let created = h.ops_since(&before);    // The file's first write (creation's shell, then the kit) already folded    // its author's `cotton_authors` fact (slice 2c), so each stage below is    // handed the alarm's own rows alone.    assert_eq!(kinds(&created), vec![("upsert", "cotton_alarms")]);    call_tool_as_owner(&h, DEVICE, "update_alarm", json!({ "id": id, "enabled": false }));    let updated = h.ops_since(&before);    // Two now, and that is the per-column shape rather than a second log line:    // the row's base stamp carries the whole alarm, and the column the update    // moved travels again at its own newer stamp.    assert_eq!(        kinds(&updated),        vec![("upsert", "cotton_alarms"), ("upsert", "cotton_alarms")]    );    assert!(        updated            .iter()            .any(|op| op["patch"].as_str().unwrap_or_default().contains("enabled")),        "the update is not in what another device would be handed: {updated:?}"    );    // A delete moves it to the bin: one more column write another device is    // handed, at its own newer stamp.    call_tool_as_owner(&h, DEVICE, "delete_alarm", json!({ "id": id }));    let binned = h.ops_since(&before);    assert!(        binned.iter().any(|op| op["patch"].as_str().unwrap_or_default().contains("trashed_at")),        "the bin move is not in what another device would be handed: {binned:?}"    );}/// `(kind, table)` per op, in the order a peer would fold them./// The ops' kinds and tables — the record writes; each act's history rows/// (slice 6b) travel beside them and are history's tests' to count.fn kinds(ops: &[serde_json::Map<String, Value>]) -> Vec<(&str, &str)> {    ops.iter()        .filter(|op| op["tbl"].as_str() != Some("cotton_changes"))        .map(|op| {            (                op["kind"].as_str().unwrap_or_default(),                op["tbl"].as_str().unwrap_or_default(),            )        })        .collect()}