Cotton code
688 lines · 20.9 KB · RustRaw
//! The five album tools over a REAL file, driven through//! `dispatch::call_tool` rather than the `/v1/mcp` endpoint — what each//! answers, what each refuses, and that every write lands as the person's.//!//! What is pinned: `title_by` and `added_by` become `user`, an edit to an open//! suggestion keeps it first, and a dismissal is never a deletion.//!//! ONE DIVERGENCE: the TypeScript hands `makeHarness` a `now` of its own; here//! the harness's `FixedClock` is the only clock, so it is MOVED to the same//! instant. That is stronger — a `decided_at` case cannot pass by accident on//! the day it is run.//!//! Every name, number and line of text is synthetic.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;fn at(iso: &str) -> chrono::DateTime<chrono::Utc> {    iso.parse().expect("an instant")}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 rows(    h: &Harness,    sql: &str,    params: Vec<SqlValue>,) -> Vec<Vec<(String, rusqlite::types::Value)>> {    h.with(|db| db.all(sql, &params))        .expect("the statement runs")        .iter()        .map(|row| row.columns().to_vec())        .collect()}fn text_of(row: &[(String, rusqlite::types::Value)], name: &str) -> Option<String> {    row.iter()        .find(|(key, _)| key == name)        .and_then(|(_, value)| match value {            rusqlite::types::Value::Text(value) => Some(value.clone()),            _ => None,        })}static SERIAL: AtomicU64 = AtomicU64::new(0);#[derive(Default)]struct PhotoOver {    subtypes: Vec<&'static str>,    is_utility: Option<i64>,    video: bool,}fn insert_photo(h: &Harness, taken_at: &str, over: PhotoOver) -> String {    let serial = SERIAL.fetch_add(1, Ordering::Relaxed) + 1;    let sha = format!("{serial:0>64}");    let id = format!("{}:{sha}", if over.video { "video" } else { "photo" });    let ws = h.workspace_id.clone();    let key = format!(        "{ws}/{}/{sha}.{}",        if over.video { "videos" } else { "photos" },        if over.video { "mp4" } else { "jpg" }    );    let subtypes = json!(over.subtypes).to_string();    if over.video {        run(            h,            "INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, taken_offset, subtypes, created_at, updated_at)             VALUES (?,?,?,?,?,1000,?,?,?,?,?)",            vec![                t(&id),                t(&ws),                t(&key),                t(&sha),                t("video/mp4"),                t(taken_at),                SqlValue::Integer(IST),                t(&subtypes),                t(AT),                t(AT),            ],        );    } else {        run(            h,            "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, taken_offset, subtypes, created_at, updated_at, is_utility)             VALUES (?,?,?,?,?,1000,?,?,?,?,?,?)",            vec![                t(&id),                t(&ws),                t(&key),                t(&sha),                t("image/jpeg"),                t(taken_at),                SqlValue::Integer(IST),                t(&subtypes),                t(AT),                t(AT),                over.is_utility.map_or(SqlValue::Null, SqlValue::Integer),            ],        );    }    id}#[derive(Default)]struct AlbumOver<'a> {    state: Option<&'a str>,    title: Option<&'a str>,    title_by: Option<&'a str>,    members: Vec<String>,}fn insert_album(h: &Harness, id: &str, over: AlbumOver<'_>) {    let state = over.state.unwrap_or("open");    // The anchor IS the album's first day (`derived_id.rs`): a fixture that    // said otherwise would test a row the pass never writes.    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 (?,?,?,?,?,?,?,?,?,?,?,?)",        vec![            t(id),            t(&h.workspace_id),            t(parts[1]),            t(state),            if state == "open" { SqlValue::Null } else { t(AT) },            t(over.title.unwrap_or("Dinner in town")),            t(over.title_by.unwrap_or("derived")),            t(&day),            t(&day),            over.members.first().map_or(SqlValue::Null, |id| t(id)),            t(AT),            t(AT),        ],    );    for record_id in &over.members {        let kind = record_id.split(':').next().expect("a kind");        let table = if kind == "video" {            "cotton_videos"        } else {            "cotton_photos"        };        let taken = rows(            h,            &format!("SELECT taken_at FROM {table} WHERE id = ?"),            vec![t(record_id)],        );        let sort_at = taken            .first()            .and_then(|row| text_of(row, "taken_at"))            .unwrap_or_else(|| AT.to_string());        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 (?,?,?,?,?,'derived',?,?,?)",            vec![                t(&synthetic_uuid("album-item")),                t(&h.workspace_id),                t(id),                t(kind),                t(record_id),                t(&sort_at),                t(AT),                t(AT),            ],        );    }}fn link_person(h: &Harness, record_id: &str, person_id: &str) {    run(        h,        "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, source_id, x, y, w, h, person_id, created_at, updated_at)         VALUES (?,?,'photo',?,'apple',?,0,0,0.1,0.1,?,?,?)",        vec![            t(&synthetic_uuid("face")),            t(&h.workspace_id),            t(record_id),            t(&synthetic_uuid("face-source")),            t(person_id),            t(AT),            t(AT),        ],    );}struct Fixture {    h: Harness,    secret: String,    a: String,    b: String,    c: String,    open_id: String,}fn fixture() -> Fixture {    let mut h = Harness::new();    h.clock.set(at(AT));    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let a = insert_photo(&h, "2026-03-14T13:30:00.000Z", PhotoOver::default());    let b = insert_photo(&h, "2026-03-14T13:40:00.000Z", PhotoOver::default());    let c = insert_photo(&h, "2026-03-14T13:50:00.000Z", PhotoOver::default());    let open_id = media_album_id("event", "2026-03-14T19");    insert_album(        &h,        &open_id,        AlbumOver {            members: vec![a.clone(), b.clone(), c.clone()],            ..AlbumOver::default()        },    );    Fixture {        h,        secret,        a,        b,        c,        open_id,    }}fn album_state(h: &Harness, id: &str) -> Vec<(String, rusqlite::types::Value)> {    rows(        h,        "SELECT state, decided_at, title, title_by, cover_id FROM cotton_media_albums WHERE id = ?",        vec![t(id)],    )    .into_iter()    .next()    .expect("the album row")}fn member_rows(h: &Harness, id: &str) -> Vec<(String, String)> {    rows(        h,        "SELECT record_id, added_by FROM cotton_media_album_items WHERE album_id = ? ORDER BY sort_at, record_id",        vec![t(id)],    )    .iter()    .map(|row| {        (            text_of(row, "record_id").unwrap_or_default(),            text_of(row, "added_by").unwrap_or_default(),        )    })    .collect()}fn album_ids(answer: &Value) -> Vec<String> {    answer["albums"]        .as_array()        .expect("a list")        .iter()        .map(|row| row["id"].as_str().expect("an id").to_string())        .collect()}// ── list_albums / get_album ─────────────────────────────────────────────────#[test]fn lists_open_suggestions_first_hides_dismissed_and_expands_one() {    let f = fixture();    let person = synthetic_uuid("person");    run(        &f.h,        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?,?,?,?,?)",        vec![t(&person), t(&f.h.workspace_id), t("Asha"), t(AT), t(AT)],    );    link_person(&f.h, &f.a, &person);    link_person(&f.h, &f.b, &person);    let kept_id = media_album_id("trip", "2026-04-10");    let trip_member = insert_photo(&f.h, "2026-04-10T05:00:00.000Z", PhotoOver::default());    insert_album(        &f.h,        &kept_id,        AlbumOver {            state: Some("kept"),            title: Some("Hampi"),            title_by: Some("user"),            members: vec![trip_member],        },    );    let dismissed_id = media_album_id("event", "2026-05-01T10");    insert_album(        &f.h,        &dismissed_id,        AlbumOver {            state: Some("dismissed"),            ..AlbumOver::default()        },    );    let listed = call_tool(&f.h, &f.secret, "list_albums", json!({}));    assert_eq!(album_ids(&listed), vec![f.open_id.clone(), kept_id.clone()]);    let first = &listed["albums"][0];    assert_eq!(first["kind"], json!("event"));    assert_eq!(first["state"], json!("open"));    assert_eq!(first["members"], json!(3));    assert_eq!(first["people"], json!(["Asha"]));    assert_eq!(first["titleBy"], json!("derived"));    let dismissed = call_tool(        &f.h,        &f.secret,        "list_albums",        json!({ "state": "dismissed" }),    );    assert_eq!(album_ids(&dismissed), vec![dismissed_id]);    let trips = call_tool(&f.h, &f.secret, "list_albums", json!({ "kind": "trip" }));    assert_eq!(album_ids(&trips), vec![kept_id]);    let march = call_tool(        &f.h,        &f.secret,        "list_albums",        json!({ "since": "2026-03-01T00:00:00Z", "until": "2026-03-31T00:00:00Z" }),    );    assert_eq!(album_ids(&march), vec![f.open_id.clone()]);    let one = call_tool(&f.h, &f.secret, "get_album", json!({ "id": f.open_id }));    assert_eq!(one["id"], json!(f.open_id));    assert_eq!(one["members"], json!(3));    assert_eq!(one["projects"], json!([]));    assert_eq!(        one["items"]            .as_array()            .expect("items")            .iter()            .map(|item| (                item["id"].as_str().unwrap_or_default().to_string(),                item["addedBy"].as_str().unwrap_or_default().to_string()            ))            .collect::<Vec<_>>(),        vec![            (f.a.clone(), "derived".to_string()),            (f.b.clone(), "derived".to_string()),            (f.c.clone(), "derived".to_string()),        ]    );    let missing = call_tool_raw(        &f.h,        &f.secret,        "get_album",        json!({ "id": media_album_id("event", "2020-01-01T09") }),    );    assert!(missing.is_error);    assert!(        missing.text.contains("no album with id"),        "{}",        missing.text    );    let bad_id = call_tool_raw(&f.h, &f.secret, "get_album", json!({ "id": "photo:abc" }));    assert!(bad_id.is_error);    assert!(bad_id.text.contains("album's id"), "{}", bad_id.text);}// ── decide_album ────────────────────────────────────────────────────────────#[test]fn keeps_dismisses_and_reopens_and_never_deletes() {    let f = fixture();    let kept = call_tool(        &f.h,        &f.secret,        "decide_album",        json!({ "id": f.open_id, "decision": "keep" }),    );    assert_eq!(kept["state"], json!("kept"));    let row = album_state(&f.h, &f.open_id);    assert_eq!(text_of(&row, "state"), Some("kept".to_string()));    assert_eq!(text_of(&row, "decided_at"), Some(AT.to_string()));    let again = call_tool_raw(        &f.h,        &f.secret,        "decide_album",        json!({ "id": f.open_id, "decision": "keep" }),    );    assert!(again.is_error);    assert!(again.text.contains("already kept"), "{}", again.text);    let dismissed = call_tool(        &f.h,        &f.secret,        "decide_album",        json!({ "id": f.open_id, "decision": "dismiss" }),    );    assert_eq!(dismissed["state"], json!("dismissed"));    assert_eq!(member_rows(&f.h, &f.open_id).len(), 3);    let reopened = call_tool(        &f.h,        &f.secret,        "decide_album",        json!({ "id": f.open_id, "decision": "open" }),    );    assert_eq!(reopened["state"], json!("open"));    assert_eq!(reopened["decidedAt"], Value::Null);    let row = album_state(&f.h, &f.open_id);    assert_eq!(text_of(&row, "state"), Some("open".to_string()));    assert_eq!(text_of(&row, "decided_at"), None);    // The tool's own audit line names the decision, and there are three — the    // refused second `keep` writes none, because it never decided anything.    //    // The server asserted this over the `cotton_mcp_audit` rows the dispatcher    // writes; the ROW is the transport's (the phone writes none), so what a    // suite about the TOOL can assert is the ask, which is exactly what the    // handler passed to `ctx.audit`.    assert_eq!(        f.h.audit_lines()            .into_iter()            .filter(|line| line.tool == "decide_album")            .map(|line| line.summary)            .collect::<Vec<_>>(),        vec![            format!("{} → kept", f.open_id),            format!("{} → dismissed", f.open_id),            format!("{} → open", f.open_id),        ]    );}// ── update_album ────────────────────────────────────────────────────────────#[test]fn renames_as_the_person_keeps_an_open_suggestion_and_refuses_a_screenshot() {    let f = fixture();    let d = insert_photo(&f.h, "2026-03-14T15:00:00.000Z", PhotoOver::default());    let clip = insert_photo(        &f.h,        "2026-03-14T15:10:00.000Z",        PhotoOver {            video: true,            ..PhotoOver::default()        },    );    let out = call_tool(        &f.h,        &f.secret,        "update_album",        json!({            "id": f.open_id,            "title": "  Our   evening ",            "add": [d, clip],            "remove": [f.c],            "coverId": d,        }),    );    assert_eq!(out["state"], json!("kept"));    assert_eq!(out["title"], json!("Our evening"));    assert_eq!(out["titleBy"], json!("user"));    assert_eq!(out["coverId"], json!(d));    assert_eq!(out["members"], json!(4));    assert_eq!(        member_rows(&f.h, &f.open_id),        vec![            (f.a.clone(), "derived".to_string()),            (f.b.clone(), "derived".to_string()),            (d.clone(), "user".to_string()),            (clip.clone(), "user".to_string()),        ]    );    // The removed picture still exists.    assert!(!rows(        &f.h,        "SELECT id FROM cotton_photos WHERE id = ?",        vec![t(&f.c)]    )    .is_empty());    let shot = insert_photo(        &f.h,        "2026-03-14T16:00:00.000Z",        PhotoOver {            subtypes: vec!["screenshot"],            ..PhotoOver::default()        },    );    let refused = call_tool_raw(        &f.h,        &f.secret,        "update_album",        json!({ "id": f.open_id, "add": [shot] }),    );    assert!(refused.is_error);    assert!(        refused.text.contains("a screenshot is not a moment"),        "{}",        refused.text    );    let info = insert_photo(        &f.h,        "2026-03-14T16:10:00.000Z",        PhotoOver {            is_utility: Some(1),            ..PhotoOver::default()        },    );    assert!(        call_tool_raw(            &f.h,            &f.secret,            "update_album",            json!({ "id": f.open_id, "add": [info] })        )        .is_error    );    assert_eq!(member_rows(&f.h, &f.open_id).len(), 4);    // The cover must be a member; a missing picture is named; nothing to change    // is refused.    assert!(call_tool_raw(        &f.h,        &f.secret,        "update_album",        json!({ "id": f.open_id, "coverId": f.c })    )    .text    .contains("one of the album's own pictures"));    assert!(call_tool_raw(        &f.h,        &f.secret,        "update_album",        json!({ "id": f.open_id, "add": [format!("photo:{}", "f".repeat(64))] })    )    .text    .contains("no photo with id"));    assert!(        call_tool_raw(&f.h, &f.secret, "update_album", json!({ "id": f.open_id }))            .text            .contains("nothing to change")    );    // Removing the cover picks another; a dismissed album refuses until    // re-opened.    let after = call_tool(        &f.h,        &f.secret,        "update_album",        json!({ "id": f.open_id, "remove": [d] }),    );    assert_eq!(after["coverId"], json!(f.a));    assert_eq!(after["members"], json!(3));    call_tool(        &f.h,        &f.secret,        "decide_album",        json!({ "id": f.open_id, "decision": "dismiss" }),    );    let closed = call_tool_raw(        &f.h,        &f.secret,        "update_album",        json!({ "id": f.open_id, "title": "x" }),    );    assert!(closed.is_error);    assert!(        closed.text.contains("re-open it with decide_album"),        "{}",        closed.text    );}// ── create_album ────────────────────────────────────────────────────────────#[test]fn is_born_kept_and_the_persons_anchored_like_a_suggestion_would_be() {    let mut f = fixture();    let x = insert_photo(&f.h, "2026-06-01T04:00:00.000Z", PhotoOver::default());    let y = insert_photo(&f.h, "2026-06-02T04:00:00.000Z", PhotoOver::default());    let out = call_tool(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "trip", "title": "Coorg", "photoIds": [y, x], "coverId": y }),    );    let minted = media_album_id("trip", "2026-06-01");    assert_eq!(out["id"], json!(minted));    assert_eq!(out["state"], json!("kept"));    assert_eq!(out["titleBy"], json!("user"));    assert_eq!(out["title"], json!("Coorg"));    assert_eq!(out["startsAt"], json!("2026-06-01"));    assert_eq!(out["endsAt"], json!("2026-06-02"));    assert_eq!(out["coverId"], json!(y));    assert_eq!(out["members"], json!(2));    assert_eq!(        member_rows(&f.h, &minted),        vec![            (x.clone(), "user".to_string()),            (y.clone(), "user".to_string()),        ]    );    // The same moment as the open suggestion: refused, naming it.    let taken = call_tool_raw(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "event", "title": "Mine", "photoIds": [f.a, f.b] }),    );    assert!(taken.is_error);    assert!(taken.text.contains(&f.open_id), "{}", taken.text);    // A screenshot, an unknown picture, an empty list, a bad kind, a blank    // title.    let shot = insert_photo(        &f.h,        "2026-07-01T04:00:00.000Z",        PhotoOver {            subtypes: vec!["screenshot"],            ..PhotoOver::default()        },    );    assert!(call_tool_raw(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "event", "title": "x", "photoIds": [shot] })    )    .text    .contains("not a moment"));    assert!(call_tool_raw(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "event", "title": "x", "photoIds": [format!("photo:{}", "e".repeat(64))] })    )    .text    .contains("no photo with id"));    assert!(call_tool_raw(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "event", "title": "x", "photoIds": [] })    )    .text    .contains("1 to 500"));    assert!(call_tool_raw(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "memory", "title": "x", "photoIds": [f.a] })    )    .text    .contains("kind must be one of"));    assert!(call_tool_raw(        &f.h,        &f.secret,        "create_album",        json!({ "kind": "event", "title": "   ", "photoIds": [f.a] })    )    .text    .contains("title must be"));    // A read-only token cannot write.    let reader = mint_token(&mut f.h, &["read"], "Reader");    assert!(        call_tool_raw(            &f.h,            &reader,            "create_album",            json!({ "kind": "event", "title": "x", "photoIds": [f.a] })        )        .is_error    );}