//! One implementation of the photo and video tools, twice.//!//! Spec §D1, revised for schema v39 by the photos-library design §D12. The//! registry says two kinds and two tables, and it is right: a video carries a//! duration and a poster a photo never does, and the verb grid compiles per//! kind. What the two do NOT differ in is any of the machinery — the same//! filters, the same caption rule, the same review note, the same delete of a//! row and its bytes. So the machinery is written once here and each kind's//! group declares what it IS.//!//! Three rules this module keeps, and what each defends://!//! NOTHING DELETES ON A REVIEW NOTE. A note is a SUGGESTION with a byline;//! the deletion is the person's own conscious act, one named id at a time.//! There is no batch argument on remove, and there will not be one.//!//! A REMOVED PICTURE WAITS IN THE BIN (architect, 5 Oct 2026: the bin, one//! rule). Removing one sets `trashed_at`: every read here hides it, the bin//! brings it back, and only the bin's erase removes the row — through the//! writer, so it becomes a sync op every device folds — whose erasure facts//! let the bytes it names go once nothing else names them.//!//! THE RECORD KEEPS ITS WHOLE HISTORY (v39). `sightings` answers every place//! a picture was seen, because the same picture forwarded four times is one//! record with four sightings and every one of them was true.//!//! READS go through the raw driver, because a sighting or a face filter is an//! EXISTS over a child table the query builder cannot express and [`filters`]//! is the ONE compilation of those. WRITES go through `ctx.writer()`, so every//! change is an op the phone folds.pubmod filters;use std::collections::BTreeMap;use cotton_store::driver::Row;use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{ bounded_limit, fail, in_chunks, js_number, optional_boolean, optional_string, project_slug_of, projects, put, resolve_project, row_by_id, rows, text, update_row, Clearable, Valid, ID_CHUNK,};usecrate::mcp::protocol::ToolFailure;usecrate::mcp::read_db::{Filter, Query};use filters::media_where;pubuse filters::MediaListFilters;// ── what a kind IS ──────────────────────────────────────────────────────────/// Every difference between photos and videos, in one place.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubstructMediaKindSpec {/// The record kind, which is also the id prefix (`photo:` / `video:`).pub kind: &'static str,pub table: &'static str,/// The word a refusal uses: "no photo with id …".pub noun: &'static str,}pubconst PHOTO_SPEC: MediaKindSpec = MediaKindSpec { kind: "photo", table: "cotton_photos", noun: "photo",};pubconst VIDEO_SPEC: MediaKindSpec = MediaKindSpec { kind: "video", table: "cotton_videos", noun: "video",};/// Mirrors `length(caption) <= 500`.const CAPTION_MAX: usize = 500;/// Mirrors `length(review_note) <= 280`.const REVIEW_NOTE_MAX: usize = 280;/// The longest description an assistant may leave — the describer's own cap,/// so a sentence from a tap and one from an agent fit the same page.const DESCRIPTION_MAX: usize = 400;/// ENGINE SHIM — `PHOTO_SUBTYPES` (`packages/core/src/constants.ts`).////// Its permanent home is `cotton_core::constants`, whose ledger row says the/// file grows one constant at a time beside the engine that reads it. The only/// reader today is [`enrichment_of`], which is itself a shim; both move/// together when `models/media/enrichment.ts` is ported.pubconst PHOTO_SUBTYPES: &[&str] = &["screenshot","selfie","burst","live","hdr","panorama","portrait","edited","slow_motion","time_lapse","screen_recording",];// ── raw-row readers ─────────────────────────────────────────────────────────//// A media read goes through `filters::media_where`, so the rows arrive as the// driver's own `Row` rather than through the codec-decoding `ReadDb`. These// three are the whole difference.pubfn rtext(row: &Row, column: &str) -> Option<String> { row.text(column) .filter(|value| !value.is_empty()) .map(str::to_string)}/// The column as TEXT even when it is empty — for a column whose empty string/// is a value rather than an absence.pubfn rtext_any(row: &Row, column: &str) -> Option<String> { row.text(column).map(str::to_string)}pubfn rint(row: &Row, column: &str) -> Option<i64> { row.int(column)}pubfn rreal(row: &Row, column: &str) -> Option<f64> { row.real(column)}/// `value ?? null`, for a column that is genuinely part of the shape.fn or_null_text(row: &Row, column: &str) -> Value { rtext_any(row, column).map_or(Value::Null, Value::from)}/// A JSON string list, read TOTALLY: the raw TEXT the driver read, or an array/// somebody already decoded. Anything that is not a non-empty string is/// dropped rather than thrown on — a grid must not blank because one row came/// through a path that predates the column.////// ENGINE SHIM — `stringListOf` of `packages/core/src/models/media//// enrichment.ts`; its permanent home is `cotton_core::models::media`.pubfn string_list_of(raw: Option<&str>) -> Vec<String> {letSome(raw) = raw else {returnVec::new(); };if raw.is_empty() {returnVec::new(); }letOk(Value::Array(items)) = serde_json::from_str::<Value>(raw) else {returnVec::new(); }; items .into_iter() .filter_map(|item| match item {Value::String(text) if !text.is_empty() => Some(text), _ => None, }) .collect()}/// What a picture knows about itself (schema v39) — the seventeen enrichment/// columns `cotton_photos` and `cotton_videos` share.////// ENGINE SHIM — `enrichmentOf` of `packages/core/src/models/media//// enrichment.ts`; its permanent home is `cotton_core::models::media`, with the/// rest of `models/`, which the ledger has as "not started". Only the two media/// groups read it today.#[derive(Debug, Clone, Default)]pubstructMediaEnrichment {pub taken_offset: Option<i64>,pub latitude: Option<f64>,pub longitude: Option<f64>,pub place_name: Option<String>,pub place_city: Option<String>,pub place_region: Option<String>,pub place_country: Option<String>,pub camera_make: Option<String>,pub camera_model: Option<String>,pub orientation: Option<i64>,pub favourite: bool,pub subtypes: Vec<String>,pub original_filename: Option<String>,pub aesthetic_score: Option<f64>,pub curation_score: Option<f64>,pub labels: Vec<String>,pub phash: Option<String>,}pubfn enrichment_of(row: &Row) -> MediaEnrichment {MediaEnrichment { taken_offset: rint(row, "taken_offset"), latitude: rreal(row, "latitude"), longitude: rreal(row, "longitude"), place_name: rtext(row, "place_name"), place_city: rtext(row, "place_city"), place_region: rtext(row, "place_region"), place_country: rtext(row, "place_country"), camera_make: rtext(row, "camera_make"), camera_model: rtext(row, "camera_model"), orientation: rint(row, "orientation"), favourite: rint(row, "favourite") == Some(1), subtypes: string_list_of(row.text("subtypes")) .into_iter() .filter(|value| PHOTO_SUBTYPES.contains(&value.as_str())) .collect(), original_filename: rtext(row, "original_filename"), aesthetic_score: rreal(row, "aesthetic_score"), curation_score: rreal(row, "curation_score"), labels: string_list_of(row.text("labels")), phash: rtext(row, "phash"), }}/// The caption a picture wears, trimmed and clipped to the column's 500.////// ENGINE SHIM — `normalisePhotoCaption` of `packages/core/src/models/photo//// transforms.ts`; permanent home `cotton_core::models::photo`. ONE writer's/// rule, shared by the app's editor and this server: two normalisations would/// eventually store a trailing newline on one path and not the other, and the/// same picture would compare unequal to itself. Newlines collapse because a/// caption is one line under a photo, never prose.pubfn normalise_photo_caption(caption: Option<&str>) -> Option<String> { collapse_clip(caption, CAPTION_MAX)}/// A review note, trimmed and clipped to 280 — or `None`, which CLEARS it.////// ENGINE SHIM — `normalisePhotoReviewNote`, same home as the caption's. A/// blank string is `None` rather than a refusal: the app's "Keep" button hands/// back what the field holds, and an empty field means the person is done with/// the suggestion.pubfn normalise_photo_review_note(note: Option<&str>) -> Option<String> { collapse_clip(note, REVIEW_NOTE_MAX)}/// `trim().replace(/\s+/g, " ")`, then `slice(0, max)` — the shape both/// normalisers share.fn collapse_clip(value: Option<&str>, max: usize) -> Option<String> {let collapsed = value .unwrap_or("") .split_whitespace() .collect::<Vec<_>>() .join(" ");if collapsed.is_empty() {returnNone; }// `String.prototype.slice` counts UTF-16 units; the ceilings here are the// column's own CHECK, which SQLite counts in characters. Both are already// enforced by the length refusal in `update_media`, so this clip only ever// fires on a value that arrived through another route.Some(collapsed.chars().take(max).collect())}// ── the arguments ───────────────────────────────────────────────────────────/// `ListMediaArgs` — one validator for both lists.#[derive(Debug, Clone, Default)]pubstructListMediaArgs {pub project: Option<String>,pub thread: Option<String>,pub since: Option<String>,pub until: Option<String>,pub reviewed: Option<bool>,pub described: Option<bool>,pub person: Option<String>,pub with_people: Option<bool>,pub favourite: Option<bool>,pub screenshots: Option<bool>,pub utility: Option<bool>,pub place: Option<String>,pub label: Option<String>,pub limit: i64,}/// A photo's or a video's id: the prefix, then the 64 hex characters of the/// content hash. Not a uuid — the id IS the content (spec D2), which is what/// makes the same picture in four chats one record.////// Checked here rather than left to the database so a caller that passed a/// video's id to a photo tool is told which it needs, instead of being told/// there is no such photo: the two ids differ only in their prefix, and that is/// exactly the mistake an assistant holding both lists will make.pubfn require_media_id(args: &Map<String, Value>, kind: &str) -> Valid<String> {let value = optional_string(args, "id").unwrap_or_default();if is_media_id(&value, kind) {returnOk(value); } fail(format!("id must be a {kind}'s id — \"{kind}:\" followed by its 64-character content hash" ))}pubfn is_media_id(value: &str, kind: &str) -> bool {letSome(hash) = value .strip_prefix(kind) .and_then(|rest| rest.strip_prefix(':'))else {returnfalse; }; hash.len() == 64 && hash .bytes() .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())}pubfn validate_list_media(args: &Map<String, Value>) -> Valid<ListMediaArgs> {for key in ["since", "until"] {ifletSome(value) = optional_string(args, key) {ifcrate::mcp::handlers::common::parse_ms(&value).is_none() {return fail(format!("{key} must be an ISO-8601 instant")); } } }let reviewed = optional_boolean(args, "reviewed")?;let described = optional_boolean(args, "described")?;let with_people = optional_boolean(args, "withPeople")?;let favourite = optional_boolean(args, "favourite")?;let screenshots = optional_boolean(args, "screenshots")?;let utility = optional_boolean(args, "utility")?;// `optionalString` already trims and reads a blank as absent, so the// TypeScript's "cannot be blank" check can only fire on a value that is// whitespace — which reads as absent here and is left out, exactly as the// trimmed value would have been.Ok(ListMediaArgs { project: optional_string(args, "project"), thread: optional_string(args, "thread"), since: optional_string(args, "since"), until: optional_string(args, "until"), reviewed, described, person: optional_string(args, "person"), with_people, favourite, screenshots, utility, place: optional_string(args, "place"), label: optional_string(args, "label"), limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST), })}/// `UpdateMediaArgs` — a caption, a review note, a description, or a refusal.#[derive(Debug, Clone)]pubstructUpdateMediaArgs {pub id: String,pub caption: Clearable<String>,pub review_note: Clearable<String>,/// What the assistant SAW in the picture, after looking at it — the only/// road an agent's sentence takes onto a picture (there is no describe/// job; the owner overruled it on 14 Oct 2026).pub description: Clearable<String>,/// The owner's star on it, marked in Cotton Photos (or imported from/// Apple Photos by the Mac).pub favourite: Option<bool>,}pubfn validate_update_media(args: &Map<String, Value>, kind: &str) -> Valid<UpdateMediaArgs> {let id = require_media_id(args, kind)?;let caption = crate::mcp::handlers::common::clearable_string(args, "caption");let review_note = crate::mcp::handlers::common::clearable_string(args, "reviewNote");let description = crate::mcp::handlers::common::clearable_string(args, "description");let favourite = optional_boolean(args, "favourite")?;if caption.is_unchanged() && review_note.is_unchanged() && description.is_unchanged() && favourite.is_none() {return fail("nothing to change — pass caption (the user's own words, or null to clear it), \ reviewNote (a suggestion they look at this again, or null to take one back off), \ description (what you saw in the picture, or null to clear it) or favourite \ (true to star it, false to take the star off)", ); }Ok(UpdateMediaArgs { id, caption, review_note, description, favourite, })}// ── the shapes ──────────────────────────────────────────────────────────────/// The place a picture was taken, as one line — the most specific part first.fn place_line(enrichment: &MediaEnrichment) -> Option<String> {letmut parts: Vec<String> = Vec::new();for part in [ &enrichment.place_name, &enrichment.place_city, &enrichment.place_region, &enrichment.place_country, ] {ifletSome(part) = part.as_deref().filter(|value| !value.is_empty()) {// `new Set(parts)` — a city that is also the place's name is said// once.if !parts.iter().any(|seen| seen == part) { parts.push(part.to_string()); } } } (!parts.is_empty()).then(|| parts.join(", "))}/// One row, as a list answers it.////// `summary` is called `description` on the wire: what the describe worker/// writes is a sentence about what is IN the picture, and calling it a summary/// would invite an assistant to try `update_summary` — which refuses the kind,/// because the material is pixels rather than text (D5).pubfn media_out( spec: MediaKindSpec, row: &Row, project_slugs: &[String], people: &[String],) -> Map<String, Value> {let enrichment = enrichment_of(row);let place = place_line(&enrichment);let summary = rtext(row, "summary");letmut out = Map::new(); out.insert("id".to_string(), or_null_text(row, "id")); out.insert("caption".to_string(), or_null_text(row, "caption")); out.insert("description".to_string(), summary.clone().map_or(Value::Null, Value::from), );if summary.is_some() { out.insert("describedBy".to_string(), or_null_text(row, "summary_by")); out.insert("describedAt".to_string(), or_null_text(row, "summary_at")); } out.insert("takenAt".to_string(), or_null_text(row, "taken_at")); out.insert("sizeBytes".to_string(),Value::from(rint(row, "size_bytes").unwrap_or(0)), );iflet (Some(width), Some(height)) = (rint(row, "width"), rint(row, "height")) { out.insert("width".to_string(), Value::from(width)); out.insert("height".to_string(), Value::from(height)); } out.insert("contentType".to_string(), or_null_text(row, "content_type"));if spec.kind == "video" {ifletSome(duration) = rint(row, "duration_ms") { out.insert("durationMs".to_string(), Value::from(duration)); } } put(&mut out, "place", place.map(Value::from));if !enrichment.subtypes.is_empty() { out.insert("subtypes".to_string(),Value::Array( enrichment .subtypes .iter() .map(|value| Value::from(value.as_str())) .collect(), ), ); } out.insert("favourite".to_string(), Value::Bool(enrichment.favourite)); out.insert("people".to_string(),Value::Array( people .iter() .map(|value| Value::from(value.as_str())) .collect(), ), );// What the Mac learned by looking (schema v40) — present only once analysed. put(&mut out, "text", rtext(row, "ocr_text").map(Value::from));ifletSome(utility) = rint(row, "is_utility") { out.insert("utility".to_string(), Value::Bool(utility == 1)); }ifletSome(note) = rtext(row, "review_note") { out.insert("reviewNote".to_string(), Value::from(note)); out.insert("reviewBy".to_string(), or_null_text(row, "review_by")); out.insert("reviewAt".to_string(), or_null_text(row, "review_at")); } out.insert("projects".to_string(),Value::Array( project_slugs .iter() .map(|value| Value::from(value.as_str())) .collect(), ), ); out}// ── the page's satellites ───────────────────────────────────────────────────/// The projects a page of rows belongs to — one query for the page, never one/// per row (the thoughts idiom).fn project_slugs_for( ctx: &Ctx<'_>, spec: MediaKindSpec, ids: &[String],) -> Result<BTreeMap<String, Vec<String>>, ToolFailure> {letmut out: BTreeMap<String, Vec<String>> = BTreeMap::new();if ids.is_empty() {returnOk(out); }let links = in_chunks(ids, |batch| { rows( ctx, &Query::on("cotton_project_links") .columns(&["record_id", "project_id"]) .eq("record_kind", spec.kind.to_string()) .filter(Filter::In("record_id".to_string(), batch.iter().map(|id| SqlValue::Text(id.clone())).collect(), )), ) })?;if links.is_empty() {returnOk(out); }let known = projects(ctx)?;for link in links {let (Some(record_id), Some(project_id)) = (text(&link, "record_id"), text(&link, "project_id"))else {continue; };letSome(slug) = project_slug_of(&known, &project_id) else {continue; }; out.entry(record_id).or_default().push(slug); }Ok(out)}/// The NAMES of the people in a page of pictures — off the faces that resolved/// to a person, one query per chunk.////// A face nobody has named is a person in the picture (it counts for/// `withPeople`) but has no name to answer here. Chunked the way every other/// `IN (…)` read is: each record id falls in exactly one chunk, so the/// per-record order the `ORDER BY` fixes survives the split.fn people_names_for( ctx: &Ctx<'_>, ids: &[String],) -> Result<BTreeMap<String, Vec<String>>, ToolFailure> {letmut out: BTreeMap<String, Vec<String>> = BTreeMap::new();for batch in ids.chunks(ID_CHUNK) {if batch.is_empty() {continue; }let holes = vec!["?"; batch.len()].join(", ");let sql = format!("SELECT DISTINCT f.record_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.record_id IN ({holes}) ORDER BY f.record_id, p.full_name" );letmut params: Vec<SqlValue> = vec![SqlValue::Text(ctx.workspace_id.to_string())]; params.extend(batch.iter().map(|id| SqlValue::Text(id.clone())));for row in ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))? {let (Some(record_id), Some(name)) = (rtext(&row, "record_id"), rtext(&row, "full_name"))else {continue; }; out.entry(record_id).or_default().push(name); } }Ok(out)}/// Every id of this kind that wears a membership of the named project.fn linked_ids( ctx: &Ctx<'_>, spec: MediaKindSpec, project_id: &str,) -> Result<Vec<String>, ToolFailure> {Ok(rows( ctx, &Query::on("cotton_project_links") .columns(&["record_id"]) .eq("record_kind", spec.kind.to_string()) .eq("project_id", project_id.to_string()), )? .into_iter() .filter_map(|row| text(&row, "record_id")) .collect())}/// One row by id, scoped to this database — or a refusal naming the id. A/// picture in the bin is deleted, waiting: it answers as not found here.pubfn media_row(ctx: &Ctx<'_>, spec: MediaKindSpec, id: &str) -> Result<Row, ToolFailure> { ctx.db() .get( &format!("SELECT * FROM {} WHERE id = ? AND workspace_id = ? AND trashed_at IS NULL", spec.table ), &[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 {} with id {id}", spec.noun)))}/// Every sighting of one record, oldest first.fn sightings_of(ctx: &Ctx<'_>, id: &str) -> Result<Vec<Row>, ToolFailure> { ctx.db() .all("SELECT record_id, source, source_id, thread_id, key, seen_at FROM cotton_media_sightings WHERE workspace_id = ? AND record_id = ? ORDER BY seen_at ASC, id ASC", &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))}/// Every place a picture was seen, oldest first, each chat with its name.////// A chat that has since been deleted still answers as a sighting with/// `name: null` — the picture DID come through it, and saying nothing would/// read as "this was never in a chat".fn sightings_out(ctx: &Ctx<'_>, id: &str) -> Result<Vec<Value>, ToolFailure> {let sightings = sightings_of(ctx, id)?;letmut thread_ids: Vec<String> = Vec::new();for row in &sightings {ifletSome(thread_id) = rtext(row, "thread_id") {if !thread_ids.contains(&thread_id) { thread_ids.push(thread_id); } } }letmut names: BTreeMap<String, Value> = BTreeMap::new();for thread in in_chunks(&thread_ids, |batch| { rows( ctx, &Query::on("cotton_msg_threads") .columns(&["id", "title"]) .filter(Filter::In("id".to_string(), batch.iter().map(|id| SqlValue::Text(id.clone())).collect(), )), ) })? {ifletSome(thread_id) = text(&thread, "id") { names.insert( thread_id, text(&thread, "title").map_or(Value::Null, Value::from), ); } }Ok(sightings .iter() .map(|row| {let source = rtext(row, "source").unwrap_or_default();letmut out = Map::new(); out.insert("source".to_string(), Value::from(source.clone())); out.insert("seenAt".to_string(), or_null_text(row, "seen_at"));match source.as_str() {"message" => {let thread_id = rtext(row, "thread_id"); out.insert("threadId".to_string(), thread_id.clone().map_or(Value::Null, Value::from), ); out.insert("name".to_string(), thread_id .and_then(|id| names.get(&id).cloned()) .unwrap_or(Value::Null), ); out.insert("messageId".to_string(), or_null_text(row, "source_id")); }"apple_library" => { out.insert("assetId".to_string(), or_null_text(row, "source_id")); }"email" => { out.insert("emailId".to_string(), or_null_text(row, "source_id")); } _ => {} }Value::Object(out) }) .collect())}/// The SELECT every face read shares — the owner's person and the Mac's/// suggestion, each with its name, in one statement.pubconst FACE_SELECT: &str ="SELECT f.id, f.record_id, f.x, f.y, f.w, f.h, f.quality, f.person_id, f.person_by, p.full_name, f.suggested_person_id, f.suggested_distance, f.suggestion_dismissed_at, sp.full_name AS suggested_name FROM cotton_media_faces f LEFT JOIN cotton_people p ON p.id = f.person_id LEFT JOIN cotton_people sp ON sp.id = f.suggested_person_id";/// The faces on one picture, each with the person it resolved to, or null.pubfn faces_out(ctx: &Ctx<'_>, id: &str) -> Result<Vec<Value>, ToolFailure> {let sql = format!("{FACE_SELECT} WHERE f.workspace_id = ? AND f.record_id = ? ORDER BY f.x ASC, f.y ASC, f.id ASC" );Ok(ctx .db() .all( &sql, &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .iter() .map(face_out) .collect())}/// One face as a tool answers it: the owner's person, and beside it the Mac's/// suggestion (schema v40) when one is open — never both on one face.pubfn face_out(row: &Row) -> Value {letmut box_out = Map::new(); box_out.insert("x".to_string(), js_number(rreal(row, "x").unwrap_or(0.0))); box_out.insert("y".to_string(), js_number(rreal(row, "y").unwrap_or(0.0))); box_out.insert("width".to_string(), js_number(rreal(row, "w").unwrap_or(0.0)), ); box_out.insert("height".to_string(), js_number(rreal(row, "h").unwrap_or(0.0)), );letmut out = Map::new(); out.insert("id".to_string(), or_null_text(row, "id")); out.insert("box".to_string(), Value::Object(box_out));ifletSome(quality) = rreal(row, "quality") { out.insert("quality".to_string(), js_number(quality)); } out.insert("person".to_string(),match rtext(row, "person_id") {Some(person_id) => {letmut person = Map::new(); person.insert("id".to_string(), Value::from(person_id)); person.insert("name".to_string(), or_null_text(row, "full_name"));// The Mac's match rather than the owner's answer: the owner// confirms it by naming the face, or clears it.if rtext(row, "person_by").is_some() { person.insert("matched".to_string(), Value::from(true)); }Value::Object(person) }None => Value::Null, }, ); out.insert("suggestion".to_string(),match rtext(row, "suggested_person_id") {Some(person_id) => {letmut person = Map::new(); person.insert("id".to_string(), Value::from(person_id)); person.insert("name".to_string(), or_null_text(row, "suggested_name"));letmut suggestion = Map::new(); suggestion.insert("person".to_string(), Value::Object(person)); suggestion.insert("distance".to_string(), rreal(row, "suggested_distance").map_or(Value::Null, js_number), );Value::Object(suggestion) }None => Value::Null, }, ); put( &mut out,"suggestionDismissedAt", rtext(row, "suggestion_dismissed_at").map(Value::from), );Value::Object(out)}// ── the four shared verbs ───────────────────────────────────────────────────pubfn list_media( ctx: &mutCtx<'_>, spec: MediaKindSpec, args: &ListMediaArgs,) -> Result<Value, ToolFailure> {// The project filter is a JOIN the filter compiler does not know about, so// the membership is read FIRST and the ids narrow the row read — the// thoughts idiom. `global` (a picture in no project at all) is deliberately// not supported: unlike a thought, a picture belongs to a project only when// somebody filed it there, so "no project" would answer with almost the// whole library and mean nothing.letmut only_ids: Option<Vec<String>> = None;ifletSome(slug) = &args.project {let known = projects(ctx)?;// Throws, naming the projects that DO exist, when the slug is unknown.letSome(project_id) = resolve_project(&known, Some(slug))? else {returnErr(ToolFailure::new(format!("a {} belongs to a project only when somebody filed it there, so \"global\" has \ no meaning here — name a project, or leave the filter out", spec.noun ))); };let ids = linked_ids(ctx, spec, &project_id)?;if ids.is_empty() {letmut out = Map::new(); out.insert(format!("{}s", spec.noun), Value::Array(Vec::new()));returnOk(Value::Object(out)); } only_ids = Some(ids); }let filters = MediaListFilters { ids: only_ids, thread_id: args.thread.clone(), since: args.since.clone(), until: args.until.clone(), reviewed: args.reviewed, described: args.described, person_id: args.person.clone(), with_people: args.with_people, favourite: args.favourite, utility: args.utility, copies: None, subtype: (args.screenshots == Some(true)).then(|| "screenshot".to_string()), place: args.place.clone(), label: args.label.clone(), limit: Some(args.limit), }; list_media_rows(ctx, spec, &filters)}/// The rows a media list answers, for filters the caller has already built.////// [`list_media`]'s own second half, lifted out so the PHONE can reach it. The/// app's picture grid is the whole library and excludes agreed copies — two/// settings [`ListMediaArgs`] deliberately does not expose, because an/// assistant asking for "my photos" wants a bounded answer and a person opening/// the grid wants theirs. Sharing this body rather than writing a second one is/// what keeps a tile on the phone and a row an assistant reads the same record:/// one filter compiler, one `media_out`, one set of project and people joins.pubfn list_media_rows( ctx: &mutCtx<'_>, spec: MediaKindSpec, filters: &MediaListFilters,) -> Result<Value, ToolFailure> {let (sql, params) = media_where(spec.table, ctx.workspace_id, filters);let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?;let ids: Vec<String> = found.iter().filter_map(|row| rtext(row, "id")).collect();let slugs = project_slugs_for(ctx, spec, &ids)?;let people = people_names_for(ctx, &ids)?;letmut out = Map::new(); out.insert( format!("{}s", spec.noun),Value::Array( found .iter() .map(|row| {let id = rtext(row, "id").unwrap_or_default();Value::Object(media_out( spec, row, slugs.get(&id).map(Vec::as_slice).unwrap_or(&[]), people.get(&id).map(Vec::as_slice).unwrap_or(&[]), )) }) .collect(), ), );Ok(Value::Object(out))}pubfn get_media( ctx: &mutCtx<'_>, spec: MediaKindSpec, id: &str,) -> Result<Map<String, Value>, ToolFailure> {let row = media_row(ctx, spec, id)?;let ids = vec![id.to_string()];let slugs = project_slugs_for(ctx, spec, &ids)?;let people = people_names_for(ctx, &ids)?;let enrichment = enrichment_of(&row);letmut out = media_out( spec, &row, slugs.get(id).map(Vec::as_slice).unwrap_or(&[]), people.get(id).map(Vec::as_slice).unwrap_or(&[]), ); out.insert("sightings".to_string(),Value::Array(sightings_out(ctx, id)?), ); out.insert("faces".to_string(), Value::Array(faces_out(ctx, id)?)); out.insert("location".to_string(),match (enrichment.latitude, enrichment.longitude) { (Some(latitude), Some(longitude)) => {letmut location = Map::new(); location.insert("latitude".to_string(), js_number(latitude)); location.insert("longitude".to_string(), js_number(longitude));Value::Object(location) } _ => Value::Null, }, );// The `place` LINE the list carries is replaced by the place's PARTS here,// exactly as the TypeScript's later spread wins over the earlier one. out.insert("place".to_string(),match place_line(&enrichment) {None => Value::Null,Some(_) => {letmut place = Map::new();for (key, value) in [ ("name", &enrichment.place_name), ("city", &enrichment.place_city), ("region", &enrichment.place_region), ("country", &enrichment.place_country), ] { place.insert( key.to_string(), value.clone().map_or(Value::Null, Value::from), ); }Value::Object(place) } }, ); out.insert("camera".to_string(),if enrichment.camera_make.is_some() || enrichment.camera_model.is_some() {letmut camera = Map::new(); camera.insert("make".to_string(), enrichment .camera_make .clone() .map_or(Value::Null, Value::from), ); camera.insert("model".to_string(), enrichment .camera_model .clone() .map_or(Value::Null, Value::from), );Value::Object(camera) } else {Value::Null }, ); out.insert("orientation".to_string(), enrichment.orientation.map_or(Value::Null, Value::from), ); out.insert("takenOffset".to_string(), enrichment.taken_offset.map_or(Value::Null, Value::from), ); out.insert("subtypes".to_string(),Value::Array( enrichment .subtypes .iter() .map(|value| Value::from(value.as_str())) .collect(), ), ); out.insert("labels".to_string(),Value::Array( enrichment .labels .iter() .map(|value| Value::from(value.as_str())) .collect(), ), ); out.insert("originalFilename".to_string(), enrichment .original_filename .clone() .map_or(Value::Null, Value::from), ); out.insert("scores".to_string(),if enrichment.aesthetic_score.is_some() || enrichment.curation_score.is_some() {letmut scores = Map::new(); scores.insert("aesthetic".to_string(), enrichment.aesthetic_score.map_or(Value::Null, js_number), ); scores.insert("curation".to_string(), enrichment.curation_score.map_or(Value::Null, js_number), );Value::Object(scores) } else {Value::Null }, ); out.insert("sha256".to_string(), or_null_text(&row, "sha256"));Ok(out)}pubfn update_media( ctx: &mutCtx<'_>, spec: MediaKindSpec, args: &UpdateMediaArgs,) -> Result<Value, ToolFailure> {// READ FIRST: the writer upserts, so an unknown id would otherwise MINT a// row rather than refuse. media_row(ctx, spec, &args.id)?;letmut patch = Map::new();// THROUGH THE ONE NORMALISER, the same rule the app's editor calls. The// length refusals stay here and run FIRST: an assistant that sent 600// characters should be told, not quietly clipped.match &args.caption {Clearable::Unchanged => {}Clearable::Cleared => { patch.insert("caption".to_string(), Value::Null); }Clearable::Set(caption) => {let length = caption.chars().count();if length > CAPTION_MAX {returnErr(ToolFailure::new(format!("a caption is at most {CAPTION_MAX} characters — this one is {length}" ))); } patch.insert("caption".to_string(), normalise_photo_caption(Some(caption)).map_or(Value::Null, Value::from), ); } }match &args.review_note {Clearable::Unchanged => {}Clearable::Cleared => {// "Keep". The note, its author and its moment go together, because// the database's own CHECK ties the note to its moment and a byline// standing over a cleared note is a suggestion nobody made. patch.insert("review_note".to_string(), Value::Null); patch.insert("review_by".to_string(), Value::Null); patch.insert("review_at".to_string(), Value::Null); }Clearable::Set(raw) => {let length = raw.chars().count();if length > REVIEW_NOTE_MAX {returnErr(ToolFailure::new(format!("a review note is at most {REVIEW_NOTE_MAX} characters — this one is {length}" ))); }letSome(note) = normalise_photo_review_note(Some(raw)) else {// A note of nothing but spaces. The CHECK refuses it, so// without this the assistant got a SQLite constraint message// about a column it has never heard of.returnErr(ToolFailure::new(format!("a review note has to say something — send null to clear the one on this {}", spec.noun ))); }; patch.insert("review_note".to_string(), Value::from(note));// The connected assistant's own name, as the owner typed it on the// Connected AIs screen — never the token's id and never "agent". patch.insert("review_by".to_string(), Value::from(ctx.agent)); patch.insert("review_at".to_string(),Value::from(crate::mcp::handlers::common::now_iso(ctx)), ); } }match &args.description {Clearable::Unchanged => {}Clearable::Cleared => {// The sentence, its author and its moment go together — the// database's CHECK ties the summary to its moment. patch.insert("summary".to_string(), Value::Null); patch.insert("summary_by".to_string(), Value::Null); patch.insert("summary_at".to_string(), Value::Null); }Clearable::Set(raw) => {let said = raw.split_whitespace().collect::<Vec<_>>().join(" ");let length = said.chars().count();if length == 0 {returnErr(ToolFailure::new(format!("a description has to say something — send null to clear the one on this {}", spec.noun ))); }if length > DESCRIPTION_MAX {returnErr(ToolFailure::new(format!("a description is at most {DESCRIPTION_MAX} characters — this one is {length}" ))); } patch.insert("summary".to_string(), Value::from(said)); patch.insert("summary_by".to_string(), Value::from(ctx.agent)); patch.insert("summary_at".to_string(),Value::from(crate::mcp::handlers::common::now_iso(ctx)), ); } }ifletSome(favourite) = args.favourite { patch.insert("favourite".to_string(), Value::Bool(favourite)); } update_row(ctx, spec.table, &args.id, patch)?;// The read-back is of what LANDED, so the answer cannot claim a value the// fold refused: the writer is deferred, and this drains it first. ctx.commit()?;let row = media_row(ctx, spec, &args.id)?;let ids = vec![args.id.clone()];let slugs = project_slugs_for(ctx, spec, &ids)?;let people = people_names_for(ctx, &ids)?;Ok(Value::Object(media_out( spec, &row, slugs.get(&args.id).map(Vec::as_slice).unwrap_or(&[]), people.get(&args.id).map(Vec::as_slice).unwrap_or(&[]), )))}/// `remove_photo` / `remove_video` — move the picture to the bin (architect,/// 5 Oct 2026: every record a person deletes waits there). Its faces,/// sightings, album places and links wait with it; `restore_from_bin` brings/// it back as it was, and only the bin's erase removes it for good — that/// erase writes one erasure fact per key it named, and each device unlinks a/// key once nothing names it. Nothing leaves the disk here: `bytesRemoved` is/// false until the bin is emptied. A picture already in the bin answers as/// removed and stays where it is.pubfn remove_media( ctx: &mutCtx<'_>, spec: MediaKindSpec, id: &str,) -> Result<Value, ToolFailure> {let row = media_row_opt(ctx, spec.table, id)? .ok_or_else(|| ToolFailure::new(format!("no {} with id {id}", spec.noun)))?;let sightings = sightings_of(ctx, id)?;if text(&row, "trashed_at").is_none() { set_media_trashed(ctx, spec.table, id, true)?; }letmut chats: Vec<String> = Vec::new();for sighting in &sightings {ifletSome(thread_id) = rtext(sighting, "thread_id") {if !chats.contains(&thread_id) { chats.push(thread_id); } } }letmut out = Map::new(); out.insert("removed".to_string(), Value::Bool(true)); out.insert("id".to_string(), Value::from(id)); out.insert("trashed".to_string(), Value::Bool(true)); out.insert("bytesRemoved".to_string(), Value::Bool(false));// The chats it came through keep it (slice 7), which the confirmation says// out loud, so an assistant can say it back.if !chats.is_empty() {let what = if spec.kind == "video" { "video" } else { "picture" };let count = chats.len(); out.insert("alsoInChats".to_string(), Value::from(count)); out.insert("note".to_string(),Value::from(format!("This {what} is also in {count} chat{}. It stays there unless those messages are deleted.",if count == 1 { "" } else { "s" } )), ); }Ok(Value::Object(out))}/// Put a picture in the bin, or take it out: its Delete, its Undo and/// `remove_photo` / `remove_video` (the bin's Restore clears the same column)./// Its edited time stays as it was either way.pubfn set_media_trashed(ctx: &mutCtx<'_>, table: &str, id: &str, trashed: bool) -> Valid<()> {let kind = match table {"cotton_photos" => cotton_core::constants::BinKind::Photo,"cotton_videos" => cotton_core::constants::BinKind::Video, _ => returnErr(ToolFailure::new("not a picture table")), };if trashed {crate::mcp::handlers::bin::put_away(ctx, kind, id) } else {let args = serde_json::json!({"kind": kind.as_str(), "id": id});crate::mcp::handlers::bin::restore_from_bin(ctx, args.as_object().unwrap()).map(|_| ()) }}/// A row this workspace holds, or `None` — for the callers that want the/// absence rather than the refusal.pubfn media_row_opt( ctx: &Ctx<'_>, table: &str, id: &str,) -> Result<Option<Map<String, Value>>, ToolFailure> { row_by_id(ctx, table, id)}