//! `media_repair` — the photos whose bytes are on no machine (todo 5365af8f).//!//! On 4 September 2026 the media-index sweep's first backfill wrote a photo//! row for every picture key a chat message named, without asking whether the//! bytes existed; 3,348 of the owner's draw as broken pictures. The sweep no//! longer does that. This act is the owner's view of the rows it left behind.//!//! A photo is MISSING when none of its objects — its own key and every key a//! sighting points at — is in this server's store or held by a live machine.//! Any one is enough: the same bytes under another chat's key still draw.//!//! `dry_run: true` reads and writes nothing. What a real run does is the//! owner's decision still to make, so `dry_run: false` refuses by name.use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::protocol::ToolFailure;/// How many missing photo ids the answer names, to look one up by.const SAMPLE: usize = 20;fn refuse(error: impl std::fmt::Display) -> ToolFailure {ToolFailure::new(error.to_string())}pubfn media_repair(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let dry_run = args.get("dry_run").and_then(Value::as_bool).unwrap_or(true);if !dry_run {returnErr(ToolFailure::new("media_repair runs as a dry run only for now: what a real run does to these photos \ is the owner's decision still to make", )); }let head = ctx.services.media_head.clone().ok_or_else(|| {ToolFailure::new("media_repair asks this server's store for each photo's bytes, and this server has none") })?;let driver = ctx.db();let workspace = SqlValue::Text(ctx.workspace_id.to_string());letmut keys: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();letmut thread_of: BTreeMap<String, String> = BTreeMap::new();for sighting in driver .all("SELECT record_id, key, thread_id FROM cotton_media_sightings WHERE workspace_id = ? AND record_kind = 'photo' ORDER BY seen_at ASC, id ASC", std::slice::from_ref(&workspace), ) .map_err(refuse)? {let (Some(record_id), Some(key)) = (sighting.text("record_id"), sighting.text("key")) else {continue; }; keys.entry(record_id.to_string()).or_default().insert(key.to_string());ifletSome(thread_id) = sighting.text("thread_id") { thread_of.entry(record_id.to_string()).or_insert_with(|| thread_id.to_string()); } }let photos = driver .all("SELECT id, key, created_at FROM cotton_photos WHERE workspace_id = ? AND trashed_at IS NULL ORDER BY created_at ASC, id ASC", std::slice::from_ref(&workspace), ) .map_err(refuse)?;letmut missing: Vec<(String, String)> = Vec::new();for photo in &photos {let id = photo.text("id").unwrap_or_default().to_string();letmut objects = keys.remove(&id).unwrap_or_default();ifletSome(key) = photo.text("key") { objects.insert(key.to_string()); }letmut reachable = false;for key in &objects {if head(key).map_err(refuse)? || !cotton_store::media_holdings::holders_of( driver, ctx.workspace_id, key, cotton_store::media_holdings::Tier::Original, ) .map_err(refuse)? .is_empty() { reachable = true;break; } }if !reachable { missing.push((id, photo.text("created_at").unwrap_or_default().to_string())); } }letmut by_thread: BTreeMap<String, i64> = BTreeMap::new();for (id, _) in &missing { *by_thread.entry(thread_of.get(id).cloned().unwrap_or_default()).or_default() += 1; }letmut threads: Vec<(String, i64)> = by_thread.into_iter().collect(); threads.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));letmut chats = Vec::with_capacity(threads.len());for (thread_id, count) in threads {let title = if thread_id.is_empty() {None } else { driver .get("SELECT title FROM cotton_msg_threads WHERE id = ?", &[SqlValue::Text(thread_id.clone())], ) .map_err(refuse)? .and_then(|row| row.text("title").map(str::to_string)) }; chats.push(json!({"threadId": (!thread_id.is_empty()).then_some(thread_id),"title": title,"missing": count, })); }Ok(json!({"dryRun": true,"photos": photos.len(),"missing": missing.len(),"createdFrom": missing.iter().map(|(_, at)| at).min(),"createdTo": missing.iter().map(|(_, at)| at).max(),"byChat": chats,"sample": missing.iter().take(SAMPLE).map(|(id, _)| id).collect::<Vec<_>>(), }))}