Cotton code
1380 lines · 59.1 KB · RustRaw
//! Data automations share the generic write transaction and its undo history.mod support;use base64::{engine::general_purpose::STANDARD, Engine};use cotton_core::definitions::{package::ToolPackage, TableDefinition, ToolDefinition};use serde_json::json;use support::{    mcp::{call_tool, call_tool_as_owner, call_tool_raw, mint_token},    Harness,};fn classroom() -> ToolPackage {    let tool: ToolDefinition =        serde_json::from_str(include_str!("fixtures/classroom/manifest.json")).unwrap();    let tables: Vec<TableDefinition> = [        include_str!("fixtures/classroom/tables/lesson.json"),        include_str!("fixtures/classroom/tables/class.json"),        include_str!("fixtures/classroom/tables/student.json"),        include_str!("fixtures/classroom/tables/grade.json"),    ]    .into_iter()    .map(|s| serde_json::from_str(s).unwrap())    .collect();    ToolPackage {        board: None, tool,        tables,        pictures: Default::default(),        samples: Default::default(),    }}fn unsigned(package: &ToolPackage) -> Vec<u8> {    cotton_core::definitions::package::encode_unsigned_package(package).unwrap()}fn replace_bytes(bytes: &mut [u8], from: &[u8], to: &[u8]) {    assert_eq!(from.len(), to.len());    let start = bytes        .windows(from.len())        .position(|w| w == from)        .expect("fixture field exists");    bytes[start..start + to.len()].copy_from_slice(to);}fn import(h: &Harness, token: &str, package: &ToolPackage) {    call_tool(        h,        token,        "import_tool",        json!({"bytes": STANDARD.encode(unsigned(package))}),    );}/// A refused import leaves a database that held no tool holding none.fn assert_no_definitions(h: &Harness, token: &str) {    let listed = call_tool(h, token, "list_tools", json!({}));    assert_eq!(listed["tools"], json!([]));    assert_eq!(listed["table_definitions"], json!([]));}// RULE: A matching create/update runs data actions as the caller, labels each change, and undo reverses the whole chain.#[test]fn automation_updates_creates_templates_notifies_and_undoes() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[            {"set":{"column":"photo","value":"photo:arrival"}},            {"create":{"table":"student","values":{"name":"$record.name"}}},            {"notify":{"text":"Welcome $record.name"}}        ]}),    ];    import(&h, &token, &p);    let first = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada","attending":false}}),    );    assert!(first["automation_changes"].as_array().unwrap().is_empty());    let changed = call_tool(        &h,        &token,        "update_record",        json!({"table":"student","id":first["record"]["id"],"patch":{"attending":true}}),    );    assert_eq!(changed["automation_changes"].as_array().unwrap().len(), 3);    assert_eq!(        changed["automation_changes"][0]["byline"],        "automation Arrival"    );    assert_eq!(changed["notifications"][0]["text"], "Welcome Ada");    assert_eq!(        call_tool(            &h,            &token,            "list_records",            json!({"table":"automation_notification"})        )["records"][0]["data"]["text"],        "Welcome Ada"    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"]            .as_array()            .unwrap()            .len(),        2    );    call_tool(        &h,        &token,        "undo",        json!({"change_id":changed["change"]["id"]}),    );    let students = call_tool(&h, &token, "list_records", json!({"table":"student"}));    assert_eq!(students["records"].as_array().unwrap().len(), 1);    assert_eq!(students["records"][0]["data"]["attending"], false);    assert!(students["records"][0]["data"]["photo"].is_null());    assert_eq!(        call_tool(            &h,            &token,            "list_records",            json!({"table":"automation_notification"})        )["records"],        json!([])    );    let created = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Bea","attending":true}}),    );    assert_eq!(created["notifications"][0]["text"], "Welcome Bea");    call_tool(        &h,        &token,        "undo",        json!({"change_id":created["change"]["id"]}),    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"]            .as_array()            .unwrap()            .len(),        1    );}// RULE: A recursive data automation stops after three action generations, so a write cannot grow forever.#[test]fn automation_chain_stops_at_three() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"copy","name":"Copy","when":{"table":"student","column":"name","to":"any"},"then":[{"create":{"table":"student","values":{"name":"$record.name"}}}]}),    ];    import(&h, &token, &p);    let created = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada"}}),    );    assert_eq!(created["automation_changes"].as_array().unwrap().len(), 3);    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"]            .as_array()            .unwrap()            .len(),        4    );    call_tool(        &h,        &token,        "undo",        json!({"change_id":created["change"]["id"]}),    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"],        json!([])    );}// RULE: Import refuses an unknown automation action with its reason before writing any definitions.#[test]fn automation_unknown_action_refuses_import() {    let mut h = Harness::bare();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"set":{"column":"attending","value":false}}]}),    ];    let mut bytes = unsigned(&p);    replace_bytes(&mut bytes, b"\"set\":", b"\"run\":");    let answer = support::mcp::call_tool_raw(        &h,        &token,        "import_tool",        json!({"bytes":STANDARD.encode(bytes)}),    );    assert!(        answer.is_error && answer.text.contains("run"),        "{}",        answer.text    );    assert_no_definitions(&h, &token);}// RULE: Undoing a grouped undo restores the trigger and every automation effect in their original order.#[test]fn automation_undo_can_itself_be_undone() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"set":{"column":"photo","value":"photo:arrival"}},{"create":{"table":"student","values":{"name":"copy"}}}]}),    ];    import(&h, &token, &p);    let created = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada","attending":true}}),    );    let undone = call_tool(        &h,        &token,        "undo",        json!({"change_id":created["change"]["id"]}),    );    let redone = call_tool(        &h,        &token,        "undo",        json!({"change_id":undone["change"]["id"]}),    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"]            .as_array()            .unwrap()            .len(),        2    );    assert_eq!(redone["record"]["data"]["photo"], "photo:arrival");    call_tool(        &h,        &token,        "undo",        json!({"change_id":redone["change"]["id"]}),    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"],        json!([])    );}// RULE: Each firing is one row of its own table (137), under the triggering change's id: what fired (tool/automation), the changes it made, when, and how it went — an undo's run says "undone", undoing that says "redone" — and none is a generic record.#[test]fn a_firing_is_kept_as_an_automation_run() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"set":{"column":"photo","value":"photo:arrival"}}]}),    ];    import(&h, &token, &p);    let created = call_tool(&h, &token, "create_record", json!({"table":"student","data":{"name":"Ada","attending":true}}));    let undone = call_tool(&h, &token, "undo", json!({"change_id":created["change"]["id"]}));    let redone = call_tool(&h, &token, "undo", json!({"change_id":undone["change"]["id"]}));    let run = |id: &serde_json::Value| {        let row = h            .db            .get(                "SELECT automation, changes, root_first, started_at, ended_at, outcome FROM cotton_automation_runs WHERE id = ?",                &[rusqlite::types::Value::Text(id.as_str().unwrap().into())],            )            .unwrap()            .unwrap_or_else(|| panic!("no run under {id}"));        let changes: serde_json::Value = serde_json::from_str(row.text("changes").unwrap()).unwrap();        assert_eq!(row.text("automation"), Some(p.tool.id.clone() + "/arrival").as_deref());        assert_eq!(changes.as_array().map(Vec::len), Some(1));        assert!(row.text("started_at").is_some() && row.text("ended_at").is_some());        (row.text("outcome").map(str::to_string), row.int("root_first"))    };    assert_eq!(run(&created["change"]["id"]), (Some("done".into()), None));    assert_eq!(run(&undone["change"]["id"]), (Some("undone".into()), Some(1)));    assert_eq!(run(&redone["change"]["id"]), (Some("redone".into()), Some(0)));}// RULE: An action failure rolls back its triggering write and all prior actions, rather than leaving half an automation.#[test]fn automation_failure_is_atomic() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tables        .iter_mut()        .find(|table| table.id == "student")        .unwrap()        .columns        .push(            serde_json::from_value(json!({"key":"nickname","name":"Nickname","type":"text"}))                .unwrap(),        );    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"create":{"table":"student","values":{"name":"copy"}}},{"create":{"table":"student","values":{"name":"$record.nickname"}}}]}),    ];    import(&h, &token, &p);    let answer = support::mcp::call_tool_raw(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada","attending":true}}),    );    assert!(answer.is_error);    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"],        json!([])    );    h.with(|db| {        assert!(db            .all(                "SELECT id FROM cotton_changes WHERE workspace_id = ?",                &[rusqlite::types::Value::Text(h.workspace_id.clone())]            )            .unwrap()            .is_empty())    });}// RULE: Import refuses notification templates that reference an undeclared source column.#[test]fn automation_notification_reference_is_validated_on_import() {    let mut h = Harness::bare();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"notify":{"text":"Hello $record.name"}}]}),    ];    let mut bytes = unsigned(&p);    replace_bytes(&mut bytes, b"$record.name", b"$record.lost");    let answer = support::mcp::call_tool_raw(        &h,        &token,        "import_tool",        json!({"bytes":STANDARD.encode(bytes)}),    );    assert!(        answer.is_error && answer.text.contains("lost"),        "{}",        answer.text    );    assert_no_definitions(&h, &token);}// RULE: Later action templates read the record after earlier set actions, so a notification describes what was actually written.#[test]fn automation_actions_read_the_updated_record_in_order() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"set":{"column":"name","value":"Bea"}},{"create":{"table":"student","values":{"name":"$record.name"}}},{"notify":{"text":"Welcome $record.name"}}]}),    ];    import(&h, &token, &p);    let written = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada","attending":true}}),    );    assert_eq!(written["record"]["data"]["name"], "Bea");    assert_eq!(written["notifications"][0]["text"], "Welcome Bea");    let students = call_tool(&h, &token, "list_records", json!({"table":"student"}));    assert!(students["records"]        .as_array()        .unwrap()        .iter()        .all(|r| r["data"]["name"] == "Bea"));}// RULE: A fan-out cascade has one budget for the whole write and refuses atomically, including the triggering record.#[test]fn automation_fanout_rolls_back_at_write_budget() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    let action = json!({"create":{"table":"student","values":{"name":"$record.name"}}});    p.tool.automations = vec![        json!({"id":"copy","name":"Copy","when":{"table":"student","column":"name","to":"any"},"then":vec![action; 5]}),    ];    import(&h, &token, &p);    let result = support::mcp::call_tool_raw(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada"}}),    );    assert!(        result.is_error && result.text.contains("budget exceeded"),        "{}",        result.text    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"],        json!([])    );    p.tool.automations[0]["then"] = json!(vec![json!({"notify":{"text":"hello"}}); 17]);    assert!(cotton_core::definitions::package::encode_unsigned_package(&p).is_err());}// RULE: An unreadable action refuses the write atomically; a valid action for a removed table does not block an unrelated write.#[test]fn unreadable_actions_refuse_but_removed_tables_do_not_block_unrelated_writes() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let p = classroom();    import(&h, &token, &p);    let mut future = p.tool.clone();    future.id = "future".into();    future.automations = vec![        json!({"id":"next","name":"Next","when":{"table":"student","column":"name","to":"any"},"then":[{"future":{"key":true}}]}),    ];    let mut stale = p.tool.clone();    stale.id = "stale".into();    stale.tables = vec!["missing_table".into()];    stale.automations = vec![        json!({"id":"next","name":"Next","when":{"table":"missing_table","column":"name","to":"any"},"then":[{"notify":{"text":"Hello"}}]}),    ];    for tool in [future, stale] {        h.run("INSERT INTO cotton_tool_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, 'now', 'now')", &[rusqlite::types::Value::Text(tool.id.clone()), rusqlite::types::Value::Text(h.workspace_id.clone()), rusqlite::types::Value::Text(serde_json::to_string(&tool).unwrap())]);    }    let refused = call_tool_raw(&h, &token, "create_record", json!({"table":"student","data":{"name":"Ada"}}));    assert!(refused.is_error && refused.text.contains("future"), "{}", refused.text);    assert_eq!(h.db.get("SELECT count(*) AS n FROM cotton_student", &[]).unwrap().unwrap().int("n"), Some(0), "the refused write is atomic");    h.run("DELETE FROM cotton_tool_definitions WHERE id = 'future'", &[]);    let created = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada"}}),    );    call_tool(        &h,        &token,        "update_record",        json!({"table":"student","id":created["record"]["id"],"patch":{"name":"Bea"}}),    );}// RULE: Undoing an individual effect leaves the parent change undoable; already-undone members are skipped.#[test]fn grouped_undo_skips_an_effect_already_undone() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"name","to":"any"},"then":[{"notify":{"text":"Hello"}}]}),    ];    import(&h, &token, &p);    let created = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada"}}),    );    call_tool(        &h,        &token,        "undo",        json!({"change_id":created["automation_changes"][0]["id"]}),    );    call_tool(        &h,        &token,        "undo",        json!({"change_id":created["change"]["id"]}),    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"],        json!([])    );}// RULE: Import refuses create references whose source and target column types differ, before any automation can run.#[test]fn automation_import_checks_reference_column_types() {    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"create":{"table":"student","values":{"name":"$record.photo"}}}]}),    ];    assert!(        cotton_core::definitions::package::encode_unsigned_package(&p)            .unwrap_err()            .to_string()            .contains("different type")    );    p.tool.automations = (0..17).map(|i| json!({"id":format!("arrival_{i}"),"name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[{"notify":{"text":"Hello"}}]})).collect();    assert!(        cotton_core::definitions::package::encode_unsigned_package(&p)            .unwrap_err()            .to_string()            .contains("too many automations")    );}// RULE: Group undo follows an effect's undo chain, so undoing an undo makes that effect live and reversible with its trigger again.#[test]fn grouped_undo_reverses_an_effect_restored_by_undoing_its_undo() {    for reversals in [2, 4, 6] {        let mut h = Harness::new();        let token = mint_token(&mut h, &["read", "write"], "Teacher");        let mut p = classroom();        p.tool.automations = vec![            json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"name","to":"any"},"then":[{"notify":{"text":"Hello"}}]}),        ];        import(&h, &token, &p);        let created = call_tool(            &h,            &token,            "create_record",            json!({"table":"student","data":{"name":"Ada"}}),        );        let mut effect = created["automation_changes"][0]["id"].clone();        for _ in 0..reversals {            let undone = call_tool(&h, &token, "undo", json!({"change_id":effect}));            effect = undone["change"]["id"].clone();        }        assert_eq!(            call_tool(                &h,                &token,                "list_records",                json!({"table":"automation_notification"})            )["records"]                .as_array()                .unwrap()                .len(),            1        );        let undone = call_tool(            &h,            &token,            "undo",            json!({"change_id":created["change"]["id"]}),        );        assert_eq!(undone["automation_undos"].as_array().unwrap().len(), 1);        assert_eq!(undone["automation_undos"][0]["undone"]["id"], effect);        for table in ["student", "automation_notification"] {            assert_eq!(                call_tool(&h, &token, "list_records", json!({"table":table}))["records"],                json!([])            );        }        // The inverse group restores exactly the currently live effect we reversed.        call_tool(            &h,            &token,            "undo",            json!({"change_id":undone["change"]["id"]}),        );        for table in ["student", "automation_notification"] {            assert_eq!(                call_tool(&h, &token, "list_records", json!({"table":table}))["records"]                    .as_array()                    .unwrap()                    .len(),                1            );        }    }}// RULE: Emptying the Bin after undoing an automation effect cannot strand its trigger; group undo skips the erased history and states why.#[test]fn grouped_undo_reports_an_effect_erased_by_emptying_the_bin() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"name","to":"any"},"then":[{"notify":{"text":"Hello"}}]}),    ];    import(&h, &token, &p);    let created = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Ada"}}),    );    let effect = created["automation_changes"][0]["id"].clone();    call_tool(&h, &token, "undo", json!({"change_id":effect}));    call_tool_as_owner(&h, "device:phone", "empty_bin", json!({})).json();    assert!(h        .all(            "SELECT id FROM cotton_changes WHERE id = ?",            &[rusqlite::types::Value::Text(                effect.as_str().unwrap().into()            )]        )        .is_empty());    let undone = call_tool(        &h,        &token,        "undo",        json!({"change_id":created["change"]["id"]}),    );    assert_eq!(undone["automation_undos"], json!([]));    assert_eq!(undone["automation_undo_skipped"][0]["change_id"], effect);    assert!(undone["automation_undo_skipped"][0]["reason"]        .as_str()        .unwrap()        .contains("permanently erased"));    for table in ["student", "automation_notification"] {        assert_eq!(            call_tool(&h, &token, "list_records", json!({"table":table}))["records"],            json!([])        );    }    // Restoring the trigger does not resurrect a permanently erased notification.    call_tool(        &h,        &token,        "undo",        json!({"change_id":undone["change"]["id"]}),    );    assert_eq!(        call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"]            .as_array()            .unwrap()            .len(),        1    );    assert_eq!(        call_tool(            &h,            &token,            "list_records",            json!({"table":"automation_notification"})        )["records"],        json!([])    );}/// The offline import's own id source: one run id, nothing random.struct OneRun;impl cotton_store::mint::IdSource for OneRun {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        Ok("run-import-1".to_string())    }}/// A write as the carry's offline import makes it: `Actor::Import`, on a file/// held offline (the only holding that may name that actor).fn create_as_import(h: &Harness, args: serde_json::Value) -> serde_json::Value {    use cotton_tools::clock::Clock;    let run = cotton_store::actor::RunId::minted(&mut OneRun, 0).expect("a run id");    let mut ctx = cotton_tools::mcp::dispatch::Ctx::phone(        &h.db,        &h.file,        &h.owner_id,        "device:import",        cotton_store::actor::Actor::Import(run),        cotton_store::mint::Held::Offline,        h.clock.now(),        std::sync::Arc::clone(&h.random),        &h.services.services,    );    let args = args.as_object().cloned().expect("an object");    cotton_tools::mcp::dispatch::call_tool(&mut ctx, "create_record", &args).expect("the import writes")}// RULE: An import carries records whose automations already ran where they were made, so a write by Actor::Import sets off no automation — while the same write by a token does.#[test]fn automations_do_not_fire_for_an_import_write() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.automations = vec![        json!({"id":"arrival","name":"Arrival","when":{"table":"student","column":"attending","to":true},"then":[            {"create":{"table":"student","values":{"name":"$record.name"}}},            {"notify":{"text":"Welcome $record.name"}}        ]}),    ];    import(&h, &token, &p);    let students = |h: &Harness| {        call_tool(h, &token, "list_records", json!({"table":"student"}))["records"]            .as_array()            .expect("a list")            .len()    };    let imported = create_as_import(&h, json!({"table":"student","data":{"name":"Ada","attending":true}}));    assert!(imported.get("notifications").is_none(), "{imported}");    assert_eq!(students(&h), 1, "the import's write made no second student");    let written = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Bea","attending":true}}),    );    assert_eq!(written["notifications"][0]["text"], "Welcome Bea");    assert_eq!(students(&h), 3, "a token's write fires the automation");}// RULE: A row guard decides whether the rule fires; a guarded Set computes from the current row in the same write transaction.#[test]fn guarded_arithmetic_runs_only_when_true() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.engines = vec!["rules@1".into()];    let student = p.tables.iter_mut().find(|t| t.id == "student").unwrap();    student        .columns        .push(serde_json::from_value(json!({"key":"score","type":"number"})).unwrap());    student        .columns        .push(serde_json::from_value(json!({"key":"total","type":"number"})).unwrap());    student.columns.push(serde_json::from_value(json!({"key":"factor","type":"number","computed":{"formula":{"op":"sum","of":["score","score"]}}})).unwrap());    p.tool.automations = vec![        json!({"id":"score","name":"Score","when":{"table":"student","column":"attending","to":true,        "guard":{">": [{"column":"factor"},4]}},"then":[{"set":{"column":"total","value":{"*": [{"column":"factor"},5]}}}]}),    ];    import(&h, &token, &p);    let columns = &p.tables.iter().find(|t| t.id == "student").unwrap().columns;    let mut counter_columns = serde_json::to_value(columns).unwrap();    counter_columns        .as_array_mut()        .unwrap()        .iter_mut()        .find(|c| c["key"] == "total")        .unwrap()["counter"] = json!(true);    assert!(        call_tool_raw(            &h,            &token,            "update_definition",            json!({"table":"student","columns":counter_columns})        )        .is_error    );    let missing_columns: Vec<_> = columns.iter().filter(|c| c.key != "score").collect();    assert!(        call_tool_raw(            &h,            &token,            "update_definition",            json!({"table":"student","columns":missing_columns})        )        .is_error    );    let no = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Synthetic One","attending":true,"score":1}}),    );    assert!(no["automation_changes"].as_array().unwrap().is_empty());    let yes = call_tool(        &h,        &token,        "create_record",        json!({"table":"student","data":{"name":"Synthetic Two","attending":true,"score":3}}),    );    assert_eq!(yes["record"]["data"]["total"], json!(30));}fn reservation_package() -> ToolPackage {    let mut p = classroom();    p.tool.engines = vec!["reserve@1".into()];    p.tool.reserve=Some(serde_json::from_value(json!({"slot_table":"class","capacity_column":"size","claim_table":"student","slot_column":"class"})).unwrap());    p}fn seed_serving(h: &Harness) {    use rusqlite::types::Value as S;    h.db.run("INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since,_hlc) VALUES ('synthetic-server',?,1,'synthetic-device',?,'2026-09-01T00:00:00Z','')",        &[S::Text(h.workspace_id.clone()),S::Text(h.file_author())]).unwrap();}// RULE: Capacity is consumed by server-owned claim rows; cancel releases one, and generic writes, undo and a client's later receipt cannot restore or overwrite a claim.#[test]fn reservation_claim_cancel_and_offline_edit_fence() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    import(&h, &token, &reservation_package());    let slot = call_tool(        &h,        &token,        "create_record",        json!({"table":"class","data":{"name":"Synthetic capacity","size":1}}),    )["record"]["id"]        .clone();    seed_serving(&h);    assert!(        call_tool_as_owner(            &h,            "synthetic-phone",            "reserve_record",            json!({"tool":"classroom","slot":slot,"data":{"name":"Offline"}})        )        .is_error    );    let args = json!({"tool":"classroom","slot":slot,"data":{"name":"Synthetic Claim"}});    let one = call_tool(&h, &token, "reserve_record", args.clone());    assert_eq!(one["ok"], true);    assert_eq!(one["remaining"], 0);    let full = call_tool(&h, &token, "reserve_record", args.clone());    assert_eq!(full, json!({"ok":false,"reason":"full","remaining":0}));    let id = one["record"]["id"].as_str().unwrap();    assert!(        call_tool_raw(            &h,            &token,            "update_record",            json!({"table":"student","id":id,"patch":{"name":"Forged"}})        )        .is_error    );    assert!(        call_tool_raw(            &h,            &token,            "create_record",            json!({"table":"student","data":{"name":"Bypass","class":slot}})        )        .is_error    );    // A first-copy pull can precede its serving fact; the authenticated server already judged that receipt.    h.db.run("DELETE FROM cotton_serving_machine", &[]).unwrap();    let author = h.file_author();    let pulled_actor = cotton_store::actor::Actor::device_job(        cotton_store::actor::JobName::named("synthetic").unwrap(),    );    use cotton_tools::clock::Clock;    let pull_stamp = format!("{}:0001:{author}", h.clock.now().timestamp_millis() + 1);    let pulled = cotton_store::wire::op_of_change(        &h.db,        &cotton_store::mint::Change::update(            "cotton_student",            id,            json!({"name":"Server confirmed"})                .as_object()                .unwrap()                .clone(),        ),        &pull_stamp,        &author,        &pulled_actor,        "synthetic-server-pull".into(),    )    .unwrap();    let accepted = cotton_store::fold::fold_pulled(&h.db, &[pulled]).unwrap();    assert!(        accepted            .applied            .contains(&"synthetic-server-pull".to_string()),        "{accepted:?}"    );    seed_serving(&h);    let change = cotton_store::mint::Change::update(        "cotton_student",        id,        json!({"name":"Offline forged"})            .as_object()            .unwrap()            .clone(),    );    let peer = "device:synthetic-offline";    let stamp = format!("9999999999999:0000:{peer}");    let fact = cotton_tools::test_fixtures::author_fact(&h.workspace_id, peer, &stamp);    let actor = cotton_store::actor::Actor::device_job(        cotton_store::actor::JobName::named("synthetic").unwrap(),    );    let op = cotton_store::wire::op_of_change(        &h.db,        &change,        &stamp,        peer,        &actor,        "offline-edit".into(),    )    .unwrap();    let retract = cotton_store::wire::op_of_change(        &h.db,        &cotton_store::mint::Change::retract("cotton_student", id),        &format!("9999999999999:0001:{peer}"),        peer,        &actor,        "offline-retract".into(),    )    .unwrap();    let result = cotton_store::fold::fold_ops(&h.db, &[fact, op, retract]).unwrap();    assert!(        result            .rejected            .iter()            .any(|r| r.op_id == "offline-retract" && r.reason.contains("server action")),        "{result:?}"    );    assert!(        result            .rejected            .iter()            .any(|r| r.reason.contains("server action")),        "{result:?}"    );    assert_eq!(        call_tool(            &h,            &token,            "cancel_reservation",            json!({"tool":"classroom","id":id})        )["remaining"],        1    );    assert_eq!(call_tool(&h, &token, "reserve_record", args)["ok"], true);}// RULE: Two connections racing for one place serialize the capacity read and claim insert; exactly one succeeds.#[test]fn two_concurrent_claims_for_capacity_one() {    use cotton_tools::clock::Clock;    use cotton_tools::mcp::dispatch::{call_tool as dispatch, Ctx};    use std::sync::{Arc, Barrier};    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    import(&h, &token, &reservation_package());    let slot = call_tool(        &h,        &token,        "create_record",        json!({"table":"class","data":{"name":"Synthetic concurrent slot","size":1}}),    )["record"]["id"]        .clone();    seed_serving(&h);    support::harness::reconcile_all(&h.db);    let tmp = tempfile::tempdir().unwrap();    let path = tmp.path().join("synthetic.sqlite");    h.db.run(        "VACUUM INTO ?",        &[rusqlite::types::Value::Text(path.to_str().unwrap().into())],    )    .unwrap();    // A `VACUUM INTO` copy is born in rollback-journal mode; the first open    // turns it to WAL, and two first opens at once deadlock on that switch,    // which SQLite breaks with an immediate "database is locked" whatever the    // busy timeout. Opened once here, the race below is the claim's alone.    drop(cotton_store::Driver::open(&path).unwrap());    let gate = Arc::new(Barrier::new(2));    let connection = h.connection(&token);    let jobs:Vec<_>=(0..2).map(|i| {        let path=path.clone();let slot=slot.clone();let gate=gate.clone();let connection=connection.clone();let owner=h.owner_id.clone();        std::thread::spawn(move||{            let db=cotton_store::Driver::open(path).unwrap();            let file=cotton_store::file_identity::read_file_identity(&db).unwrap().unwrap();            let services=support::fakes::FakeServices::new();let clock=cotton_tools::clock::FixedClock::default_start();            let actor=cotton_store::actor::Actor::Token(cotton_store::actor::TokenId::in_file(&db,&connection.id).unwrap());            let audit=|_:&str,_:&str|{};            let mut ctx=Ctx::new(&db,&file,&owner,&connection.name,&connection.id,&connection.scopes,clock.now(),Arc::new(cotton_tools::random::SystemRandom),Some(actor),&services.services,&audit);            gate.wait();            dispatch(&mut ctx,"reserve_record",json!({"tool":"classroom","slot":slot,"data":{"name":format!("Synthetic {i}")}}).as_object().unwrap()).unwrap()        })    }).collect();    let answers: Vec<_> = jobs.into_iter().map(|j| j.join().unwrap()).collect();    assert_eq!(        answers.iter().filter(|a| a["ok"] == true).count(),        1,        "{answers:?}"    );    assert_eq!(        answers.iter().filter(|a| a["reason"] == "full").count(),        1,        "{answers:?}"    );}// RULE: A capacity rollup is read from the transaction's current movement rows, including writes made after an older computed index.#[test]fn reservation_capacity_can_be_a_live_rollup() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = reservation_package();    let mut movements = p.tables.iter().find(|t| t.id == "student").unwrap().clone();    movements.id = "capacity_movement".into();    movements.name = "Capacity movement".into();    movements.plural = "Capacity movements".into();    movements        .columns        .push(serde_json::from_value(json!({"key":"units","type":"number"})).unwrap());    let class = p.tables.iter_mut().find(|t| t.id == "class").unwrap();    class.columns.iter_mut().find(|c|c.key=="size").unwrap().computed=Some(serde_json::from_value(json!({"rollup":{"table":"capacity_movement","link":"class","op":"sum","column":"units"}})).unwrap());    p.tool.tables.push(movements.id.clone());    p.tables.push(movements);    import(&h, &token, &p);    let slot = call_tool(        &h,        &token,        "create_record",        json!({"table":"class","data":{"name":"Synthetic rollup slot"}}),    )["record"]["id"]        .clone();    seed_serving(&h);    let args = json!({"tool":"classroom","slot":slot,"data":{"name":"Synthetic Claim"}});    assert_eq!(        call_tool(&h, &token, "reserve_record", args.clone())["reason"],        "full"    );    for _ in 0..2 {        call_tool(            &h,            &token,            "create_record",            json!({"table":"capacity_movement","data":{"name":"Synthetic delivery","class":slot,"units":1}}),        );        assert_eq!(            call_tool(&h, &token, "reserve_record", args.clone())["ok"],            true        );    }    assert_eq!(        call_tool(&h, &token, "reserve_record", args)["reason"],        "full"    );}// RULE: Every package save validates capabilities and rule columns, including in-process kit installs that do not pass through the archive decoder.#[test]fn direct_package_install_validates_capabilities_and_rule_columns() {    use cotton_tools::clock::Clock;    use cotton_tools::mcp::dispatch::Ctx;    let mut h = Harness::bare();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let connection = h.connection(&token);    let audit = |_: &str, _: &str| {};    let actor = cotton_store::actor::Actor::Token(        cotton_store::actor::TokenId::in_file(&h.db, &connection.id).unwrap(),    );    let mut ctx = Ctx::new(        &h.db,        &h.file,        &h.owner_id,        &connection.name,        &connection.id,        &connection.scopes,        h.clock.now(),        h.random.clone(),        Some(actor),        &h.services.services,        &audit,    );    let mut p = classroom();    p.tool.engines = vec!["missing@1".into()];    assert!(cotton_tools::mcp::handlers::tool_packages::install_package(        &mut ctx,        &p,        cotton_tools::mcp::handlers::tool_packages::Door::Import,        false    )    .is_err());    p.tool.engines = vec!["rules@1".into()];    p.tool.automations = vec![        json!({"id":"bad","name":"Bad","when":{"table":"student","column":"attending","to":true,"guard":{"column":"missing"}},"then":[{"notify":{"text":"Synthetic"}}]}),    ];    assert!(cotton_tools::mcp::handlers::tool_packages::install_package(        &mut ctx,        &p,        cotton_tools::mcp::handlers::tool_packages::Door::Import,        false    )    .is_err());    drop(ctx);    assert_no_definitions(&h, &token);}// RULE: Set expressions store text and clock dates through the same typed write and undo path as numeric rules.#[test]fn rules_set_clock_and_text_values_and_undo() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.engines = vec!["rules@1".into()];    let student = p.tables.iter_mut().find(|t| t.id == "student").unwrap();    for (key, kind) in [("marked_at", "date"), ("marked_on", "date"), ("copy", "text")] {        student.columns.push(serde_json::from_value(json!({"key":key,"type":kind})).unwrap());    }    student.columns.iter_mut().find(|c| c.key == "marked_at").unwrap().format = Some(cotton_core::definitions::ColumnFormat::CalendarDatetime);    p.tool.automations = vec![json!({"id":"mark","name":"Mark","when":{"table":"student","column":"attending","to":true},"then":[        {"set":{"column":"marked_at","value":{"now":true}}},        {"set":{"column":"marked_on","value":{"today":true}}},        {"set":{"column":"copy","value":{"column":"name"}}}    ]})];    import(&h, &token, &p);    let created = call_tool(&h, &token, "create_record", json!({"table":"student","data":{"name":"Synthetic","attending":false}}));    let changed = call_tool(&h, &token, "update_record", json!({"table":"student","id":created["record"]["id"],"patch":{"attending":true}}));    let data = &changed["record"]["data"];    assert_eq!(data["copy"], "Synthetic");    assert!(chrono::DateTime::parse_from_rfc3339(data["marked_at"].as_str().unwrap()).is_ok());    assert!(chrono::NaiveDate::parse_from_str(data["marked_on"].as_str().unwrap(), "%Y-%m-%d").is_ok());    call_tool(&h, &token, "undo", json!({"change_id":changed["change"]["id"]}));    let read = call_tool(&h, &token, "get_record_by_table", json!({"table":"student","id":created["record"]["id"]}));    assert!(read["data"]["marked_at"].is_null());}// RULE: Claims consume their positive whole quantity, defaulting to one; a refused group cannot oversell, and cancel releases its whole quantity once.#[test]fn reservation_quantities_sum_default_and_cancel() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = reservation_package();    p.tool.reserve.as_mut().unwrap().quantity_column = Some("places".into());    p.tables.iter_mut().find(|t| t.id == "student").unwrap().columns.push(        serde_json::from_value(json!({"key":"places","type":"number"})).unwrap());    import(&h, &token, &p);    let slot = call_tool(&h, &token, "create_record", json!({"table":"class","data":{"name":"Synthetic","size":5}}))["record"]["id"].clone();    seed_serving(&h);    for quantity in [json!(0), json!(-1), json!(1.5), json!(null), json!("2")] {        assert!(call_tool_raw(&h, &token, "reserve_record", json!({"tool":"classroom","slot":slot,"data":{"name":"Invalid","places":quantity}})).is_error);    }    let group = call_tool(&h, &token, "reserve_record", json!({"tool":"classroom","slot":slot,"data":{"name":"Group","places":3}}));    assert_eq!(group["remaining"], 2);    let full = call_tool(&h, &token, "reserve_record", json!({"tool":"classroom","slot":slot,"data":{"name":"Too many","places":3}}));    assert_eq!(full["ok"], false);    assert_eq!(full["remaining"], 2);    let single = call_tool(&h, &token, "reserve_record", json!({"tool":"classroom","slot":slot,"data":{"name":"Single"}}));    assert_eq!(single["remaining"], 1);    assert_eq!(single["record"]["data"]["places"], 1);    for _ in 0..2 {        let cancel = call_tool(&h, &token, "cancel_reservation", json!({"tool":"classroom","id":group["record"]["id"]}));        assert_eq!(cancel["remaining"], 4);    }}// RULE: Package acts execute only their installed shared verbs; their conditions and claim binding prevent arbitrary writes or moving/resizing a reservation.#[test]fn package_acts_reserve_set_cancel_and_refuse_other_verbs() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = reservation_package();    p.tool.engines.push("rules@1".into());    p.tables.iter_mut().find(|t| t.id == "student").unwrap().columns.push(serde_json::from_value(json!({"key":"lesson","type":"link","link_to":"lesson"})).unwrap());    p.tables.iter_mut().find(|t| t.id == "class").unwrap().acts = Some(vec![serde_json::from_value(json!({        "id":"book","label":"Book","kind":"create","verb":"reserve_record","data":{"data":{"name":"Synthetic Claim"}}    })).unwrap()]);    p.tables.iter_mut().find(|t| t.id == "student").unwrap().acts = Some(vec![        serde_json::from_value(json!({"id":"attend","label":"Attend","kind":"update","verb":"set","data":{"column":"attending","value":true},"when":{"attending":false}})).unwrap(),        serde_json::from_value(json!({"id":"cancel","label":"Cancel","kind":"delete","verb":"cancel_reservation","confirm":"Cancel this reservation?"})).unwrap()    ]);    p.tables.iter_mut().find(|t| t.id == "student").unwrap().delete = Some(false);    p.tables.iter_mut().find(|t| t.id == "class").unwrap().acts.as_mut().unwrap().push(serde_json::from_value(json!({        "id":"book_lesson","label":"Book lesson","kind":"create","verb":"reserve_record","data":{"data":{"name":"Picked lesson"}},        "pick":{"kind":"record","table":"lesson","argument":"data.lesson","where":{"subject":"mathematics"}}    })).unwrap());    import(&h, &token, &p);    let slot = call_tool(&h, &token, "create_record", json!({"table":"class","data":{"name":"Synthetic","size":1}}))["record"]["id"].clone();    seed_serving(&h);    let booked = call_tool(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book"}));    assert_eq!(booked["ok"], true);    let claim = booked["record"]["id"].clone();    let attended = call_tool(&h, &token, "run_record_act", json!({"table":"student","id":claim,"act":"attend"}));    assert_eq!(attended["record"]["data"]["attending"], true);    assert!(call_tool_raw(&h, &token, "run_record_act", json!({"table":"student","id":claim,"act":"attend"})).is_error);    assert!(call_tool_raw(&h, &token, "run_record_act", json!({"table":"student","id":claim,"act":"delete_person"})).is_error);    let cancelled = call_tool(&h, &token, "run_record_act", json!({"table":"student","id":claim,"act":"cancel"}));    assert_eq!(cancelled["remaining"], 1);    for (subject, allowed) in [("science", false), ("mathematics", true)] {        let lesson = call_tool(&h, &token, "create_record", json!({"table":"lesson","data":{"title":"Synthetic lesson","subject":subject}}))["record"]["id"].clone();        let answer = call_tool_raw(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book_lesson","picked":lesson}));        if allowed { assert_eq!(answer.json()["record"]["data"]["lesson"], lesson); }        else { assert!(answer.is_error); }    }    let student = p.tables.iter_mut().find(|t| t.id == "student").unwrap();    student.acts.as_mut().unwrap()[0].data = Some(serde_json::from_value(json!({"column":"class","value":{"column":"class"}})).unwrap());    assert!(cotton_core::definitions::acts::validate_tables(&p.tool, &p.tables).is_err());}// RULE: A rule reads the triggering row's id and typed columns, and Create preserves link targets so attendance stays attached to its booking and member.#[test]fn rules_create_links_from_triggering_record() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.engines = vec!["rules@1".into()];    let lesson = p.tables.iter_mut().find(|t| t.id == "lesson").unwrap();    lesson.columns.push(serde_json::from_value(json!({"key":"student","type":"link","link_to":"student"})).unwrap());    p.tool.automations = vec![json!({"id":"attendance","name":"Attendance","when":{"table":"student","column":"attending","to":true,"guard":{"!=":["$record.id",null]}},"then":[        {"create":{"table":"lesson","values":{"title":"$record.name","student":"$record.id","class":"$record.class"}}}    ]})];    import(&h, &token, &p);    let class = call_tool(&h, &token, "create_record", json!({"table":"class","data":{"name":"Synthetic"}}))["record"]["id"].clone();    let student = call_tool(&h, &token, "create_record", json!({"table":"student","data":{"name":"Synthetic member","class":class,"attending":false}}))["record"]["id"].clone();    let changed = call_tool(&h, &token, "update_record", json!({"table":"student","id":student,"patch":{"attending":true}}));    let lessons = call_tool(&h, &token, "list_records", json!({"table":"lesson"}));    assert_eq!(lessons["records"][0]["data"]["student"], student);    assert_eq!(lessons["records"][0]["data"]["class"], class);    assert_eq!(lessons["records"][0]["data"]["title"], "Synthetic member");    call_tool(&h, &token, "undo", json!({"change_id":changed["change"]["id"]}));    assert!(call_tool(&h, &token, "list_records", json!({"table":"lesson"}))["records"].as_array().unwrap().is_empty());    p.tool.automations[0]["then"][0]["create"]["values"]["class"] = json!("$record.id");    assert!(cotton_core::definitions::automations::validate_tables(&p.tool, &p.tables).is_err());}// RULE: A create act uses only its package's ordinary tables, bound row values and validated picks, then records its automation effects in the same undo group.#[test]fn package_create_act_binds_picks_and_undoes() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = classroom();    p.tool.engines = vec!["rules@1".into()];    p.tables.iter_mut().find(|t| t.id == "lesson").unwrap().columns.push(        serde_json::from_value(json!({"key":"student","type":"link","link_to":"student"})).unwrap());    p.tables.iter_mut().find(|t| t.id == "student").unwrap().acts = Some(vec![serde_json::from_value(json!({        "id":"renew","label":"Renew","kind":"create","verb":"create",        "data":{"table":"lesson","data":{"title":"Synthetic renewal","subject":"art"}},        "bindings":{"data.student":"$id"},        "pick":{"kind":"record","table":"class","argument":"data.class","where":{"year":"year 4"}}    })).unwrap()]);    assert!(p.tables.iter().find(|t| t.id == "student").unwrap().resolved_parts().acts.more.contains(&"renew".into()));    p.tool.automations = vec![json!({"id":"renewed","name":"Renewed","when":{"table":"lesson","column":"subject","to":"art"},"then":[{"notify":{"text":"Renewed"}}]})];    import(&h, &token, &p);    let student = call_tool(&h, &token, "create_record", json!({"table":"student","data":{"name":"Synthetic member"}}))["record"]["id"].clone();    assert!(call_tool_raw(&h, &token, "run_record_act", json!({"table":"student","id":student,"act":"renew"})).is_error);    for (year, allowed) in [("year 5", false), ("year 4", true)] {        let class = call_tool(&h, &token, "create_record", json!({"table":"class","data":{"name":"Synthetic class","year":year}}))["record"]["id"].clone();        let answer = call_tool_raw(&h, &token, "run_record_act", json!({"table":"student","id":student,"act":"renew","picked":class}));        if allowed {            let answer = answer.json();            assert_eq!(answer["record"]["data"]["student"], student);            assert_eq!(answer["record"]["data"]["class"], class);            assert_eq!(answer["notifications"][0]["text"], "Renewed");            call_tool(&h, &token, "undo", json!({"change_id":answer["change"]["id"]}));        } else { assert!(answer.is_error); }    }    assert!(call_tool(&h, &token, "list_records", json!({"table":"lesson"}))["records"].as_array().unwrap().is_empty());    let act = &mut p.tables.iter_mut().find(|t| t.id == "student").unwrap().acts.as_mut().unwrap()[0];    act.data.as_mut().unwrap().0.iter_mut().find(|(key, _)| key == "table").unwrap().1 = json!("person");    assert!(cotton_core::definitions::acts::validate_tables(&p.tool, &p.tables).is_err());}// RULE: Number picks are checked by the writer for both reservations and creates; defaults are numbers and rejected quantities never consume capacity or create a row.#[test]fn package_number_picks_reserve_and_create() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = reservation_package();    p.tool.engines.push("rules@1".into());    p.tool.reserve.as_mut().unwrap().quantity_column = Some("places".into());    p.tables.iter_mut().find(|t| t.id == "student").unwrap().columns.push(serde_json::from_value(json!({"key":"places","type":"number"})).unwrap());    p.tables.iter_mut().find(|t| t.id == "class").unwrap().acts = Some(vec![        serde_json::from_value(json!({"id":"book","label":"Book","kind":"create","verb":"reserve_record","data":{"data":{"name":"Synthetic group"}},"pick":{"kind":"number","argument":"data.places","min":1,"default":2,"max":4}})).unwrap(),        serde_json::from_value(json!({"id":"payment","label":"Take cash","kind":"create","verb":"create","data":{"table":"lesson","data":{"title":"Synthetic payment"}},"pick":{"kind":"number","argument":"data.amount","min":1,"default":10,"max":100}})).unwrap()    ]);    p.tables.iter_mut().find(|t| t.id == "lesson").unwrap().columns.push(serde_json::from_value(json!({"key":"amount","type":"number"})).unwrap());    import(&h, &token, &p);    let slot = call_tool(&h, &token, "create_record", json!({"table":"class","data":{"name":"Synthetic","size":5}}))["record"]["id"].clone();    seed_serving(&h);    for value in [json!(0), json!(5), json!("2"), json!(1.5), json!(null)] {        assert!(call_tool_raw(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book","picked":value})).is_error);    }    let booked = call_tool(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book"}));    assert_eq!(booked["record"]["data"]["places"], 2);    assert_eq!(booked["remaining"], 3);    let full = call_tool(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book","picked":4}));    assert_eq!(full["ok"], false);    assert_eq!(full["remaining"], 3);    assert!(call_tool_raw(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"payment","picked":101})).is_error);    let payment = call_tool(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"payment","picked":25.5}));    assert_eq!(payment["record"]["data"]["amount"], 25.5);    assert_eq!(call_tool(&h, &token, "list_records", json!({"table":"lesson"}))["records"].as_array().unwrap().len(), 1);}// RULE: Ordered picks bind together before one write; an invalid later pick leaves no partial reservation or created row.#[test]fn package_ordered_picks_run_once_with_all_values() {    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Teacher");    let mut p = reservation_package();    p.tool.engines.push("rules@1".into());    p.tool.reserve.as_mut().unwrap().quantity_column = Some("places".into());    p.tables.iter_mut().find(|t| t.id == "student").unwrap().columns.push(serde_json::from_value(json!({"key":"places","type":"number"})).unwrap());    p.tables.iter_mut().find(|t| t.id == "class").unwrap().acts = Some(vec![serde_json::from_value(json!({        "id":"book", "label":"Book", "kind":"create", "verb":"reserve_record",        "picks":[{"kind":"text","argument":"data.name","label":"Name"},                 {"kind":"number","argument":"data.places","label":"Places","min":1,"default":2,"max":4}]    })).unwrap()]);    import(&h, &token, &p);    let slot = call_tool(&h, &token, "create_record", json!({"table":"class","data":{"name":"Synthetic","size":5}}))["record"]["id"].clone();    seed_serving(&h);    for picked in [json!(["Synthetic",0]), json!(["Synthetic"]), json!(["Synthetic",2,3]), json!("Synthetic"), json!(["Synthetic","2"])] {        assert!(call_tool_raw(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book","picked":picked})).is_error);    }    assert!(call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"].as_array().unwrap().is_empty());    let booked = call_tool(&h, &token, "run_record_act", json!({"table":"class","id":slot,"act":"book","picked":["Synthetic group",3]}));    assert_eq!(booked["record"]["data"]["name"], "Synthetic group");    assert_eq!(booked["record"]["data"]["places"], 3);    assert_eq!(booked["remaining"], 2);    assert_eq!(call_tool(&h, &token, "list_records", json!({"table":"student"}))["records"].as_array().unwrap().len(), 1);}// RULE: Trusted imported claims keep source identity and use the same capacity check; importing never opens the generic claim-table write fence.#[test]fn imported_reservations_keep_capacity_and_the_generic_write_fence() {    use cotton_tools::mcp::{        dispatch::{Ctx, ToolServices},        handlers::tables,    };    let mut h = Harness::new();    let token = mint_token(&mut h, &["read", "write"], "Synthetic importer");    let mut package = reservation_package();    package.tables.iter_mut().find(|t|t.id=="student").unwrap().columns.push(serde_json::from_value(json!({"key":"import_id","name":"Import id","type":"text","readonly":true,"indexed":true})).unwrap());    // Imported claim automations run after the claim-write scope closes;    // otherwise an automation could mint another claim without capacity.    package.tool.automations.push(json!({"id":"claim_bypass","name":"Synthetic bad rule","when":{"table":"student","column":"name","to":"Attempt bypass"},"then":[{"create":{"table":"student","values":{"name":"Forged","class":"$record.class"}}}]}));    import(&h, &token, &package);    seed_serving(&h);    let slot = call_tool(        &h,        &token,        "create_record",        json!({"table":"class","data":{"name":"Synthetic","size":1}}),    )["record"]["id"]        .clone();    let services = ToolServices::none();    let audit = |_: &str, _: &str| {};    let file = cotton_store::file_identity::read_file_identity(&h.db)        .unwrap()        .unwrap();    let mut ctx = Ctx::for_worker(        &h.db,        &file,        &h.owner_id,        cotton_tools::mcp::writer::job("synthetic-import"),        "Synthetic import",        chrono::Utc::now(),        std::sync::Arc::new(cotton_tools::random::SystemRandom),        &services,        &audit,    );    assert!(        call_tool_raw(            &h,            &token,            "reserve_imported_record",            json!({"tool":"classroom","slot":slot,"data":{"name":"Bypass","import_id":"seed:0"}})        )        .is_error    );    let input =        json!({"tool":"classroom","slot":slot,"data":{"name":"Synthetic","import_id":"seed:1"}});    let mut attack = input.clone();    attack["data"]["name"] = "Attempt bypass".into();    attack["data"]["import_id"] = "seed:attack".into();    assert!(tables::reserve_imported_record(&mut ctx, attack.as_object().unwrap()).is_err());    assert_eq!(        h.db.get("SELECT count(*) n FROM cotton_student", &[])            .unwrap()            .unwrap()            .int("n"),        Some(0)    );    let first = tables::reserve_imported_record(&mut ctx, input.as_object().unwrap()).unwrap();    assert_eq!(first["ok"], true);    assert_eq!(first["record"]["data"]["import_id"], "seed:1");    let mut next = input.clone();    next["data"]["import_id"] = "seed:2".into();    assert_eq!(        tables::reserve_imported_record(&mut ctx, next.as_object().unwrap()).unwrap(),        json!({"ok":false,"reason":"full","remaining":0})    );    assert_eq!(        tables::reserve_imported_record(&mut ctx, input.as_object().unwrap()).unwrap()["record"]            ["id"],        first["record"]["id"]    );    assert!(tables::create_imported_record(        &mut ctx,        json!({"table":"student","data":{"name":"Bypass","class":slot,"import_id":"seed:3"}})            .as_object()            .unwrap()    )    .is_err());}