//! The tools that read and decide what the Mac learned by LOOKING at pictures//! (schema v40): `update_face`, `list_duplicates`, `decide_duplicate`.//!//! Two kinds of writer, never mixed. The Mac's analysis worker PROPOSES — a//! face suggestion, a duplicate group — and never lands here. These three tools//! carry the OWNER's answers: who a face is, whether a proposal stands. Every//! write goes through the op writer so it becomes a sync op the phone folds,//! and none of them deletes anything: a confirmed copy is removed only when a//! person names it to `remove_photo`.//!//! THE MODEL ITSELF IS NOT HERE, and there is nothing in this file that wants//! it to be. Vision's own reading — the OCR text, the utility verdict, the face//! boxes, the perceptual hash — is written by the analysis worker (2f), which//! reaches its model through a `deps` trait the way agent L's `GoogleWorker`//! does. These tools only ever read what that worker wrote and write what the//! owner decided, so the seam this group needs from 2f is a WORKER that fills//! columns, never a rail a handler calls.use cotton_store::driver::Row;use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};usecrate::mcp::handlers::common::{ bounded_limit, clearable_string, fail, now_iso, optional_boolean, optional_enum, optional_string, put, require_string, update_row, Clearable, Valid,};usecrate::mcp::handlers::media_tools::{face_out, is_media_id, rint, rtext, FACE_SELECT};usecrate::mcp::protocol::ToolFailure;pubfn handlers() -> HandlerGroup { &[ ("update_face", update_face), ("list_duplicates", list_duplicates), ("decide_duplicate", decide_duplicate), ]}/// ENGINE SHIM — `MEDIA_DUPLICATE_STATES` (`packages/core/src/constants.ts`),/// whose permanent home is `cotton_core::constants`; that file grows one/// constant at a time beside the engine that reads it, and the only reader/// today is this group's two validators.pubconst MEDIA_DUPLICATE_STATES: &[&str] = &["open", "confirmed", "dismissed"];// ── update_face ─────────────────────────────────────────────────────────────pubstructUpdateFaceArgs {pub id: String,pub person_id: Clearable<String>,pub dismiss_suggestion: bool,}pubfn validate_update_face(args: &Map<String, Value>) -> Valid<UpdateFaceArgs> {letSome(id) = require_string(args, "id") else {return fail("id must be a face's id, from get_photo"); };let person_id = clearable_string(args, "personId");let dismiss = optional_boolean(args, "dismissSuggestion")?.unwrap_or(false);if person_id.is_unchanged() && !dismiss {return fail("nothing to decide — pass personId (who this is, or null to clear it) or \ dismissSuggestion: true", ); }if !person_id.is_unchanged() && dismiss {return fail("one decision per call — either name the person (personId) or dismiss the suggestion", ); }Ok(UpdateFaceArgs { id, person_id, dismiss_suggestion: dismiss, })}fn face_row(ctx: &Ctx<'_>, id: &str) -> Result<Row, ToolFailure> { ctx.db() .get( &format!("{FACE_SELECT}\n WHERE f.workspace_id = ? AND f.id = ?"), &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new(format!("no face {id} — face ids come from get_photo")))}/// The owner's answer about one face.////// Naming a person (or clearing one) also clears the suggestion — a decided/// face carries no opinion — and dismissing a suggestion stamps/// `suggestion_dismissed_at` so the Mac never suggests that face again. The/// owner's answer replaces the engine's link (`person_by` goes), and clearing/// a face the engine LINKED is the owner saying "not them": it is stamped/// dismissed, so the Mac neither links nor suggests that face again.pubfn update_face(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_update_face(args)?;// READ FIRST: the writer upserts, so an id nobody minted would otherwise// become a face row rather than a refusal.let before = face_row(ctx, &args.id)?;let record_id = rtext(&before, "record_id").unwrap_or_default();letmut patch = Map::new();match &args.person_id {Clearable::Unchanged => {if args.dismiss_suggestion {if rtext(&before, "suggested_person_id").is_none() {returnErr(ToolFailure::new("this face carries no suggestion to dismiss", )); } patch.insert("suggested_person_id".to_string(), Value::Null); patch.insert("suggested_distance".to_string(), Value::Null); patch.insert("suggestion_dismissed_at".to_string(),Value::from(now_iso(ctx)), ); } } decision => {let person_id = match decision {Clearable::Set(person_id) => {let known = ctx .db() .get("SELECT id FROM cotton_people WHERE workspace_id = ? AND id = ? AND archived_at IS NULL", &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(person_id.clone()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))?;if known.is_none() {returnErr(ToolFailure::new(format!("no person {person_id} — person ids come from list_people" ))); }Value::from(person_id.clone()) } _ => Value::Null, };let unlinking = person_id.is_null() && rtext(&before, "person_by").is_some(); patch.insert("person_id".to_string(), person_id); patch.insert("person_by".to_string(), Value::Null); patch.insert("suggested_person_id".to_string(), Value::Null); patch.insert("suggested_distance".to_string(), Value::Null); patch.insert("suggestion_dismissed_at".to_string(),if unlinking { Value::from(now_iso(ctx)) } else { Value::Null }, ); } } update_row(ctx, "cotton_media_faces", &args.id, patch)?; ctx.commit()?;let after = face_row(ctx, &args.id)?;letmut out = Map::new(); out.insert("face".to_string(), face_out(&after)); out.insert("photoId".to_string(), Value::from(record_id));Ok(Value::Object(out))}// ── the near-duplicate proposals ────────────────────────────────────────────/// A pair with a picture in the bin is no pair to decide: the one binned is/// deleted, waiting.const BOTH_OUT_OF_BIN: &str = "keep_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) \ AND copy_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)";const DUPLICATE_COLUMNS: &str ="SELECT id, record_kind, keep_id, copy_id, distance, method, state, decided_at FROM cotton_media_duplicates";fn duplicate_out(row: &Row) -> Map<String, Value> {letmut out = Map::new(); out.insert("id".to_string(), rtext(row, "id").map_or(Value::Null, Value::from), ); out.insert("copyId".to_string(), rtext(row, "copy_id").map_or(Value::Null, Value::from), ); out.insert("distance".to_string(),Value::from(rint(row, "distance").unwrap_or(0)), ); out.insert("method".to_string(), rtext(row, "method").map_or(Value::Null, Value::from), ); out.insert("state".to_string(), rtext(row, "state").map_or(Value::Null, Value::from), ); put( &mut out,"decidedAt", rtext(row, "decided_at").map(Value::from), ); out}pubstructListDuplicatesArgs {pub state: Option<String>,pub keep: Option<String>,pub limit: i64,}pubfn validate_list_duplicates(args: &Map<String, Value>) -> Valid<ListDuplicatesArgs> {let state = optional_enum(args, "state", MEDIA_DUPLICATE_STATES)?;let keep = optional_string(args, "keep");ifletSome(keep) = &keep {if !is_media_id(keep, "photo") {return fail("keep must be a photo's id — \"photo:\" and its content hash"); } }Ok(ListDuplicatesArgs { state, keep, limit: bounded_limit(args, 100, 500), })}/// Proposals grouped by the photo proposed as the keep.pubfn list_duplicates(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_list_duplicates(args)?;letmut where_parts = vec!["workspace_id = ?".to_string(), BOTH_OUT_OF_BIN.to_string()];letmut params: Vec<SqlValue> = vec![SqlValue::Text(ctx.workspace_id.to_string())];ifletSome(state) = &args.state { where_parts.push("state = ?".to_string()); params.push(SqlValue::Text(state.clone())); }ifletSome(keep) = &args.keep { where_parts.push("keep_id = ?".to_string()); params.push(SqlValue::Text(keep.clone())); } params.push(SqlValue::Integer(args.limit));let sql = format!("{DUPLICATE_COLUMNS} WHERE {} ORDER BY keep_id ASC, distance ASC, copy_id ASC LIMIT ?", where_parts.join(" AND ") );let found = ctx .db() .all(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))?;// Grouped in FIRST-SEEN order, which the `ORDER BY` has already made keep// order — a map that re-sorted would be a second opinion about the page.letmut groups: Vec<(String, Vec<Value>)> = Vec::new();for row in &found {let keep_id = rtext(row, "keep_id").unwrap_or_default();let shaped = Value::Object(duplicate_out(row));match groups.iter_mut().find(|(id, _)| *id == keep_id) {Some((_, copies)) => copies.push(shaped),None => groups.push((keep_id, vec![shaped])), } }letmut out = Map::new(); out.insert("groups".to_string(),Value::Array( groups .into_iter() .map(|(keep_id, copies)| {letmut group = Map::new(); group.insert("keepId".to_string(), Value::from(keep_id)); group.insert("copies".to_string(), Value::Array(copies));Value::Object(group) }) .collect(), ), ); out.insert("total".to_string(), Value::from(found.len()));Ok(Value::Object(out))}pubstructDecideDuplicateArgs {pub id: String,pub state: String,}pubfn validate_decide_duplicate(args: &Map<String, Value>) -> Valid<DecideDuplicateArgs> {letSome(id) = require_string(args, "id") else {return fail("id must be a proposal's id, from list_duplicates"); };letSome(state) = optional_enum(args, "state", MEDIA_DUPLICATE_STATES)? else {return fail(format!("state is required — one of: {}", MEDIA_DUPLICATE_STATES.join(", ") )); };Ok(DecideDuplicateArgs { id, state })}/// The owner's decision on one proposal; `open` takes it back. Deletes nothing.pubfn decide_duplicate(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_decide_duplicate(args)?;let one = |ctx: &Ctx<'_>, id: &str| -> Result<Option<Row>, ToolFailure> { ctx.db() .get( &format!("{DUPLICATE_COLUMNS} WHERE workspace_id = ? AND id = ?"), &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string())) };if one(ctx, &args.id)?.is_none() {returnErr(ToolFailure::new(format!("no proposal {} — ids come from list_duplicates", args.id ))); }letmut patch = Map::new(); patch.insert("state".to_string(), Value::from(args.state.clone())); patch.insert("decided_at".to_string(),if args.state == "open" {Value::Null } else {Value::from(now_iso(ctx)) }, ); update_row(ctx, "cotton_media_duplicates", &args.id, patch)?; ctx.commit()?;let after = one(ctx, &args.id)?.ok_or_else(|| {ToolFailure::new(format!("proposal {} vanished during the write", args.id)) })?;letmut out = Map::new(); out.insert("keepId".to_string(), rtext(&after, "keep_id").map_or(Value::Null, Value::from), );for (key, value) in duplicate_out(&after) { out.insert(key, value); }Ok(Value::Object(out))}