1108 lines · 50.6 KB · RustRaw
//! The generic record verbs over the photos engine — `photo`, `video`,//! `album`, and the engine's views `media`, `album_item`, `duplicate` and//! `sighting` — driven end to end through the dispatcher over a real file.//!//! What is pinned: what each table READS (the engine's own columns beside the//! stored ones), how each list narrows, searches, orders and counts, and that//! every write lands through the photo, video, album and duplicate tools that//! already write it — with the refusals where the engine has no writer.//!//! Every name, caption, place and picture is synthetic//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use cotton_store::protocol::derived_id::{media_album_item_id, media_duplicate_id};use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};const AT: &str = "2026-09-20T08:00:00.000Z";fn t(value: &str) -> SqlValue { SqlValue::Text(value.to_string())}fn n(value: i64) -> SqlValue { SqlValue::Integer(value)}fn hash(serial: u8) -> String { format!("{serial:0>64}")}struct Seeded { h: Harness, secret: String, /// "Sunset at the lake", a favourite, in the open trip album. lake: String, /// No caption, a dog on the beach, in the kept event album. dog: String, /// A screenshot: never addable to an album. screenshot: String, /// A picture of information: never addable to an album. receipt: String, /// A likely copy of `lake`. copy: String, /// A film with a poster, in the open trip album. film: String, open_album: String, kept_album: String, dismissed_album: String, open_pair: String, dismissed_pair: String,}struct NewPhoto<'a> { serial: u8, caption: Option<&'a str>, summary: Option<&'a str>, taken_at: &'a str, size: (i64, i64, i64), favourite: bool, utility: Option<i64>, subtypes: &'a str,}fn insert_photo(h: &Harness, photo: NewPhoto<'_>) -> String { let sha = hash(photo.serial); let id = format!("photo:{sha}"); h.run( "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, width, \ height, taken_at, caption, summary, summary_by, summary_at, favourite, is_utility, subtypes, \ created_at, updated_at) \ VALUES (?, ?, ?, ?, 'image/jpeg', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[ t(&id), t(&h.workspace_id), t(&format!("{}/photos/{sha}.jpg", h.workspace_id)), t(&sha), n(photo.size.2), n(photo.size.0), n(photo.size.1), t(photo.taken_at), photo.caption.map_or(SqlValue::Null, t), photo.summary.map_or(SqlValue::Null, t), photo.summary.map_or(SqlValue::Null, |_| t("describe")), photo.summary.map_or(SqlValue::Null, |_| t(AT)), n(i64::from(photo.favourite)), photo.utility.map_or(SqlValue::Null, n), t(photo.subtypes), t(AT), t(AT), ], ); id}fn insert_film(h: &Harness, serial: u8) -> String { let sha = hash(serial); let id = format!("video:{sha}"); h.run( "INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, width, \ height, duration_ms, taken_at, poster_key, caption, summary, summary_by, summary_at, \ created_at, updated_at) \ VALUES (?, ?, ?, ?, 'video/mp4', 9000000, 1920, 1080, 42000, ?, ?, 'Jumping in', \ 'a child jumps into the lake', 'describe', ?, ?, ?)", &[ t(&id), t(&h.workspace_id), t(&format!("{}/videos/{sha}.mp4", h.workspace_id)), t(&sha), t("2026-09-10T12:00:00.000Z"), t(&format!("{}/posters/{sha}.jpg", h.workspace_id)), t(AT), t(AT), t(AT), ], ); id}fn insert_album(h: &Harness, id: &str, state: &str, title: &str, members: &[&str]) { let parts: Vec<&str> = id.split(':').collect(); let day: String = parts[2].chars().take(10).collect(); h.run( "INSERT INTO cotton_media_albums (id, workspace_id, kind, state, decided_at, title, title_by, \ starts_at, ends_at, home_label, cover_id, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?, 'derived', ?, ?, 'Example City', ?, ?, ?)", &[ 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, |first| t(first)), t(AT), t(AT), ], ); for record in members { let kind = record.split(':').next().unwrap(); h.run( "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', ?, ?, ?)", &[ t(&media_album_item_id(id, record)), t(&h.workspace_id), t(id), t(kind), t(record), t(AT), t(AT), t(AT), ], ); }}fn insert_pair(h: &Harness, keep: &str, copy: &str, distance: i64, state: &str) -> String { let id = media_duplicate_id(keep, copy); h.run( "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, copy_id, \ distance, method, state, decided_at, created_at, updated_at) \ VALUES (?, ?, 'photo', ?, ?, ?, 'phash', ?, ?, ?, ?)", &[ t(&id), t(&h.workspace_id), t(keep), t(copy), n(distance), t(state), if state == "open" { SqlValue::Null } else { t(AT) }, t(AT), t(AT), ], ); id}fn insert_sighting(h: &Harness, id: &str, kind: &str, record: &str, source: &str, thread: Option<&str>) { h.run( "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, \ source_id, thread_id, key, seen_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[ t(id), t(&h.workspace_id), t(kind), t(record), t(source), thread.map_or(SqlValue::Null, |_| t(&format!("{id}-message"))), thread.map_or(SqlValue::Null, t), t(&format!("{}/sightings/{id}.jpg", h.workspace_id)), t(AT), t(AT), t(AT), ], );}fn seeded() -> Seeded { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); let lake = insert_photo( &h, NewPhoto { serial: 1, caption: Some("Sunset at the lake"), summary: Some("An orange sky over still water."), taken_at: "2026-09-10T10:00:00.000Z", size: (4032, 3024, 2_202_009), favourite: true, utility: Some(0), subtypes: "[]", }, ); let dog = insert_photo( &h, NewPhoto { serial: 2, caption: None, summary: Some("A dog running on the beach."), taken_at: "2026-09-11T09:00:00.000Z", size: (3024, 4032, 1_500_000), favourite: false, utility: None, subtypes: "[\"portrait\"]", }, ); let screenshot = insert_photo( &h, NewPhoto { serial: 3, caption: None, summary: None, taken_at: "2026-09-12T09:00:00.000Z", size: (1170, 2532, 400_000), favourite: false, utility: Some(0), subtypes: "[\"screenshot\"]", }, ); let receipt = insert_photo( &h, NewPhoto { serial: 4, caption: Some("Example receipt"), summary: None, taken_at: "2026-09-13T09:00:00.000Z", size: (1000, 1000, 100_000), favourite: false, utility: Some(1), subtypes: "[]", }, ); let copy = insert_photo( &h, NewPhoto { serial: 5, caption: None, summary: None, taken_at: "2026-09-10T10:01:00.000Z", size: (3024, 4032, 1_782_579), favourite: false, utility: Some(0), subtypes: "[]", }, ); let film = insert_film(&h, 6); let open_album = "album:trip:2026-09-10".to_string(); let kept_album = "album:event:2026-09-11T09".to_string(); let dismissed_album = "album:event:2026-07-01T09".to_string(); insert_album(&h, &open_album, "open", "Example lake trip", &[&lake, &film]); insert_album(&h, &kept_album, "kept", "Example beach evening", &[&dog]); insert_album(&h, &dismissed_album, "dismissed", "Example nothing", &[&lake]); let open_pair = insert_pair(&h, &lake, ©, 3, "open"); let dismissed_pair = insert_pair(&h, &lake, &dog, 9, "dismissed"); let thread = "c0000000-0000-4000-8000-000000000001"; h.run( "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES (?, ?, 'group', 'Example family', ?, ?)", &[t(thread), t(&h.workspace_id), t(AT), t(AT)], ); insert_sighting(&h, "s-lake", "photo", &lake, "message", Some(thread)); insert_sighting(&h, "s-film", "video", &film, "library", None); Seeded { h, secret, lake, dog, screenshot, receipt, copy, film, open_album, kept_album, dismissed_album, open_pair, dismissed_pair, }}impl Seeded { fn call(&self, tool: &str, args: Value) -> Value { call_tool(&self.h, &self.secret, tool, args) } fn refused(&self, tool: &str, args: Value) -> String { let answer = call_tool_raw(&self.h, &self.secret, tool, args); assert!(answer.is_error, "{tool} was expected to refuse: {}", answer.text); answer.text } fn list(&self, args: Value) -> Value { self.call("list_records", args) } fn ids(&self, args: Value) -> Vec<String> { ids(&self.list(args)) } fn get(&self, table: &str, id: &str) -> Value { self.call("get_record_by_table", json!({ "table": table, "id": id })) }}fn ids(answer: &Value) -> Vec<String> { answer["records"] .as_array() .expect("records") .iter() .map(|record| record["id"].as_str().unwrap().to_string()) .collect()}// ── the library ─────────────────────────────────────────────────────────────/// RULE: The library is every photo and every video as one list, newest first, a film's print its poster, narrowed by kind, searched by a substring of the caption or the description, and counted whole.#[test]fn the_library_is_every_picture_newest_first_searched_and_counted() { let s = seeded(); let all = s.list(json!({ "table": "media" })); assert_eq!( ids(&all), [s.receipt.as_str(), s.screenshot.as_str(), s.dog.as_str(), s.film.as_str(), s.copy.as_str(), s.lake.as_str()] ); assert_eq!(all["total"], 6); let film = &all["records"][3]["data"]; assert_eq!(film["kind"], "video"); assert_eq!(film["duration_ms"], 42000); assert!(film["key"].as_str().unwrap().contains("/posters/"), "a film's print is its poster"); assert_eq!(all["records"][5]["data"]["caption"], "Sunset at the lake"); let videos = s.list(json!({ "table": "media", "where": { "kind": "video" } })); assert_eq!(ids(&videos), [s.film.as_str()]); assert_eq!(videos["total"], 1); let paged = s.list(json!({ "table": "media", "where": { "kind": "photo" }, "limit": 2 })); assert_eq!(paged["records"].as_array().unwrap().len(), 2); assert_eq!(paged["next_page"], 2); assert_eq!(paged["total"], 5, "the total is the whole list, not the page"); assert_eq!(s.ids(json!({ "table": "media", "query": "DOG" })), [s.dog.as_str()]); assert_eq!(s.ids(json!({ "table": "media", "query": "orange lake" })), [s.lake.as_str()]); assert_eq!(s.ids(json!({ "table": "media", "query": "lake" })), [s.film.as_str(), s.lake.as_str()]); assert_eq!(s.ids(json!({ "table": "media", "query": "100%" })), Vec::<String>::new()); // A picture the owner agreed is a copy leaves the library — and nothing // else: the photo table still lists it, and it still reads by id. s.call( "update_record", json!({ "table": "duplicate", "id": s.open_pair, "patch": { "state": "confirmed" } }), ); assert!(!s.ids(json!({ "table": "media" })).contains(&s.copy)); assert!(s.ids(json!({ "table": "photo" })).contains(&s.copy)); assert_eq!(s.get("media", &s.copy)["data"]["kind"], "photo");}/// RULE: The library is read here and changed on a picture's own table: a create or an update of it is refused in words, as is a column it does not have.#[test]fn the_library_refuses_what_belongs_to_a_pictures_own_table() { let s = seeded(); let update = s.refused( "update_record", json!({ "table": "media", "id": s.lake, "patch": { "caption": "x" } }), ); assert!(update.contains("update_record on \"photo\""), "{update}"); let create = s.refused( "create_record", json!({ "table": "media", "data": { "caption": "x" } }), ); assert!(create.contains("enters as its bytes"), "{create}"); for column in ["albums", "people", "no_such_column"] { let refusal = s.refused("list_records", json!({ "table": "media", "where": { column: "x" } })); assert!(refusal.contains(column), "{refusal}"); } let project = s.refused("list_records", json!({ "table": "duplicate", "project": "nowhere" })); assert!(!project.is_empty());}/// RULE: A picture's city and camera reach the library as its card draws them, and the library narrows by them — a declared column the view does not answer is never read as nothing.#[test]fn the_library_carries_a_pictures_city_and_camera_and_narrows_by_them() { let s = seeded(); s.h.run( "UPDATE cotton_photos SET place_city = 'Testville', camera_make = 'Synthcam', camera_model = 'S1' WHERE id = ?", &[t(&s.lake)], ); s.h.run("UPDATE cotton_videos SET place_city = 'Testville' WHERE id = ?", &[t(&s.film)]); let lake = s.get("media", &s.lake)["data"].clone(); assert_eq!(lake["place_city"], "Testville", "{lake}"); assert_eq!(lake["camera_make"], "Synthcam", "{lake}"); assert_eq!(lake["camera_model"], "S1", "{lake}"); assert_eq!( s.ids(json!({ "table": "media", "where": { "place_city": "Testville" } })), [s.film.as_str(), s.lake.as_str()] ); assert_eq!(s.ids(json!({ "table": "media", "where": { "camera_model": "S1" } })), [s.lake.as_str()]);}/// RULE: Every column a photos-engine view declares is answered by its SELECT and narrows, except the ones the engine fills beside each row and the ones only a phone answers (the library's `on_phone`), which are refused in words.#[test]fn every_declared_view_column_narrows_or_is_refused_in_words() { let s = seeded(); let filled_beside = ["albums", "people", "keep_facts", "copy_facts"]; for view in ["media", "album_item", "duplicate", "sighting"] { let definition = cotton_core::kit::table(view) .or_else(|| cotton_core::definitions::builtin_table_definitions().iter().find(|definition| definition.id == view).cloned()) .unwrap_or_else(|| panic!("{view} is defined")); for column in definition.columns.iter().map(|column| column.key.as_str()) { let args = json!({ "table": view, "where": { column: { "present": true } } }); if filled_beside.contains(&column) || cotton_core::definitions::is_device_answered_column(view, column) { let refusal = s.refused("list_records", args); assert!(refusal.contains(column), "{view}.{column}: {refusal}"); } else { let answer = call_tool_raw(&s.h, &s.secret, "list_records", args); assert!(!answer.is_error, "{view}.{column}: {}", answer.text); } } }}// ── photos and videos ───────────────────────────────────────────────────────/// RULE: A photo reads the albums it is in (never a dismissed one), and its list narrows by an album (a dismissed one matching nothing, as the albums it reads say) or by being in any album./// It also narrows by what an album can still take by hand — no screenshot, no picture of information, nothing already in it.#[test]fn a_photo_reads_its_albums_and_narrows_by_album_and_by_what_an_album_can_take() { let s = seeded(); let lake = s.get("photo", &s.lake); assert_eq!(lake["data"]["albums"], json!([s.open_album])); assert_eq!(lake["data"]["favourite"], true); assert_eq!(s.get("video", &s.film)["data"]["albums"], json!([s.open_album])); assert!(s.get("photo", &s.copy)["data"].get("albums").is_none()); assert_eq!( s.ids(json!({ "table": "photo", "where": { "albums": s.open_album } })), [s.lake.as_str()] ); assert_eq!( s.ids(json!({ "table": "video", "where": { "albums": s.open_album } })), [s.film.as_str()] ); assert!( s.ids(json!({ "table": "photo", "where": { "albums": s.dismissed_album } })).is_empty(), "the lake is in the dismissed album, which it does not read as one of its albums" ); assert_eq!( s.ids(json!({ "table": "photo", "where": { "albums": { "values": [s.dismissed_album, s.kept_album] } } })), [s.dog.as_str()] ); assert_eq!( s.ids(json!({ "table": "photo", "where": { "albums": { "present": true } } })), [s.dog.as_str(), s.lake.as_str()] ); let addable = s.list(json!({ "table": "photo", "where": { "addable_to": s.open_album } })); assert_eq!(ids(&addable), [s.dog.as_str(), s.copy.as_str()]); assert_eq!(addable["total"], 2); assert_eq!( s.ids(json!({ "table": "photo", "where": { "addable_to": s.kept_album } })), [s.copy.as_str(), s.lake.as_str()] ); assert_eq!(s.ids(json!({ "table": "photo", "query": "beach" })), [s.dog.as_str()]); let unknown = s.refused( "list_records", json!({ "table": "photo", "where": { "addable_to": "album:trip:2026-01-01" } }), ); assert!(unknown.contains("no album"), "{unknown}"); let dismissed = s.refused( "list_records", json!({ "table": "photo", "where": { "addable_to": s.dismissed_album } }), ); assert!(dismissed.contains("dismissed"), "{dismissed}"); let on_video = s.refused( "list_records", json!({ "table": "video", "where": { "addable_to": s.open_album } }), ); assert!(on_video.contains("addable_to"), "{on_video}"); let many = s.refused( "list_records", json!({ "table": "photo", "where": { "addable_to": { "values": [s.open_album] } } }), ); assert!(many.contains("one record id"), "{many}");}/// RULE: A picture reads the people confirmed in it, each once, and `where people` narrows the library by person — one, any of several, or anyone at all — so a person's page lists exactly the pictures whose page names them.#[test]fn a_picture_reads_its_people_and_narrows_by_person() { let s = seeded(); let person = |id: &str| { s.h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?,?,?,?,?)", &[t(id), t(&s.h.workspace_id), t(id), t("2026-09-01T00:00:00.000Z"), t("2026-09-01T00:00:00.000Z")], ); }; let face = |serial: u8, kind: &str, record: &str, person: Option<&str>| { s.h.run( "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, source_id, x, y, w, h, person_id, suggested_person_id, created_at, updated_at) \ VALUES (?,?,?,?,'apple',?,0,0,0.1,0.1,?,?,?,?)", &[ t(&format!("face:{serial}")), t(&s.h.workspace_id), t(kind), t(record), t(&format!("source:{serial}")), person.map(t).unwrap_or(SqlValue::Null), if person.is_none() { t("person:c") } else { SqlValue::Null }, t("2026-09-01T00:00:00.000Z"), t("2026-09-01T00:00:00.000Z"), ], ); }; person("person:a"); person("person:b"); person("person:c"); face(1, "photo", &s.lake, Some("person:a")); face(2, "photo", &s.lake, Some("person:a")); // the same person twice reads once face(3, "photo", &s.lake, Some("person:b")); face(4, "photo", &s.dog, None); // only suggested: not in the picture yet face(5, "video", &s.film, Some("person:b")); assert_eq!(s.get("photo", &s.lake)["data"]["people"], json!(["person:a", "person:b"])); assert!(s.get("photo", &s.dog)["data"].get("people").is_none()); assert_eq!(s.get("video", &s.film)["data"]["people"], json!(["person:b"])); assert_eq!(s.ids(json!({ "table": "photo", "where": { "people": "person:a" } })), vec![s.lake.clone()]); assert_eq!(s.ids(json!({ "table": "video", "where": { "people": "person:b" } })), vec![s.film.clone()]); assert!(s.ids(json!({ "table": "photo", "where": { "people": "person:c" } })).is_empty()); assert_eq!( s.ids(json!({ "table": "photo", "where": { "people": { "values": ["person:b", "person:c"] } } })), vec![s.lake.clone()] ); assert_eq!(s.ids(json!({ "table": "photo", "where": { "people": { "present": true } } })), vec![s.lake.clone()]); let nobody = s.ids(json!({ "table": "photo", "where": { "people": { "present": false } } })); assert!(nobody.contains(&s.dog) && !nobody.contains(&s.lake), "{nobody:?}");}/// RULE: A photo's and a video's caption and review note are written through update_photo and update_video and undone the same way; Keep clears the note with its author and moment; the favourite star is the owner's to mark (Cotton Photos, 12 Nov 2026), on the picture or on the library's print; what Cotton writes is refused.#[test]fn a_picture_takes_a_caption_and_keep_and_refuses_what_has_no_writer() { let s = seeded(); let captioned = s.call( "update_record", json!({ "table": "photo", "id": s.dog, "patch": { "caption": " Dog on the beach " } }), ); assert_eq!(captioned["change"]["byline"], "Claude"); assert_eq!(captioned["change"]["before"], json!({ "caption": null })); assert_eq!(captioned["change"]["after"], json!({ "caption": "Dog on the beach" })); assert_eq!(captioned["change"]["undoable"], true); let undone = s.call("undo", json!({ "change_id": captioned["change"]["id"] })); assert!(undone["record"]["data"].get("caption").is_none()); let noted = s.call( "update_record", json!({ "table": "photo", "id": s.lake, "patch": { "review_note": "Blurry — keep?" } }), ); assert_eq!(noted["record"]["data"]["review_by"], "Claude"); let kept = s.call( "update_record", json!({ "table": "photo", "id": s.lake, "patch": { "review_note": null } }), ); let after = &kept["record"]["data"]; assert!(after.get("review_note").is_none() && after.get("review_by").is_none()); assert!(after.get("review_at").is_none()); let film = s.call( "update_record", json!({ "table": "video", "id": s.film, "patch": { "caption": "Into the lake" } }), ); assert_eq!(film["record"]["data"]["caption"], "Into the lake"); // The lake is seeded a favourite (Apple Photos' star, imported). let unstarred = s.call( "update_record", json!({ "table": "photo", "id": s.lake, "patch": { "favourite": false } }), ); assert_eq!(unstarred["record"]["data"]["favourite"], false); let starred = s.call( "update_record", json!({ "table": "media", "id": s.lake, "patch": { "favourite": true } }), ); assert_eq!(s.get("photo", &s.lake)["data"]["favourite"], true, "the library's print stars the picture itself: {starred}"); let film_starred = s.call("update_record", json!({ "table": "media", "id": s.film, "patch": { "favourite": true } })); assert_eq!(s.get("video", &s.film)["data"]["favourite"], true, "{film_starred}"); // Cotton Photos' Favourites and Videos read the library by these columns. let favourites = s.ids(json!({ "table": "media", "where": { "favourite": true } })); assert!(favourites.contains(&s.lake) && favourites.contains(&s.film) && !favourites.contains(&s.dog), "{favourites:?}"); assert_eq!(s.get("media", &s.lake)["data"]["favourite"], true, "the library reads a star as yes or no"); assert_eq!(s.ids(json!({ "table": "media", "where": { "kind": "video" } })), vec![s.film.clone()]); let library = s.refused("update_record", json!({ "table": "media", "id": s.lake, "patch": { "caption": "x" } })); assert!(library.contains("own table"), "{library}"); let summary = s.refused( "update_record", json!({ "table": "photo", "id": s.lake, "patch": { "summary": "mine" } }), ); assert!(summary.contains("Cotton sets it itself"), "{summary}"); let byline = s.refused( "update_record", json!({ "table": "photo", "id": s.lake, "patch": { "review_by": "me" } }), ); assert!(byline.contains("Cotton sets it itself"), "{byline}"); let made = s.refused("create_record", json!({ "table": "photo", "data": { "caption": "x" } })); assert!(made.contains("enters as its bytes"), "{made}");}/// RULE: Deleting a photo, a video or a library picture moves it to the bin through remove_photo or remove_video — "Moved <name> to the bin" (the Bin's tile on Home, the default), undoable, its key alive and its bytes kept — and the Undo brings it back.#[test]fn deleting_a_picture_moves_it_to_the_bin_and_undo_brings_it_back() { let s = seeded(); let key = s.get("photo", &s.dog)["data"]["key"].as_str().unwrap().to_string(); s.h.services.media.put(&key, vec![1, 2, 3]); let deleted = s.call("delete_record", json!({ "table": "photo", "id": s.dog })); assert_eq!(deleted["change"]["verb"], "delete"); assert_eq!(deleted["change"]["undoable"], true, "{deleted}"); let said = deleted["change"]["receipt"]["said"].as_str().unwrap(); assert!(said.starts_with("Moved ") && said.ends_with(" to the bin"), "{said}"); assert!(deleted["record"]["deleted_at"].is_string(), "{deleted}"); // Nothing leaves while it waits in the bin: no erasure, no unlink. assert!(!s.h.with(|db| cotton_store::media_erasure::is_dead(db, &key)).expect("reads"), "a binned picture's key died"); assert!(s.h.with(cotton_store::media_erasure::pending_unlinks).expect("reads").is_empty(), "a binned picture's key was queued"); assert_eq!(s.h.services.media.get(&key), Some(vec![1, 2, 3]), "the tool deleted the bytes itself"); assert!(s.get("photo", &s.dog)["deleted_at"].is_string(), "a binned photo reads as not deleted"); assert!(!s.ids(json!({ "table": "photo" })).contains(&s.dog), "a binned photo is still listed"); s.call("undo", json!({ "change_id": deleted["change"]["id"] })); let back = s.get("photo", &s.dog); assert_eq!((back["data"]["key"].clone(), back["deleted_at"].clone()), (json!(key), Value::Null), "Undo did not bring the photo back"); s.call("delete_record", json!({ "table": "media", "id": s.film })); assert_eq!( s.h.count("SELECT count(*) AS c FROM cotton_videos WHERE trashed_at IS NOT NULL", &[]), 1, "the library's delete reached the film's own tool" ); let wrong = s.refused("delete_record", json!({ "table": "photo", "id": s.film })); assert!(wrong.contains("is no longer here"), "{wrong}");}// ── albums ──────────────────────────────────────────────────────────────────/// Who named an album, read off the file — no generic read answers it.fn named_by(s: &Seeded, album: &str) -> String { for by in ["derived", "user"] { if s.h.count( "SELECT count(*) AS c FROM cotton_media_albums WHERE id = ? AND title_by = ?", &[t(album), t(by)], ) == 1 { return by.to_string(); } } panic!("{album} has no title_by");}/// An album's state and whether it carries a decision moment, off the file.fn decided(s: &Seeded, album: &str) -> (String, bool) { let state = s.get("album", album)["data"]["state"].as_str().unwrap().to_string(); let stamped = s.h.count( "SELECT count(*) AS c FROM cotton_media_albums WHERE id = ? AND decided_at IS NOT NULL", &[t(album)], ) == 1; (state, stamped)}/// RULE: Albums list open first then kept, a dismissed one left out unless the state is asked for, each with its cover's print, the print's size and how many pictures it holds.#[test]fn albums_list_open_first_without_the_dismissed_and_answer_their_print() { let s = seeded(); let listed = s.list(json!({ "table": "album" })); assert_eq!(ids(&listed), [s.open_album.as_str(), s.kept_album.as_str()]); assert_eq!(listed["total"], 2); let open = &listed["records"][0]["data"]; assert_eq!(open["member_count"], 2); assert_eq!(open["cover_id"], json!(s.lake)); assert!(open["cover_key"].as_str().unwrap().ends_with(&format!("{}.jpg", hash(1)))); assert_eq!(open["cover_width"], 4032); assert_eq!(open["cover_height"], 3024); assert_eq!(open["home_label"], "Example City"); assert_eq!( s.ids(json!({ "table": "album", "where": { "state": "dismissed" } })), [s.dismissed_album.as_str()] ); assert_eq!( s.get("album", &s.dismissed_album)["data"]["state"], "dismissed", "a dismissed album still reads by id" );}/// RULE: An album is renamed and re-covered through update_album and decided through decide_album — a rename keeps an open suggestion, a dismissed one is brought back before it is renamed — and each is undone the same way./// The undo of a rename gives the name back to whoever gave it; anything Cotton sets, a clear, a create and a delete are refused.#[test]fn an_album_is_renamed_and_decided_through_its_own_tools() { let s = seeded(); let renamed = s.call( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "title": "Lake weekend" } }), ); let after = &renamed["change"]["after"]; assert_eq!(after["title"], "Lake weekend"); assert_eq!(after["state"], "kept", "a name is a decision"); assert_eq!(after["@title_by"], json!({ "was": "derived", "now": "user" })); assert!(renamed["change"]["before"].get("@title_by").is_none()); assert_eq!(named_by(&s, &s.open_album), "user"); let undone = s.call("undo", json!({ "change_id": renamed["change"]["id"] })); assert_eq!(undone["record"]["data"]["title"], "Example lake trip"); assert_eq!(undone["record"]["data"]["state"], "open"); assert_eq!(named_by(&s, &s.open_album), "derived", "Cotton's name is Cotton's again"); assert_eq!( undone["change"]["after"]["@title_by"], json!({ "was": "user", "now": "derived" }) ); let redone = s.call("undo", json!({ "change_id": undone["change"]["id"] })); assert_eq!(redone["record"]["data"]["title"], "Lake weekend"); assert_eq!(named_by(&s, &s.open_album), "user"); s.call("undo", json!({ "change_id": redone["change"]["id"] })); assert_eq!(named_by(&s, &s.open_album), "derived"); let recovered = s.call( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "cover_id": s.film } }), ); assert!(recovered["record"]["data"]["cover_key"].as_str().unwrap().contains("/posters/")); let dismissed = s.call( "update_record", json!({ "table": "album", "id": s.kept_album, "patch": { "state": "dismissed" } }), ); assert_eq!(dismissed["change"]["after"]["state"], "dismissed"); assert!(!s.ids(json!({ "table": "album" })).contains(&s.kept_album)); let back = s.call( "update_record", json!({ "table": "album", "id": s.kept_album, "patch": { "state": "kept", "title": "Beach" } }), ); assert_eq!(back["record"]["data"]["state"], "kept"); assert_eq!(back["record"]["data"]["title"], "Beach"); let cleared = s.refused( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "title": null } }), ); assert!(!cleared.is_empty()); let kind = s.refused( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "kind": "event" } }), ); assert!(kind.contains("Cotton sets it itself"), "{kind}"); let count = s.refused( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "member_count": 9 } }), ); assert!(count.contains("Cotton sets it itself"), "{count}"); let gone = s.refused("delete_record", json!({ "table": "album", "id": s.open_album })); assert!(gone.contains("never deleted"), "{gone}"); let made = s.refused( "create_record", json!({ "table": "album", "data": { "title": "Mine" } }), ); assert!(made.contains("create_album"), "{made}");}/// RULE: An album's pictures list in the order they were taken, a film by its poster; one is put in and taken out through update_album, and the change says what that moved beside the picture — the suggestion it kept, the cover it re-picked./// The put-in is undone by taking it out — and a screenshot, a picture already there, an edit and the undo of a take-out are refused.#[test]fn an_albums_pictures_go_in_and_come_out_through_update_album() { let s = seeded(); let listed = s.list(json!({ "table": "album_item", "where": { "album_id": s.open_album } })); let pictures: Vec<&str> = listed["records"] .as_array() .unwrap() .iter() .map(|record| record["data"]["record_id"].as_str().unwrap()) .collect(); assert_eq!(pictures, [s.lake.as_str(), s.film.as_str()]); assert_eq!(listed["total"], 2); let mut lakes = vec![ media_album_item_id(&s.open_album, &s.lake), media_album_item_id(&s.dismissed_album, &s.lake), ]; lakes.sort(); assert_eq!( s.ids(json!({ "table": "album_item", "where": { "record_id": s.lake } })), lakes, "one picture in two albums lists in the order of the items' own ids" ); assert_eq!(listed["records"][1]["data"]["kind"], "video"); assert_eq!(listed["records"][1]["data"]["duration_ms"], 42000); assert!(listed["records"][1]["data"]["key"].as_str().unwrap().contains("/posters/")); let added = s.call( "create_record", json!({ "table": "album_item", "data": { "album_id": s.kept_album, "record_id": s.copy } }), ); let item = media_album_item_id(&s.kept_album, &s.copy); assert_eq!(added["record"]["id"], json!(item)); assert_eq!(added["change"]["verb"], "create"); assert_eq!(added["change"]["undoable"], true); assert_eq!(s.get("album", &s.kept_album)["data"]["member_count"], 2); let album = &added["change"]["after"]["@album"]; assert_eq!(album["was"]["state"], "kept"); assert_eq!(album["now"]["state"], "kept", "a kept album stays kept"); assert_eq!(album["now"]["members"], json!([s.dog, s.copy])); s.call("undo", json!({ "change_id": added["change"]["id"] })); assert_eq!(s.get("album", &s.kept_album)["data"]["member_count"], 1); let lake_item = media_album_item_id(&s.open_album, &s.lake); let removed = s.call("delete_record", json!({ "table": "album_item", "id": lake_item })); assert_eq!(removed["change"]["undoable"], false); let album = &removed["change"]["before"]["@album"]; assert_eq!( (&album["was"]["state"], &album["now"]["state"]), (&json!("open"), &json!("kept")), "taking a picture out of a suggestion keeps it" ); assert_eq!( (&album["was"]["cover_id"], &album["now"]["cover_id"]), (&json!(s.lake), &json!(s.film)), "taking the cover out picks another" ); assert_eq!(s.get("album", &s.open_album)["data"]["cover_id"], json!(s.film)); assert_eq!(s.get("album", &s.open_album)["data"]["member_count"], 1); assert!(s.get("photo", &s.lake)["data"].get("albums").is_none(), "the picture stays in Photos"); let undo = s.refused("undo", json!({ "change_id": removed["change"]["id"] })); assert!(undo.contains("create_record"), "{undo}"); let screenshot = s.refused( "create_record", json!({ "table": "album_item", "data": { "album_id": s.kept_album, "record_id": s.screenshot } }), ); assert!(screenshot.contains("screenshot"), "{screenshot}"); let twice = s.refused( "create_record", json!({ "table": "album_item", "data": { "album_id": s.kept_album, "record_id": s.dog } }), ); assert!(twice.contains("already in"), "{twice}"); let wrong_kind = s.refused( "create_record", json!({ "table": "album_item", "data": { "album_id": s.kept_album, "record_id": s.copy, "kind": "video" } }), ); assert!(wrong_kind.contains("is a photo"), "{wrong_kind}"); let edit = s.refused( "update_record", json!({ "table": "album_item", "id": media_album_item_id(&s.kept_album, &s.dog), "patch": { "caption": "x" } }), ); assert!(edit.contains("never changed"), "{edit}");}/// RULE: Putting a picture in an open suggestion keeps it, and the change holds the album whole before and after; its undo takes the picture out AND opens the suggestion again through decide_album, with no decision moment left./// The undo is refused, with nothing written, unless the album is wholly as the put-in left it (a cover, a name, a keep-open-keep since all refuse) and unless the take-out would leave it exactly as it was.#[test]fn undoing_a_put_in_opens_the_suggestion_it_kept_or_is_refused() { let s = seeded(); let put_in = |album: &str, record: &str| { s.call( "create_record", json!({ "table": "album_item", "data": { "album_id": album, "record_id": record } }), ) }; let patch = |album: &str, patch: Value| { s.call("update_record", json!({ "table": "album", "id": album, "patch": patch })); }; let undo_refused = |added: &Value| { let refused = s.refused("undo", json!({ "change_id": added["change"]["id"] })); assert!(refused.contains("cannot be undone") || refused.contains("changed since"), "{refused}"); refused }; let added = put_in(&s.open_album, &s.copy); let album = &added["change"]["after"]["@album"]; assert_eq!((&album["was"]["state"], &album["now"]["state"]), (&json!("open"), &json!("kept"))); assert_eq!(album["was"]["decided_at"], Value::Null); assert_eq!(album["now"]["cover_id"], json!(s.lake), "the cover did not move"); assert_eq!(added["change"]["before"], Value::Null, "a create has no before"); assert_eq!(decided(&s, &s.open_album), ("kept".to_string(), true)); let undone = s.call("undo", json!({ "change_id": added["change"]["id"] })); assert_eq!(undone["record"], Value::Null); assert_eq!(decided(&s, &s.open_album), ("open".to_string(), false), "open again, undecided"); assert_eq!(s.get("album", &s.open_album)["data"]["member_count"], 2); let back = &undone["change"]["before"]["@album"]; assert_eq!((&back["was"]["state"], &back["now"]["state"]), (&json!("kept"), &json!("open"))); // The person's own cover and name since: undoing would leave an OPEN // suggestion carrying their choices, which the nightly pass overwrites. let added = put_in(&s.open_album, &s.copy); patch(&s.open_album, json!({ "cover_id": s.copy })); patch(&s.open_album, json!({ "title": "Mine now" })); let refused = undo_refused(&added); assert!(refused.contains("changed after the picture went in"), "{refused}"); assert_eq!(s.get("album", &s.open_album)["data"]["member_count"], 3, "nothing was taken out"); assert_eq!(s.get("album", &s.open_album)["data"]["state"], "kept"); // Kept, re-opened and kept again since: the same state, a new decision. let added = put_in(&s.kept_album, &s.copy); patch(&s.kept_album, json!({ "state": "open" })); patch(&s.kept_album, json!({ "state": "kept" })); let refused = undo_refused(&added); assert!(refused.contains("changed after the picture went in"), "{refused}"); assert_eq!(s.get("album", &s.kept_album)["data"]["member_count"], 2);}/// RULE: The undo of a put-in is refused in words when taking the picture out cannot leave the album as it was — the album's cover was that very picture before it went in, and taking it out would pick another.#[test]fn a_put_in_whose_take_out_cannot_restore_the_album_is_not_undone() { let s = seeded(); // A cover that is not one of the album's pictures: no engine write makes // one, but a synced or older file may hold it. s.h.run( "UPDATE cotton_media_albums SET cover_id = ? WHERE id = ?", &[t(&s.copy), t(&s.kept_album)], ); let added = s.call( "create_record", json!({ "table": "album_item", "data": { "album_id": s.kept_album, "record_id": s.copy } }), ); let refused = s.refused("undo", json!({ "change_id": added["change"]["id"] })); assert!(refused.contains("cover_id other than it was before"), "{refused}"); assert_eq!(s.get("album", &s.kept_album)["data"]["member_count"], 2, "nothing was taken out"); assert_eq!(s.get("album", &s.kept_album)["data"]["cover_id"], json!(s.copy));}// ── duplicates ──────────────────────────────────────────────────────────────/// RULE: Duplicates list the open pairs grouped by the picture to keep, each side's print and facts in words; a pair is answered through decide_duplicate and the answer undone the same way; a delete, a create and anything but the state are refused.#[test]fn duplicates_are_the_open_pairs_answered_through_decide_duplicate() { let s = seeded(); let listed = s.list(json!({ "table": "duplicate" })); assert_eq!(ids(&listed), [s.open_pair.as_str()]); assert_eq!(listed["total"], 1); let pair = &listed["records"][0]["data"]; assert_eq!(pair["keep_id"], json!(s.lake)); assert_eq!(pair["copy_id"], json!(s.copy)); assert_eq!(pair["keep_facts"], "4032 × 3024 · 2.1 MB · Favourite"); assert_eq!(pair["copy_facts"], "3024 × 4032 · 1.7 MB"); assert_eq!(pair["distance"], 3); assert_eq!(pair["method"], "phash"); assert!(pair["copy_key"].as_str().unwrap().ends_with(&format!("{}.jpg", hash(5)))); assert_eq!( s.ids(json!({ "table": "duplicate", "where": { "state": "dismissed" } })), [s.dismissed_pair.as_str()] ); let answered = s.call( "update_record", json!({ "table": "duplicate", "id": s.open_pair, "patch": { "state": "confirmed" } }), ); // The pair now reads when it was decided, so the change says that too. assert_eq!(answered["change"]["before"], json!({ "decided_at": null, "state": "open" })); let after = answered["change"]["after"].as_object().unwrap(); assert_eq!(after.keys().collect::<Vec<_>>(), ["decided_at", "state"], "{after:?}"); assert_eq!(after["state"], "confirmed"); assert!(after["decided_at"].as_str().is_some_and(|at| at.starts_with("20")), "{after:?}"); let left = s.list(json!({ "table": "duplicate" })); assert_eq!(left["total"], 0); s.call("undo", json!({ "change_id": answered["change"]["id"] })); assert_eq!(s.ids(json!({ "table": "duplicate" })), [s.open_pair.as_str()]); let gone = s.refused("delete_record", json!({ "table": "duplicate", "id": s.open_pair })); assert!(gone.contains("never deleted"), "{gone}"); let distance = s.refused( "update_record", json!({ "table": "duplicate", "id": s.open_pair, "patch": { "distance": 1 } }), ); assert!(distance.contains("the Mac's to say"), "{distance}"); let made = s.refused( "create_record", json!({ "table": "duplicate", "data": { "keep_id": s.lake, "copy_id": s.dog } }), ); assert!(made.contains("proposes"), "{made}"); let facts = s.refused( "list_records", json!({ "table": "duplicate", "where": { "keep_facts": "x" } }), ); assert!(facts.contains("cannot be narrowed"), "{facts}");}/// RULE: A pair of films reads as a pair of photos does — each side's poster as its print and its facts in words — and is answered the same way.#[test]fn a_pair_of_films_reads_its_posters_and_facts() { let s = seeded(); let second = insert_film(&s.h, 7); let pair = media_duplicate_id(&s.film, &second); s.h.run( "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, copy_id, \ distance, method, state, created_at, updated_at) \ VALUES (?, ?, 'video', ?, ?, 2, 'featureprint', 'open', ?, ?)", &[t(&pair), t(&s.h.workspace_id), t(&s.film), t(&second), t(AT), t(AT)], ); let listed = s.list(json!({ "table": "duplicate", "where": { "keep_id": s.film } })); assert_eq!(ids(&listed), [pair.as_str()]); let films = &listed["records"][0]["data"]; assert!(films["keep_key"].as_str().unwrap().ends_with(&format!("posters/{}.jpg", hash(6)))); assert!(films["copy_key"].as_str().unwrap().ends_with(&format!("posters/{}.jpg", hash(7)))); assert_eq!(films["keep_facts"], "1920 × 1080 · 8.6 MB"); assert_eq!(films["copy_facts"], "1920 × 1080 · 8.6 MB"); assert_eq!(s.list(json!({ "table": "duplicate" }))["total"], 2); let answered = s.call( "update_record", json!({ "table": "duplicate", "id": pair, "patch": { "state": "dismissed" } }), ); assert_eq!(answered["record"]["data"]["state"], "dismissed");}// ── sightings ───────────────────────────────────────────────────────────────/// RULE: Where a photo or a video was seen lists by its link, a chat by its own name, and is read only.#[test]fn a_pictures_sightings_list_by_its_link_and_are_read_only() { let s = seeded(); let photo = s.list(json!({ "table": "sighting", "where": { "photo_id": s.lake } })); assert_eq!(ids(&photo), ["s-lake"]); let seen = &photo["records"][0]["data"]; assert_eq!(seen["source"], "message"); assert_eq!(seen["thread_name"], "Example family"); assert!(seen.get("video_id").is_none()); let film = s.list(json!({ "table": "sighting", "where": { "video_id": s.film } })); assert_eq!(ids(&film), ["s-film"]); assert_eq!(film["records"][0]["data"]["source"], "library"); assert!(film["records"][0]["data"].get("thread_name").is_none()); assert_eq!(s.get("sighting", "s-film")["data"]["video_id"], json!(s.film)); let write = s.refused( "update_record", json!({ "table": "sighting", "id": "s-lake", "patch": { "thread_name": "x" } }), ); assert!(write.contains("read only"), "{write}");}// ── the tools a generic verb stands in for ─────────────────────────────────/// RULE: A generic verb over the photos engine's tables reaches, by name, every existing tool it stands in for, so a run that refuses a tool is never read or written round.#[test]fn a_generic_verb_names_every_media_tool_it_stands_in_for() { use cotton_tools::mcp::handlers::tables::tools_reached; let reached = |tool: &str, table: &str| tools_reached(tool, table); for wanted in ["list_photos", "list_videos"] { assert!(reached("list_records", "media").contains(&wanted), "{wanted}"); } assert!(reached("list_records", "duplicate").contains(&"list_duplicates")); assert!(reached("get_record_by_table", "album_item").contains(&"get_album")); assert!(reached("list_records", "sighting").contains(&"get_photo")); for table in ["photo", "video"] { assert!(reached("get_record_by_table", table).contains(&"list_albums"), "{table}"); assert!(reached("list_records", table).contains(&"list_albums"), "{table}"); } assert!( !reached("delete_record", "album_item").contains(&"decide_album"), "a plain take-out never decides; the undo that re-opens asks for decide_album itself" ); for wanted in ["remove_photo", "remove_video"] { assert!(reached("delete_record", "media").contains(&wanted), "{wanted}"); } assert!(reached("update_record", "photo").contains(&"update_photo")); assert!(reached("update_record", "video").contains(&"update_video")); assert!(reached("update_record", "duplicate").contains(&"decide_duplicate")); assert!(reached("create_record", "album_item").contains(&"update_album")); assert!(reached("delete_record", "album_item").contains(&"update_album")); let album = reached("update_record", "album"); assert!(album.contains(&"update_album") && album.contains(&"decide_album"), "{album:?}");}/// RULE: Keeping an album Cotton suggested is a decision, not an add: its receipt says Kept and the album's name, and its Undo returns the suggestion to undecided — open, asked again — never dismissed; dismissing is its own choice with its own Undo.#[test]fn undo_of_keeping_a_suggested_album_asks_again() { let s = seeded(); let kept = s.call( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "state": "kept" } }), ); assert_eq!(kept["record"]["data"]["state"], "kept", "{kept}"); assert_eq!(kept["change"]["receipt"]["said"], "Kept Example lake trip"); assert_eq!(kept["change"]["undoable"], true); let undone = s.call("undo", json!({ "change_id": kept["change"]["id"] })); assert_eq!(undone["record"]["data"]["state"], "open", "the suggestion is asked again: {undone}"); assert!(s.ids(json!({ "table": "album", "where": { "state": "open" } })).contains(&s.open_album)); assert!(!s.ids(json!({ "table": "album", "where": { "state": "dismissed" } })).contains(&s.open_album)); // Dismissing is its own choice: said as the state column's own word for // it (the album definition's label, "Not this"), and undone back to undecided. let dismissed = s.call( "update_record", json!({ "table": "album", "id": s.open_album, "patch": { "state": "dismissed" } }), ); assert_eq!(dismissed["change"]["receipt"]["said"], "Not this Example lake trip"); let back = s.call("undo", json!({ "change_id": dismissed["change"]["id"] })); assert_eq!(back["record"]["data"]["state"], "open", "{back}");}