//! `set_audience` — who may hold one record of a shared database: an only-you//! hold (`only_you`) or the owner's release (`everyone`). The OWNER'S OWN ACT//! (`McpScope::Owner`: the owner's app calls it from the record tray; an//! assistant never can), and the store's fold refuses a release from anybody//! but the owner at one of their own devices whichever door it came through//! (`cotton_store::audience`).use serde_json::{json, Map, Value};use cotton_store::audience::{self, AUDIENCES, ONLY_YOU};use cotton_store::keep;usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{now_iso, optional_string};usecrate::mcp::handlers::keep_rules::record_target;usecrate::mcp::protocol::ToolFailure;fn failure(error: impl std::fmt::Display) -> ToolFailure {ToolFailure::new(error.to_string())}fn required(args: &Map<String, Value>, argument: &str) -> Result<String, ToolFailure> { optional_string(args, argument) .filter(|value| !value.trim().is_empty()) .ok_or_else(|| ToolFailure::new(format!("{argument} is required")))}/// `set_audience { table, id, audience }`. Setting the audience a record/// already carries changes nothing and writes nothing.pubfn set_audience(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let table = required(args, "table")?;let id = required(args, "id")?;let wanted = required(args, "audience")?;if !AUDIENCES.contains(&wanted.as_str()) {returnErr(ToolFailure::new(format!("audience is one of {}", AUDIENCES.join(", ")))); }// A definition's id (`todo`) or the table a record lives in, as a keep// rule names it.let target = record_target(&keep::record_target_of(&table, &id));letSome((table, id)) = keep::record_target(&target).map(|(t, i)| (t.to_string(), i.to_string())) else {returnErr(ToolFailure::new("table and id name one record")); };let db = ctx.db();let answer = json!({ "table": table, "id": id, "audience": wanted });if audience::of_record(db, &table, &id).map_err(failure)?.as_deref() == Some(wanted.as_str()) {returnOk(answer); }let at = now_iso(ctx);let workspace_id = ctx.workspace_id.to_string();let change = if wanted == ONLY_YOU { audience::mark(ctx.db(), &workspace_id, &table, &id, &at) } else { audience::release(ctx.db(), &workspace_id, &table, &id, &at) } .map_err(failure)?;let patch = change.patch.unwrap_or_default();let writer = ctx.writer()?; writer.upsert(audience::TABLE, &change.row_id, patch); ctx.commit()?;Ok(answer)}