//! Suggested albums over MCP (schema v42, spec §D6, §D9).//!//! The server PROPOSES (the albums worker) and the person DECIDES — through//! the app, or through an assistant acting for them here. Five tools://!//! `list_albums` / `get_album` — read;//! `decide_album` — keep, dismiss, or re-open a proposal;//! `update_album` — rename, re-cover, add or remove pictures. An//! edit to an OPEN proposal keeps it first, in//! the same write: a name is a decision;//! `create_album` — a person-made album, born kept, every member//! the person's, no proposal step.//!//! ONE WRITER PER COLUMN (D5). Everything here writes as the person: `title_by`//! and `added_by` become `user`, and the nightly pass never touches a kept row//! again. Nothing here deletes an album — `dismiss` is the album's own state.//!//! SCREENSHOTS AND UTILITY IMAGES NEVER ENTER (D1), by the pass or by hand://! `album_admits_by_hand` is the one rule, and the refusal says so in a//! sentence.usecrate::mcp::writer::Retract;use cotton_core::rules::media::albums::{ album_admits_by_hand, album_people, local_instant, zone_offset_seconds,};use cotton_store::driver::Row;use cotton_store::protocol::derived_id::{media_album_id, media_album_item_id};use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};usecrate::mcp::handlers::common::{ bounded_limit, fail, insert_row, iso_timestamp, now_iso, optional_enum, optional_string, parse_ms, quoted, update_row, workspace_timezone_or_null, Valid,};usecrate::mcp::handlers::media_tools::{is_media_id, rint, rtext, rtext_any};usecrate::mcp::protocol::ToolFailure;pubfn handlers() -> HandlerGroup { &[ ("list_albums", list_albums), ("get_album", get_album), ("decide_album", decide_album), ("update_album", update_album), ("create_album", create_album), ]}const ALBUMS: &str = "cotton_media_albums";const ITEMS: &str = "cotton_media_album_items";/// The album places whose picture is not in the bin.const BINNED_LEFT_OUT: &str = " AND record_id NOT IN (SELECT id FROM cotton_photos WHERE trashed_at IS NOT NULL \ UNION ALL SELECT id FROM cotton_videos WHERE trashed_at IS NOT NULL)";/// ENGINE SHIM — `MEDIA_ALBUM_STATES` (`packages/core/src/constants.ts`). The/// KINDS are already `cotton_core::constants::MediaAlbumKind`; the states have/// no reader outside this group yet, and land in `constants.rs` beside them the/// day one appears.const ALBUM_STATES: &[&str] = &["open", "kept", "dismissed"];const ALBUM_KINDS: &[&str] = &["trip", "event"];const DECISIONS: &[&str] = &["keep", "dismiss", "open"];/// Mirrors nothing in the file — a title is one line the person typed.const ALBUM_TITLE_MAX: usize = 120;const ALBUM_PICTURES_MAX: usize = 500;// ── the validators ──────────────────────────────────────────────────────────/// `album:` then its kind and its moment — `ALBUM_ID_RE`, as a check rather/// than a regex: `album:(trip|event):YYYY-MM-DD` with an optional `THH`.fn is_album_id(value: &str) -> bool {letSome(rest) = value.strip_prefix("album:") else {returnfalse; };letSome((kind, moment)) = rest.split_once(':') else {returnfalse; };if !ALBUM_KINDS.contains(&kind) {returnfalse; }let (date, hour) = match moment.split_once('T') {Some((date, hour)) => (date, Some(hour)),None => (moment, None), };let date_ok = date.len() == 10 && date.bytes().enumerate().all(|(index, byte)| match index {4 | 7 => byte == b'-', _ => byte.is_ascii_digit(), });let hour_ok = match hour {None => true,Some(hour) => hour.len() == 2 && hour.bytes().all(|byte| byte.is_ascii_digit()), }; date_ok && hour_ok}fn require_album_id(args: &Map<String, Value>) -> Valid<String> {match optional_string(args, "id") {Some(value) if is_album_id(&value) => Ok(value), _ => fail("id must be an album's id — \"album:\" then its kind and its moment, as list_albums \ gives it", ), }}/// `PICTURE_ID_RE` — a photo's or a video's id.fn is_picture_id(value: &str) -> bool { is_media_id(value, "photo") || is_media_id(value, "video")}fn picture_id_list( args: &Map<String, Value>, key: &str, required: bool,) -> Valid<Option<Vec<String>>> {letSome(raw) = args.get(key) else {returnif required { fail(format!("{key} is required")) } else {Ok(None) }; };let bad_shape = format!("{key} must be an array of 1 to {ALBUM_PICTURES_MAX} photo or video ids");letSome(items) = raw.as_array() else {return fail(bad_shape); };if items.is_empty() || items.len() > ALBUM_PICTURES_MAX {return fail(bad_shape); }letmut value = Vec::with_capacity(items.len());for item in items {match item.as_str() {Some(entry) if is_picture_id(entry) => value.push(entry.to_string()), _ => {return fail(format!("{key} entries must be photo or video ids — \"photo:\" or \"video:\" then the \ 64-character content hash" )) } } }Ok(Some(value))}fn album_title(args: &Map<String, Value>, required: bool) -> Valid<Option<String>> {letSome(raw) = args.get("title") else {returnif required { fail("title is required") } else {Ok(None) }; };letSome(text) = raw.as_str().filter(|value| !value.trim().is_empty()) else {return fail("title must be a non-empty string"); };let value = text.split_whitespace().collect::<Vec<_>>().join(" ");if value.chars().count() > ALBUM_TITLE_MAX {return fail(format!("title must be at most {ALBUM_TITLE_MAX} characters" )); }Ok(Some(value))}pubstructListAlbumsArgs {pub state: Option<String>,pub kind: Option<String>,pub since: Option<String>,pub until: Option<String>,pub limit: i64,}pubfn validate_list_albums(args: &Map<String, Value>) -> Valid<ListAlbumsArgs> {let state = optional_enum(args, "state", ALBUM_STATES)?;let kind = optional_enum(args, "kind", ALBUM_KINDS)?;letmut window: [Option<String>; 2] = [None, None];for (index, key) in ["since", "until"].into_iter().enumerate() {letSome(raw) = optional_string(args, key) else {continue; };match iso_timestamp(&raw) {Some(parsed) => window[index] = Some(parsed),None => return fail(format!("{key} must be an ISO-8601 instant")), } }let [since, until] = window;Ok(ListAlbumsArgs { state, kind, since, until, limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST), })}pubstructUpdateAlbumArgs {pub id: String,pub title: Option<String>,pub cover_id: Option<String>,pub add: Option<Vec<String>>,pub remove: Option<Vec<String>>,}pubfn validate_update_album(args: &Map<String, Value>) -> Valid<UpdateAlbumArgs> {let id = require_album_id(args)?;let title = album_title(args, false)?;let cover_id = optional_string(args, "coverId");ifletSome(cover_id) = &cover_id {if !is_picture_id(cover_id) {return fail("coverId must be a photo or video id"); } }let add = picture_id_list(args, "add", false)?;let remove = picture_id_list(args, "remove", false)?;if title.is_none() && cover_id.is_none() && add.is_none() && remove.is_none() {return fail("nothing to change — pass title, coverId, add or remove"); }Ok(UpdateAlbumArgs { id, title, cover_id, add, remove, })}pubstructCreateAlbumArgs {pub kind: String,pub title: String,pub photo_ids: Vec<String>,pub cover_id: Option<String>,}pubfn validate_create_album(args: &Map<String, Value>) -> Valid<CreateAlbumArgs> {letSome(kind) = optional_enum(args, "kind", ALBUM_KINDS)? else {return fail("kind is required — trip or event"); };let title = album_title(args, true)?.unwrap_or_default();let photo_ids = picture_id_list(args, "photoIds", true)?.unwrap_or_default();let cover_id = optional_string(args, "coverId");ifletSome(cover_id) = &cover_id {if !is_picture_id(cover_id) {return fail("coverId must be a photo or video id"); } }Ok(CreateAlbumArgs { kind, title, photo_ids, cover_id, })}// ── reads ───────────────────────────────────────────────────────────────────fn album_row(ctx: &Ctx<'_>, id: &str) -> Result<Row, ToolFailure> { ctx.db() .get( &format!("SELECT * FROM {ALBUMS} WHERE id = ? AND workspace_id = ?"), &[SqlValue::Text(id.to_string()),SqlValue::Text(ctx.workspace_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new(format!("no album with id {id}")))}/// An album's places, in order. `shown`: only the pictures out of the bin —/// what an answer reads; an edit reads every place, so a picture waiting in/// the bin keeps its place (and the cover) for its restore.fn items_of(ctx: &Ctx<'_>, album_id: &str, shown: bool) -> Result<Vec<Row>, ToolFailure> {let shown = if shown { BINNED_LEFT_OUT } else { "" }; ctx.db() .all( &format!("SELECT id, record_kind, record_id, added_by, sort_at FROM {ITEMS} WHERE workspace_id = ? AND album_id = ?{shown} ORDER BY sort_at ASC, record_id ASC" ), &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(album_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))}/// Linked people across a set of pictures — the title rule's own reading.fn people_of(ctx: &Ctx<'_>, record_ids: &[String]) -> Result<Vec<String>, ToolFailure> {if record_ids.is_empty() {returnOk(Vec::new()); }let holes = vec!["?"; record_ids.len()].join(", ");let sql = format!("SELECT f.record_id, f.person_id, p.full_name FROM cotton_media_faces f JOIN cotton_people p ON p.id = f.person_id WHERE f.workspace_id = ? AND f.person_id IS NOT NULL AND f.record_id IN ({holes})" );letmut params: Vec<SqlValue> = vec![SqlValue::Text(ctx.workspace_id.to_string())]; params.extend(record_ids.iter().map(|id| SqlValue::Text(id.clone())));let faces = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?;letmut by_record: std::collections::HashMap<String, Vec<String>> = Default::default();letmut names: std::collections::HashMap<String, String> = Default::default();for face in &faces {let (Some(record_id), Some(person_id)) = (rtext(face, "record_id"), rtext(face, "person_id"))else {continue; }; by_record .entry(record_id) .or_default() .push(person_id.clone());ifletSome(name) = rtext(face, "full_name") { names.insert(person_id, name); } }let per_member: Vec<Vec<String>> = record_ids .iter() .map(|id| by_record.get(id).cloned().unwrap_or_default()) .collect();// `.1` is the NAMES half of the pair; `.0` is the ids, which no// caller here shows.Ok(album_people(&per_member, |id| names.get(id).cloned()).1)}fn project_slugs_of(ctx: &Ctx<'_>, album_id: &str) -> Result<Vec<String>, ToolFailure> {Ok(ctx .db() .all("SELECT p.slug FROM cotton_project_links l JOIN cotton_memory_projects p ON p.id = l.project_id WHERE l.workspace_id = ? AND l.record_kind = 'album' AND l.record_id = ? ORDER BY p.slug", &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(album_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .iter() .filter_map(|row| rtext(row, "slug")) .collect())}fn album_out(row: &Row, items: &[Row], people: &[String]) -> Map<String, Value> {let field = |column: &str| rtext_any(row, column).map_or(Value::Null, Value::from);letmut out = Map::new(); out.insert("id".to_string(), field("id")); out.insert("kind".to_string(), field("kind")); out.insert("state".to_string(), field("state")); out.insert("decidedAt".to_string(), field("decided_at")); out.insert("title".to_string(), field("title")); out.insert("titleBy".to_string(), field("title_by")); out.insert("startsAt".to_string(), field("starts_at")); out.insert("endsAt".to_string(), field("ends_at")); out.insert("homeLabel".to_string(), field("home_label")); out.insert("coverId".to_string(), field("cover_id")); out.insert("members".to_string(), Value::from(items.len())); out.insert("people".to_string(),Value::Array( people .iter() .map(|value| Value::from(value.as_str())) .collect(), ), ); out.insert("createdAt".to_string(), field("created_at")); out.insert("updatedAt".to_string(), field("updated_at")); out}pubfn list_albums(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_list_albums(args)?;letmut where_parts = vec!["workspace_id = ?".to_string()];letmut params: Vec<SqlValue> = vec![SqlValue::Text(ctx.workspace_id.to_string())];match &args.state {Some(state) => { where_parts.push("state = ?".to_string()); params.push(SqlValue::Text(state.clone())); }// A dismissed album is a tombstone: listed only when asked for by name.None => where_parts.push("state IN ('open', 'kept')".to_string()), }ifletSome(kind) = &args.kind { where_parts.push("kind = ?".to_string()); params.push(SqlValue::Text(kind.clone())); }ifletSome(since) = &args.since { where_parts.push("ends_at >= ?".to_string()); params.push(SqlValue::Text(since.chars().take(10).collect())); }ifletSome(until) = &args.until { where_parts.push("starts_at <= ?".to_string()); params.push(SqlValue::Text(until.chars().take(10).collect())); } params.push(SqlValue::Integer(args.limit));let sql = format!("SELECT * FROM {ALBUMS} WHERE {} ORDER BY CASE state WHEN 'open' THEN 0 ELSE 1 END, starts_at DESC, id LIMIT ?", where_parts.join(" AND ") );let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?;letmut albums = Vec::with_capacity(found.len());for row in &found {let id = rtext(row, "id").unwrap_or_default();let items = items_of(ctx, &id, true)?;let record_ids: Vec<String> = items .iter() .filter_map(|item| rtext(item, "record_id")) .collect();let people = people_of(ctx, &record_ids)?; albums.push(Value::Object(album_out(row, &items, &people))); }letmut out = Map::new(); out.insert("albums".to_string(), Value::Array(albums));Ok(Value::Object(out))}fn album_answer(ctx: &Ctx<'_>, id: &str) -> ToolResult {let row = album_row(ctx, id)?;let items = items_of(ctx, id, true)?;let record_ids: Vec<String> = items .iter() .filter_map(|item| rtext(item, "record_id")) .collect();let people = people_of(ctx, &record_ids)?;letmut out = album_out(&row, &items, &people); out.insert("items".to_string(),Value::Array( items .iter() .map(|item| {letmut shaped = Map::new(); shaped.insert("id".to_string(), rtext(item, "record_id").map_or(Value::Null, Value::from), ); shaped.insert("kind".to_string(), rtext(item, "record_kind").map_or(Value::Null, Value::from), ); shaped.insert("addedBy".to_string(), rtext(item, "added_by").map_or(Value::Null, Value::from), ); shaped.insert("sortAt".to_string(), rtext(item, "sort_at").map_or(Value::Null, Value::from), );Value::Object(shaped) }) .collect(), ), ); out.insert("projects".to_string(),Value::Array( project_slugs_of(ctx, id)? .into_iter() .map(Value::from) .collect(), ), );Ok(Value::Object(out))}pubfn get_album(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = require_album_id(args)?; album_answer(ctx, &id)}// ── writes ──────────────────────────────────────────────────────────────────fn patch_album( ctx: &mutCtx<'_>, id: &str,mut patch: Map<String, Value>,) -> Result<(), ToolFailure> {// `cotton_media_albums` carries no `moddatetime` trigger, so the stamp the// cell used to write is written here — as the TypeScript's `patchAlbum`// does, on every patch including an empty one. patch.insert("updated_at".to_string(), Value::from(now_iso(ctx))); update_row(ctx, ALBUMS, id, patch)}/// Who named an album, put back by the UNDO of a rename — the one write of/// `title_by` beside `update_album` / `create_album` (which make it `user`)/// and the nightly pass. No tool takes it: the generic `undo` of an album's/// rename reaches it, after `update_album` has put the old name back, so a/// name Cotton gave is Cotton's again and the nightly pass may refresh it.pubfn put_back_naming(ctx: &mutCtx<'_>, id: &str, title_by: &str) -> Result<(), ToolFailure> {if !matches!(title_by, "derived" | "user") {returnErr(ToolFailure::new(format!("an album is named by \"derived\" or \"user\", not {title_by:?}" ))); } album_row(ctx, id)?;letmut patch = Map::new(); patch.insert("title_by".to_string(), Value::from(title_by)); patch_album(ctx, id, patch)?; ctx.commit()?; ctx.audit("update_album", &format!("{id}: naming put back to {title_by}"));Ok(())}pubfn decide_album(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let id = require_album_id(args)?;letSome(decision) = optional_enum(args, "decision", DECISIONS)? else {returnErr(ToolFailure::new("decision is required — keep, dismiss or open", )); };let row = album_row(ctx, &id)?;let state = match decision.as_str() {"keep" => "kept","dismiss" => "dismissed", _ => "open", };if rtext(&row, "state").as_deref() == Some(state) {returnErr(ToolFailure::new(if state == "open" { format!("{id} is already open — it is waiting for a decision") } else { format!("{id} is already {state}") })); }letmut patch = Map::new(); patch.insert("state".to_string(), Value::from(state)); patch.insert("decided_at".to_string(),if state == "open" {Value::Null } else {Value::from(now_iso(ctx)) }, ); patch_album(ctx, &id, patch)?; ctx.commit()?; ctx.audit("decide_album", &format!("{id} → {state}")); album_answer(ctx, &id)}/// One picture named to an album tool, as the checks need it.structPicture { id: String, taken_at: String, taken_offset: Option<i64>,}/// The pictures named, checked to exist here and to be admissible by hand.fn pictures_for(ctx: &Ctx<'_>, ids: &[String]) -> Result<Vec<Picture>, ToolFailure> {letmut out = Vec::with_capacity(ids.len());for id in ids {let kind = if id.starts_with("video:") {"video" } else {"photo" };let table = if kind == "video" {"cotton_videos" } else {"cotton_photos" };let utility = if kind == "video" {"NULL" } else {"is_utility" };let row = ctx .db() .get( &format!("SELECT id, taken_at, taken_offset, {utility} AS is_utility, subtypes FROM {table} WHERE id = ? AND workspace_id = ? AND trashed_at IS NULL" ), &[SqlValue::Text(id.clone()),SqlValue::Text(ctx.workspace_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new(format!("no {kind} with id {id}")))?;let subtypes = crate::mcp::handlers::media_tools::string_list_of(row.text("subtypes"));if !album_admits_by_hand(rint(&row, "is_utility"), &subtypes) {returnErr(ToolFailure::new(format!("{id} is a screenshot or a picture of information, and a screenshot is not a \ moment — it cannot go in an album" ))); } out.push(Picture { id: rtext(&row, "id").unwrap_or_default(), taken_at: rtext(&row, "taken_at").unwrap_or_default(), taken_offset: rint(&row, "taken_offset"), }); }Ok(out)}fn insert_items( ctx: &mutCtx<'_>, album_id: &str, pictures: &[Picture],) -> Result<usize, ToolFailure> {let stamp = now_iso(ctx);for picture in pictures {letmut patch = Map::new(); patch.insert("album_id".to_string(), Value::from(album_id)); patch.insert("record_kind".to_string(),Value::from(if picture.id.starts_with("video:") {"video" } else {"photo" }), ); patch.insert("record_id".to_string(), Value::from(picture.id.clone()));// Added BY HAND is added by the person, always: this whole file writes// as them (D5), and the nightly pass never touches what they made. patch.insert("added_by".to_string(), Value::from("user")); patch.insert("sort_at".to_string(), Value::from(picture.taken_at.clone())); patch.insert("created_at".to_string(), Value::from(stamp.clone())); patch.insert("updated_at".to_string(), Value::from(stamp.clone())); ctx.writer()? .upsert(ITEMS, &media_album_item_id(album_id, &picture.id), patch); }Ok(pictures.len())}pubfn update_album(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_update_album(args)?;let row = album_row(ctx, &args.id)?;let state = rtext(&row, "state").unwrap_or_default();if state == "dismissed" {returnErr(ToolFailure::new(format!("{} is dismissed — re-open it with decide_album before changing it", args.id ))); }let current = items_of(ctx, &args.id, false)?;let have: Vec<String> = current .iter() .filter_map(|item| rtext(item, "record_id")) .collect();let wanted: Vec<String> = args .add .clone() .unwrap_or_default() .into_iter() .filter(|id| !have.contains(id)) .collect();let adding = pictures_for(ctx, &wanted)?;let removing: Vec<&Row> = current .iter() .filter(|item| { rtext(item, "record_id").is_some_and(|record_id| { args.remove .as_ref() .is_some_and(|remove| remove.contains(&record_id)) }) }) .collect();letmut remaining: Vec<String> = have.clone();for picture in &adding {if !remaining.contains(&picture.id) { remaining.push(picture.id.clone()); } }for item in &removing {ifletSome(record_id) = rtext(item, "record_id") { remaining.retain(|id| *id != record_id); } }ifletSome(cover_id) = &args.cover_id {if !remaining.contains(cover_id) {returnErr(ToolFailure::new("coverId must be one of the album's own pictures", )); } }letmut patch = Map::new();// An edit to an open proposal keeps it first: a name is a decision.if state == "open" { patch.insert("state".to_string(), Value::from("kept")); patch.insert("decided_at".to_string(), Value::from(now_iso(ctx))); }ifletSome(title) = &args.title { patch.insert("title".to_string(), Value::from(title.clone())); patch.insert("title_by".to_string(), Value::from("user")); }ifletSome(cover_id) = &args.cover_id { patch.insert("cover_id".to_string(), Value::from(cover_id.clone())); }let removed = removing.len();let removed_ids: Vec<String> = removing .iter() .filter_map(|item| rtext(item, "id")) .collect();for item_id in &removed_ids { ctx.writer()?.retract(ITEMS, item_id, Retract::Relation); }let added = insert_items(ctx, &args.id, &adding)?;// A cover that has just been removed picks another member, so the album is// never left pointing at a picture it no longer holds.ifletSome(cover_id) = rtext(&row, "cover_id") {if !remaining.contains(&cover_id) && args.cover_id.is_none() { patch.insert("cover_id".to_string(), remaining.first().cloned().map_or(Value::Null, Value::from), ); } } patch_album(ctx, &args.id, patch)?; ctx.commit()?;letmut said: Vec<String> = Vec::new();if args.title.is_some() { said.push("renamed".to_string()); }if added > 0 { said.push(format!("{added} added")); }if removed > 0 { said.push(format!("{removed} removed")); }if state == "open" { said.push("kept".to_string()); } ctx.audit("update_album", &format!("{}: {}", args.id,if said.is_empty() {"nothing changed".to_string() } else { said.join(", ") } ), ); album_answer(ctx, &args.id)}pubfn create_album(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_create_album(args)?; make_album(ctx, Some(args.kind), &args.title, &args.photo_ids, args.cover_id)}/// A group made on a table whose groups are albums (`groups.kept_in`): the/// album `create_album` makes, named `title` and holding `photo_ids`, its/// kind read from the pictures — an event when they were all taken on one/// local day, a trip when they span several — since a group is given no/// kind. Checked as `create_album` checks its own arguments.pubfn create_album_for_group(ctx: &mutCtx<'_>, title: &str, photo_ids: &[String]) -> ToolResult {letmut args = Map::new(); args.insert("title".to_string(), Value::from(title)); args.insert("photoIds".to_string(),Value::Array(photo_ids.iter().cloned().map(Value::from).collect()), );let title = album_title(&args, true)?.unwrap_or_default();let photo_ids = picture_id_list(&args, "photoIds", true)?.unwrap_or_default(); make_album(ctx, None, &title, &photo_ids, None)}/// `create_album`'s write: `kind` given, or — `None` — read from the span of/// the pictures' local days.fn make_album( ctx: &mutCtx<'_>, kind: Option<String>, title: &str, photo_ids: &[String], cover_id: Option<String>,) -> ToolResult {letmut unique: Vec<String> = Vec::new();for id in photo_ids {if !unique.contains(id) { unique.push(id.clone()); } }let pictures = pictures_for(ctx, &unique)?;ifletSome(cover_id) = &cover_id {if !pictures.iter().any(|picture| picture.id == *cover_id) {returnErr(ToolFailure::new("coverId must be one of the album's own pictures", )); } }// The anchor a DERIVED album of these pictures would carry, so a// person-made album and a proposal over the same moment are ONE id.let timezone = workspace_timezone_or_null(ctx)?.unwrap_or_else(|| "UTC".to_string());letmut placed: Vec<(&Picture, cotton_core::rules::media::albums::LocalInstant)> = Vec::new();for picture in &pictures {let offset = match picture.taken_offset {Some(offset) => offset,None => zone_offset_seconds(&timezone, parse_ms(&picture.taken_at).unwrap_or(0)), };let at = local_instant(&picture.taken_at, offset).map_err(|error| {ToolFailure::new(format!("{} has an unreadable moment: {error}", picture.id)) })?; placed.push((picture, at)); } placed.sort_by(|a, b| a.1.ms.cmp(&b.1.ms).then_with(|| a.0.id.cmp(&b.0.id)));let (first_picture, first_at) = placed .first() .ok_or_else(|| ToolFailure::new("photoIds is required"))?;let last_at = &placed[placed.len() - 1].1;let kind = kind.unwrap_or_else(|| {if first_at.date == last_at.date { "event" } else { "trip" }.to_string() });let id = media_album_id( &kind,if kind == "event" { &first_at.hour } else { &first_at.date }, );// Deliberately NOT scoped to this workspace: the id is derived from the// moment alone, so a row anywhere in this file already stands on it.let taken = ctx .db() .get( &format!("SELECT id, title FROM {ALBUMS} WHERE id = ?"), &[SqlValue::Text(id.clone())], ) .map_err(|error| ToolFailure::new(error.to_string()))?;ifletSome(taken) = taken {returnErr(ToolFailure::new(format!("an album already stands on that moment — {} ({}). Add these pictures to it with \ update_album, or re-open it with decide_album if it was dismissed.", rtext(&taken, "id").unwrap_or_default(), quoted(&rtext_any(&taken, "title").unwrap_or_default()) ))); }let stamp = now_iso(ctx);letmut patch = Map::new(); patch.insert("kind".to_string(), Value::from(kind.clone())); patch.insert("state".to_string(), Value::from("kept")); patch.insert("decided_at".to_string(), Value::from(stamp.clone())); patch.insert("title".to_string(), Value::from(title)); patch.insert("title_by".to_string(), Value::from("user")); patch.insert("starts_at".to_string(), Value::from(first_at.date.clone())); patch.insert("ends_at".to_string(), Value::from(last_at.date.clone())); patch.insert("home_label".to_string(), Value::Null); patch.insert("cover_id".to_string(),Value::from( cover_id .clone() .unwrap_or_else(|| first_picture.id.clone()), ), ); insert_row(ctx, ALBUMS, &id, patch)?; insert_items(ctx, &id, &pictures)?; ctx.commit()?;let change = crate::mcp::handlers::tables::record_added(ctx, "album", &id)?; ctx.audit("create_album", &format!("{id}: {} picture(s)", pictures.len()), );letmut answer = album_answer(ctx, &id)?;ifletSome(answer) = answer.as_object_mut() { answer.insert("change".to_string(), change); }Ok(answer)}