Cotton code
180 lines · 9.8 KB · RustRaw
//! Groups that are a live filter, and groups of any table: a group is either records picked by hand or a `where` like//! list_records' — "the open todos", "the goals still going" — whose records//! are whatever the filter finds when it is read. Driven end to end through//! the dispatcher. Every name is invented.mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};fn harness() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}fn refused(h: &Harness, secret: &str, tool: &str, args: Value) -> String {    let answer = call_tool_raw(h, secret, tool, args);    assert!(answer.is_error, "{tool} was expected to refuse: {}", answer.text);    answer.text}fn made(h: &Harness, secret: &str, table: &str, data: Value) -> String {    let made = call_tool(h, secret, "create_record", json!({ "table": table, "data": data }));    made["record"]["id"].as_str().unwrap_or_else(|| panic!("no {table}: {made}")).to_string()}fn said(answer: &Value) -> &str {    answer["change"]["receipt"]["said"].as_str().unwrap_or_else(|| panic!("no receipt: {answer}"))}fn listed_ids(page: &Value) -> Vec<String> {    let mut ids: Vec<String> =        page["records"].as_array().unwrap().iter().map(|record| record["id"].as_str().unwrap().to_string()).collect();    ids.sort();    ids}fn sorted(of: &[&String]) -> Vec<String> {    let mut ids: Vec<String> = of.iter().map(|id| id.to_string()).collect();    ids.sort();    ids}/// RULE: A group may be a live filter instead of hand-picked records: it keeps a where like list_records', its records are whatever that finds when it is read (a record made later joins it), and add, remove and order are refused on it.#[test]fn a_group_can_be_a_live_filter() {    let (h, secret) = harness();    let gutters = made(&h, &secret, "todo", json!({ "title": "Clear the gutters", "status": "open" }));    let shed = made(&h, &secret, "todo", json!({ "title": "Paint the shed", "status": "done" }));    let answer = call_tool(&h, &secret, "create_group", json!({ "table": "todo", "name": "Going", "where": { "status": "open" } }));    assert_eq!(said(&answer), "Made Going");    let going = answer["group"]["id"].as_str().unwrap().to_string();    assert_eq!(answer["group"]["where"], json!({ "status": "open" }), "a filter group says its filter: {answer}");    assert_eq!(answer["group"]["count"], 1);    assert_eq!(answer["group"]["top"][0]["id"], gutters.as_str());    // Live: a goal made after the group joins it, and one that stops matching leaves.    let hedge = made(&h, &secret, "todo", json!({ "title": "Trim the hedge", "status": "open" }));    let page = call_tool(&h, &secret, "list_records", json!({ "table": "todo", "where": { "group": going } }));    assert_eq!(listed_ids(&page), sorted(&[&gutters, &hedge]), "{page}");    assert_eq!(page["total"], 2);    call_tool(&h, &secret, "update_record", json!({ "table": "todo", "id": gutters, "patch": { "status": "done" } }));    let page = call_tool(&h, &secret, "list_records", json!({ "table": "todo", "where": { "group": going } }));    assert_eq!(listed_ids(&page), sorted(&[&hedge]));    let groups = call_tool(&h, &secret, "list_groups", json!({ "table": "todo", "record": hedge }));    assert_eq!(groups["groups"][0]["count"], 1);    assert_eq!(groups["groups"][0]["holds"], true, "holds is whether the record matches the filter");    let groups = call_tool(&h, &secret, "list_groups", json!({ "table": "todo", "record": shed }));    assert_eq!(groups["groups"][0]["holds"], false);    for change in [json!({ "add": [shed] }), json!({ "remove": [hedge] }), json!({ "order": [hedge] })] {        let mut args = change.clone();        args["id"] = json!(going);        let text = refused(&h, &secret, "update_group", args);        assert!(text.contains("filter"), "a filter group's records are what it finds, not picked: {text}");    }    // The filter itself is changed with `where`, and undone like any change.    let changed = call_tool(&h, &secret, "update_group", json!({ "id": going, "where": { "status": "done" } }));    assert_eq!(said(&changed), "Changed what Going shows");    assert_eq!(changed["group"]["count"], 2);    let page = call_tool(&h, &secret, "list_records", json!({ "table": "todo", "where": { "group": going } }));    assert_eq!(listed_ids(&page), sorted(&[&gutters, &shed]));    call_tool(&h, &secret, "undo", json!({ "change_id": changed["change"]["id"] }));    let page = call_tool(&h, &secret, "list_records", json!({ "table": "todo", "where": { "group": going } }));    assert_eq!(listed_ids(&page), sorted(&[&hedge]), "undo puts the filter back");}/// RULE: A group's filter is checked as list_records' where is — an unknown column, a bad value or an empty filter is refused when the group is made, never kept to answer nothing later — and a group is either picked by hand or a filter, never both.#[test]fn a_filter_is_checked_when_it_is_kept() {    let (h, secret) = harness();    let gutters = made(&h, &secret, "todo", json!({ "title": "Clear the gutters", "status": "open" }));    for (filter, why) in [        (json!({ "colour": "red" }), "an unknown column"),        (json!({ "status": "sideways" }), "a value the column never holds"),        (json!({}), "an empty filter"),        (json!("status = open"), "a filter that is not an object"),    ] {        refused(&h, &secret, "create_group", json!({ "table": "todo", "name": "Odd", "where": filter }));        let _ = why;    }    let text = refused(        &h,        &secret,        "create_group",        json!({ "table": "todo", "name": "Both", "records": [gutters], "where": { "status": "open" } }),    );    assert!(text.contains("records") && text.contains("where"), "{text}");    // A hand-picked group does not turn into a filter.    let picked = call_tool(&h, &secret, "create_group", json!({ "table": "todo", "name": "Picked", "records": [gutters] }));    let id = picked["group"]["id"].as_str().unwrap();    assert!(picked["group"].get("where").map_or(true, Value::is_null), "{picked}");    refused(&h, &secret, "update_group", json!({ "id": id, "where": { "status": "open" } }));}/// RULE: Every table that keeps records takes groups, not only those whose definition draws stacks: a group of goals or of a table the person defined is made, picked by hand or by filter, and read through list_records like a group of people.#[test]fn every_table_takes_groups() {    let (h, secret) = harness();    let gutters = made(&h, &secret, "todo", json!({ "title": "Clear the gutters", "status": "open" }));    let picked = call_tool(&h, &secret, "create_group", json!({ "table": "todo", "name": "House", "records": [gutters] }));    let house = picked["group"]["id"].as_str().unwrap().to_string();    let page = call_tool(&h, &secret, "list_records", json!({ "table": "todo", "where": { "group": house } }));    assert_eq!(listed_ids(&page), vec![gutters.clone()]);    // A table the person defined, whose definition says nothing of groups.    let lesson = json!({        "id": "lesson", "name": "Lesson", "plural": "Lessons", "picture": null, "builtin": false, "engine": null,        "columns": [            { "key": "title", "type": "text", "required": true },            { "key": "level", "type": "choice", "choices": ["beginner", "advanced"] }        ],        "title": "title",        "slip": { "title": "title", "subtitle": null, "trailing": null, "photo": null, "toggle": null },        "tile": { "face": "slip-list" },        "page": [ { "heading": null, "columns": ["title"] } ],        "instructions": "A lesson is one class."    });    h.run(        "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) \         VALUES ('lesson', ?, ?, 0, '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')",        &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(lesson.to_string())],    );    let scales = made(&h, &secret, "lesson", json!({ "title": "Scales", "level": "beginner" }));    made(&h, &secret, "lesson", json!({ "title": "Fugues", "level": "advanced" }));    let picked = call_tool(&h, &secret, "create_group", json!({ "table": "lesson", "name": "Starting", "where": { "level": "beginner" } }));    assert_eq!(picked["group"]["count"], 1, "{picked}");    let found = call_tool(&h, &secret, "list_records", json!({ "table": "lesson", "where": { "group": picked["group"]["id"] } }));    assert_eq!(listed_ids(&found), vec![scales]);}/// RULE: A filter group of a list read as a day plan is that list narrowed by the filter and read by the plan: its sections count the whole group on the reader's day.#[test]fn a_todo_filter_group_reads_by_the_day_plan() {    let (h, secret) = harness();    let due = |title: &str, day: &str, priority: i64| -> String {        made(&h, &secret, "todo", json!({ "title": title, "due_at": day, "priority": priority }))    };    let tyres = due("Pump the tyres", "2026-10-05T09:00:00Z", 1);    let lamp = due("Fit the lamp", "2026-10-08T09:00:00Z", 1);    due("Oil the chain", "2026-10-06T09:00:00Z", 0);    let answer = call_tool(&h, &secret, "create_group", json!({ "table": "todo", "name": "First", "where": { "priority": 1 } }));    let first = answer["group"]["id"].as_str().unwrap().to_string();    let page = call_tool(        &h,        &secret,        "list_records",        json!({ "table": "todo", "where": { "group": first }, "today": "2026-10-05", "timezone": "UTC" }),    );    let ids: Vec<&str> = page["records"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();    assert_eq!(ids, [tyres.as_str(), lamp.as_str()], "{page}");    assert_eq!(page["sections"][0], json!({ "key": "today", "count": 1 }), "{page}");}