//! THE PHONE LINKS AN EVENT'S ATTENDEES TO PEOPLE once attendees are sealed//! (e2e rulings R3, 16 Nov 2026). The object did it//! (apps/business/src/calendar_engine.ts `linkPeople`) while it could read an//! attendee's email and phone; sealed, it cannot, so the writer of record's//! pass does it here from its own copy, by the same rule://!//! - an attendee is matched to a person by the email or phone it names,//! through the handles People carry (`person_handle`), each handle//! normalised as the import normalises it (cotton-rules `handles_from`);//! - a handle two people claim is neither's;//! - each person matched gains the event as an edge (`cotton_links`, the//! event's `people`), under the derived id every phone and the object//! compute, so two phones write one edge; one already there stays, nobody//! is ever taken off, and an attendee that matches nobody is no person made//! up.//!//! While the object reads attendees in the clear it links them itself and//! this links none. A number without its country code is matched only as//! written (the phone's copy holds no owner region); the object's rule reads//! it in the owner's country.use std::collections::{BTreeMap, BTreeSet};use cotton_core::cotton_rules::handles::{handle_key, handles_from, ContactSource};use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{now_iso, Valid};usecrate::mcp::protocol::ToolFailure;const ATTENDEE: &str = "event_attendee";/// Whether the object links attendees: while their table is not sealed.fn object_links(ctx: &Ctx<'_>) -> Valid<bool> {let held = ctx .read .driver() .get(&format!("SELECT definition FROM {} WHERE id = '{ATTENDEE}'", crate::definitions::TABLE_DEFINITIONS), &[]) .map_err(|error| ToolFailure::new(error.to_string()))?;let sealed = held .and_then(|row| row.text("definition").map(str::to_owned)) .and_then(|text| serde_json::from_str::<Value>(&text).ok()) .is_some_and(|definition| definition.get("seal").is_some_and(|seal| !seal.is_null()));Ok(!sealed)}/// Every live person's handles, `kind:value` → the one person who carries it (a handle two people claim is left out).fn people_by_handle(ctx: &Ctx<'_>) -> Valid<BTreeMap<String, String>> {let found = ctx .read .driver() .all("SELECT h.person_id AS person_id, h.kind AS kind, h.normalised AS normalised FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id AND p.trashed_at IS NULL WHERE h.workspace_id = ? AND h.trashed_at IS NULL AND h.normalised IS NOT NULL", &[SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(|error| ToolFailure::new(error.to_string()))?;letmut claimed: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();for row in &found {let (Some(person), Some(kind), Some(value)) = (row.text("person_id"), row.text("kind"), row.text("normalised")) else { continue }; claimed.entry(format!("{kind}:{value}")).or_default().insert(person.to_owned()); }Ok(claimed.into_iter().filter(|(_, people)| people.len() == 1).filter_map(|(key, people)| people.into_iter().next().map(|person| (key, person))).collect())}/// Link each event's attendees to the people they are (see above). Answers how many edges it made.pubfn link_event_attendees(ctx: &mutCtx<'_>) -> Valid<usize> {if object_links(ctx)? {returnOk(0); }let people = people_by_handle(ctx)?;if people.is_empty() {returnOk(0); }let attendees = ctx .read .driver() .all("SELECT a.event_id AS event_id, a.email AS email, a.phone AS phone FROM cotton_event_attendees a JOIN cotton_events e ON e.id = a.event_id", &[], ) .map_err(|error| ToolFailure::new(error.to_string()))?;letmut wanted: BTreeSet<(String, String)> = BTreeSet::new();for row in &attendees {letSome(event) = row.text("event_id") else { continue };let source = ContactSource { phone: row.text("phone"), email: row.text("email") };for handle in handles_from(&source, None) {ifletSome(person) = people.get(&handle_key(&handle)) { wanted.insert((event.to_owned(), person.clone())); } } }letmut made = 0;for (event, person) in wanted {let edge = cotton_store::protocol::derived_id::link_id_for( &cotton_store::protocol::derived_id::LinkRow { from_kind: "event", from_id: &event, to_kind: "person", to_id: &person, to_database: None }, ctx.file.id(), );let held = !ctx .read .driver() .all("SELECT id FROM cotton_links WHERE id = ?", &[SqlValue::Text(edge.clone())]) .map_err(|error| ToolFailure::new(error.to_string()))? .is_empty();if held {continue; }letmut row = Map::new(); row.insert("id".into(), Value::from(edge.clone())); row.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string())); row.insert("from_kind".into(), Value::from("event")); row.insert("from_id".into(), Value::from(event)); row.insert("to_kind".into(), Value::from("person")); row.insert("to_id".into(), Value::from(person)); row.insert("created_at".into(), Value::from(now_iso(ctx))); ctx.writer()?.upsert("cotton_links", &edge, row); made += 1; }Ok(made)}