Cotton code
276 lines · 14.3 KB · RustRaw
//! Albums are the photo list's groups (Spec 10 G item 3, the architect's B)://! `media` says `groups.kept_in: { table: album, items: album_item }`, so the//! four group verbs on it read and write albums — no `_group` row, no column//! — while every other table's groups stay rows under `_group`. Driven end to//! end through the dispatcher over a real file. Every name is invented.mod support;use std::sync::atomic::{AtomicU64, Ordering};use cotton_store::protocol::derived_id::media_album_id;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_raw, mint_token};const AT: &str = "2026-09-01T00:00:00.000Z";/// The offset every fixture picture was taken at — India, +05:30.const IST: i64 = 19800;static SERIAL: AtomicU64 = AtomicU64::new(0);fn t(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn run(h: &Harness, sql: &str, params: Vec<SqlValue>) {    h.with(|db| db.run(sql, &params)).expect("the statement runs");}fn texts(h: &Harness, sql: &str, params: Vec<SqlValue>) -> Vec<Vec<Option<String>>> {    h.with(|db| db.all(sql, &params))        .expect("the statement runs")        .iter()        .map(|row| {            row.columns()                .iter()                .map(|(_, value)| match value {                    SqlValue::Text(text) => Some(text.clone()),                    SqlValue::Integer(n) => Some(n.to_string()),                    _ => None,                })                .collect()        })        .collect()}fn harness() -> (Harness, String) {    let mut h = Harness::new();    h.clock.set(AT.parse().expect("an instant"));    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}fn photo(h: &Harness, taken_at: &str) -> String {    let serial = SERIAL.fetch_add(1, Ordering::Relaxed) + 1;    let sha = format!("{serial:0>64}");    let id = format!("photo:{sha}");    let key = format!("{}/photos/{sha}.jpg", h.workspace_id);    run(        h,        "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, taken_offset, subtypes, created_at, updated_at)         VALUES (?,?,?,?,'image/jpeg',1000,?,?,'[]',?,?)",        vec![t(&id), t(&h.workspace_id), t(&key), t(&sha), t(taken_at), SqlValue::Integer(IST), t(AT), t(AT)],    );    id}/// An album the nightly pass suggested (or one already decided), its first/// member its cover.fn album(h: &Harness, id: &str, state: &str, title: &str, members: &[&String]) {    let parts: Vec<&str> = id.split(':').collect();    let day: String = parts[2].chars().take(10).collect();    run(        h,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, state, decided_at, title, title_by, starts_at, ends_at, cover_id, created_at, updated_at)         VALUES (?,?,?,?,?,?,'derived',?,?,?,?,?)",        vec![            t(id),            t(&h.workspace_id),            t(parts[1]),            t(state),            if state == "open" { SqlValue::Null } else { t(AT) },            t(title),            t(&day),            t(&day),            members.first().map_or(SqlValue::Null, |id| t(id)),            t(AT),            t(AT),        ],    );    for record in members {        run(            h,            "INSERT INTO cotton_media_album_items (id, workspace_id, album_id, record_kind, record_id, added_by, sort_at, created_at, updated_at)             VALUES (?,?,?,'photo',?,'derived',?,?,?)",            vec![t(&synthetic_uuid("album-item")), t(&h.workspace_id), t(id), t(record), t(AT), t(AT), t(AT)],        );    }}/// An album's own fields: state, title, cover, first and last day.fn album_row(h: &Harness, id: &str) -> Vec<Option<String>> {    texts(h, "SELECT state, title, cover_id, starts_at, ends_at FROM cotton_media_albums WHERE id = ?", vec![t(id)])        .into_iter()        .next()        .unwrap_or_else(|| panic!("no album {id}"))}fn album_members(h: &Harness, id: &str) -> Vec<String> {    texts(h, "SELECT record_id FROM cotton_media_album_items WHERE album_id = ? ORDER BY record_id", vec![t(id)])        .into_iter()        .filter_map(|row| row.into_iter().next().flatten())        .collect()}fn group_rows(h: &Harness) -> usize {    texts(h, "SELECT id FROM cotton_groups", vec![]).len()}fn stacks(h: &Harness, secret: &str) -> Vec<Value> {    call_tool(h, secret, "list_groups", json!({ "table": "media" }))["groups"].as_array().expect("groups").clone()}fn sorted(mut ids: Vec<String>) -> Vec<String> {    ids.sort();    ids}/// RULE: A group made on the photo list is an album — create_group on media writes the album (born kept, named, its cover and days from its pictures) and its picture rows, and no `_group` row — and reads back from list_groups as a group whose id is the album's and whose pile is the list's own pictures; groups backed by the album table, no column (architect, Spec 10 G item 3 B).#[test]fn a_group_made_on_the_photo_list_is_an_album() {    let (h, secret) = harness();    let first = photo(&h, "2026-06-01T04:00:00.000Z");    let second = photo(&h, "2026-06-02T04:00:00.000Z");    let made = call_tool(&h, &secret, "create_group", json!({ "table": "media", "name": "Coorg", "records": [second, first] }));    let id = media_album_id("trip", "2026-06-01");    assert_eq!(made["group"]["id"], json!(id), "{made}");    assert_eq!(made["change"]["table"], json!("album"), "the change is the album's own: {made}");    let said = made["change"]["receipt"]["said"].as_str().unwrap_or_default();    assert!(said.starts_with("Made Coorg with 2 "), "the receipt names the album and how many went in: {made}");    assert_eq!(        album_row(&h, &id),        vec![Some("kept".into()), Some("Coorg".into()), Some(first.clone()), Some("2026-06-01".into()), Some("2026-06-02".into())],        "born kept, as create_album makes one: its cover the first taken, its days its pictures'"    );    assert_eq!(album_members(&h, &id), sorted(vec![first.clone(), second.clone()]));    assert_eq!(group_rows(&h), 0, "no group row stands beside the album");    let read = stacks(&h, &secret);    assert_eq!(read.len(), 1, "{read:?}");    assert_eq!(read[0]["id"], json!(id));    assert_eq!(read[0]["name"], json!("Coorg"));    assert_eq!(read[0]["table"], json!("media"));    assert_eq!(read[0]["kept_in"], json!("album"), "a stack says whose page opens it");    assert_eq!(read[0]["count"], json!(2));    let top: Vec<&str> = read[0]["top"].as_array().unwrap().iter().map(|record| record["id"].as_str().unwrap()).collect();    assert_eq!(top, vec![first.as_str(), second.as_str()], "the cover on top, then the rest");    assert_eq!(read[0]["top"][0]["table"], json!("media"), "a pile is the photo list's own prints");    // One evening's pictures make an event, as the album table names one.    let dusk = photo(&h, "2026-07-04T13:00:00.000Z");    let night = photo(&h, "2026-07-04T15:00:00.000Z");    let evening = call_tool(&h, &secret, "create_group", json!({ "table": "media", "name": "Rooftop", "records": [dusk, night] }));    assert_eq!(evening["group"]["id"], json!(media_album_id("event", "2026-07-04T18")), "{evening}");    // A group's members are the album's pictures, on the photo list's own read.    let page = call_tool(&h, &secret, "list_records", json!({ "table": "media", "where": { "group": id } }));    let listed: Vec<String> = page["records"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap().to_string()).collect();    assert_eq!(sorted(listed), sorted(vec![first, second]));}/// RULE: A group verb on the photo list is the album's own write and leaves suggested, kept and dismissed, the cover and the days to the album — a rename, an add and a remove change the album's name and its picture rows and nothing else of a kept album, a delete dismisses the album (never deletes it) and its Undo brings it back, and the MCP album tools read the same album.#[test]fn a_group_verb_writes_the_album_and_leaves_its_own_fields_alone() {    let (h, secret) = harness();    let a = photo(&h, "2026-03-14T13:30:00.000Z");    let b = photo(&h, "2026-03-14T13:40:00.000Z");    let c = photo(&h, "2026-03-20T13:40:00.000Z");    let id = media_album_id("event", "2026-03-14T19");    album(&h, &id, "kept", "Dinner in town", &[&a, &b]);    let before = album_row(&h, &id);    let renamed = call_tool(&h, &secret, "update_group", json!({ "id": id, "name": "Birthday dinner" }));    assert_eq!(renamed["change"]["table"], json!("album"), "{renamed}");    assert_eq!(renamed["group"]["name"], json!("Birthday dinner"));    let after = album_row(&h, &id);    assert_eq!(after[1], Some("Birthday dinner".into()));    assert_eq!((&after[0], &after[2], &after[3], &after[4]), (&before[0], &before[2], &before[3], &before[4]), "only the name moved");    let added = call_tool(&h, &secret, "update_group", json!({ "id": id, "add": [c] }));    assert_eq!(added["change"]["table"], json!("album_item"), "{added}");    assert_eq!(added["change"]["undoable"], json!(true), "one picture put in is undone by its receipt");    assert_eq!(album_members(&h, &id), sorted(vec![a.clone(), b.clone(), c.clone()]));    assert_eq!(added["group"]["count"], json!(3));    let after = album_row(&h, &id);    assert_eq!((&after[0], &after[2], &after[3], &after[4]), (&before[0], &before[2], &before[3], &before[4]), "state, cover and days stay");    assert!(call_tool_raw(&h, &secret, "update_group", json!({ "id": id, "add": [c] })).text.contains("Already in"));    let removed = call_tool(&h, &secret, "update_group", json!({ "id": id, "remove": [b] }));    assert_eq!(removed["change"]["receipt"]["said"].as_str().map(|said| said.starts_with("Removed")), Some(true), "{removed}");    assert_eq!(album_members(&h, &id), sorted(vec![a.clone(), c.clone()]));    let after = album_row(&h, &id);    assert_eq!((&after[0], &after[2], &after[3], &after[4]), (&before[0], &before[2], &before[3], &before[4]));    let got = call_tool(&h, &secret, "get_album", json!({ "id": id }));    assert_eq!(got["title"], json!("Birthday dinner"), "the album tools read what the group verbs wrote: {got}");    for (refusal, args) in [        ("order they were taken", json!({ "id": id, "order": [c, a] })),        ("no where", json!({ "id": id, "where": { "kind": "photo" } })),    ] {        let said = call_tool_raw(&h, &secret, "update_group", args).text;        assert!(said.contains(refusal), "{said}");    }    let deleted = call_tool(&h, &secret, "delete_group", json!({ "id": id }));    assert_eq!(deleted["group"], Value::Null);    assert_eq!(album_row(&h, &id)[0], Some("dismissed".into()), "a deleted group is a dismissed album, still there");    assert_eq!(album_members(&h, &id), sorted(vec![a.clone(), c.clone()]), "its pictures stay in it");    assert!(stacks(&h, &secret).is_empty(), "a dismissed album is no stack");    let change = deleted["change"]["id"].as_str().expect("a change id");    call_tool(&h, &secret, "undo", json!({ "change_id": change }));    assert_eq!(album_row(&h, &id)[0], Some("kept".into()), "its Undo brings the album back as it was");    assert_eq!(stacks(&h, &secret).len(), 1);    assert_eq!(group_rows(&h), 0);}/// RULE: The photo list's stacks are the album list — the same albums in the same order as list_records on album answers for /photos/albums (a suggestion waiting for its answer first, wearing the album slip's "suggested", then the kept; a dismissed one left out) — so a suggested album is a stack marked suggested, never a second list.#[test]fn the_photo_lists_stacks_are_the_album_list() {    let (h, secret) = harness();    let a = photo(&h, "2026-03-14T13:30:00.000Z");    let b = photo(&h, "2026-04-10T05:00:00.000Z");    let c = photo(&h, "2026-05-02T05:00:00.000Z");    let suggested = media_album_id("event", "2026-03-14T19");    let kept = media_album_id("trip", "2026-04-10");    let dismissed = media_album_id("trip", "2026-05-02");    album(&h, &suggested, "open", "Dinner in town", &[&a]);    album(&h, &kept, "kept", "Hampi", &[&b]);    album(&h, &dismissed, "dismissed", "Errand", &[&c]);    let listed = call_tool(&h, &secret, "list_records", json!({ "table": "album" }));    let albums: Vec<&str> = listed["records"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();    let read = stacks(&h, &secret);    let piles: Vec<&str> = read.iter().map(|group| group["id"].as_str().unwrap()).collect();    assert_eq!(piles, albums, "the stacks are the album list, in its order");    assert_eq!(piles, vec![suggested.as_str(), kept.as_str()]);    assert_eq!(read[0]["byline"], json!("suggested"));    assert_eq!(read[1]["byline"], Value::Null);    let holding = call_tool(&h, &secret, "list_groups", json!({ "table": "media", "record": b }));    let holds: Vec<bool> = holding["groups"].as_array().unwrap().iter().map(|g| g["holds"].as_bool().unwrap()).collect();    assert_eq!(holds, vec![false, true]);    // A group starts from its pictures and keeps no filter.    let none = call_tool_raw(&h, &secret, "create_group", json!({ "table": "media", "name": "Empty" })).text;    assert!(none.contains("pick some"), "{none}");    let filter = call_tool_raw(&h, &secret, "create_group", json!({ "table": "media", "name": "Films", "where": { "kind": "video" } })).text;    assert!(filter.contains("no where"), "{filter}");}/// RULE: Only a table whose definition keeps its groups in the album table writes albums — a group made on People is still a row under `_group` and no album is written — so albums-as-groups changes no other table's groups.#[test]fn other_tables_groups_are_still_group_rows() {    let (h, secret) = harness();    let person = call_tool(&h, &secret, "create_record", json!({ "table": "person", "data": { "full_name": "Asha Rao" } }));    let person = person["record"]["id"].as_str().unwrap().to_string();    let made = call_tool(&h, &secret, "create_group", json!({ "table": "person", "name": "Family", "records": [person] }));    assert_eq!(made["change"]["table"], json!("_group"), "{made}");    assert_eq!(group_rows(&h), 1);    assert!(texts(&h, "SELECT id FROM cotton_media_albums", vec![]).is_empty(), "no album is written for a person");    let id = made["group"]["id"].as_str().unwrap();    call_tool(&h, &secret, "update_group", json!({ "id": id, "name": "Close family" }));    call_tool(&h, &secret, "delete_group", json!({ "id": id }));    assert!(texts(&h, "SELECT id FROM cotton_media_albums", vec![]).is_empty());}