//! What every chat verb repeats: the table names, the two row reads that come//! before almost every write, and the ONE way this module authors a message.//!//! The port of `packages/core/src/services/chat/shared.ts`, plus the two//! helpers `groupVerbs.ts` kept to itself and `messageVerbs.ts` needed as well.//!//! A verb that cannot find its row fails LOUDLY. A mutation that quietly does//! nothing is worse than one that says it did nothing — and the refusal is the//! same sentence whether the row is absent or belongs to another workspace,//! which is this crate's probe-resistance rule everywhere else too.use serde_json::{Map, Value};use cotton_core::messages::apply_message_write::MessageWriteThread;use cotton_core::messages::MessageMeta;use cotton_store::driver::Row;use rusqlite::types::ValueasSqlValue;usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::now_iso;usecrate::mcp::protocol::ToolFailure;pubconst THREADS: &str = "cotton_msg_threads";pubconst MESSAGES: &str = "cotton_msg_messages";pubconst CONTACTS: &str = "cotton_msg_contacts";pubconst PARTICIPANTS: &str = "cotton_msg_thread_participants";pubconst REACTIONS: &str = "cotton_msg_reactions";pubconst RECEIPTS: &str = "cotton_msg_receipts";/// The thread this verb acts on, scoped to the workspace.////// ONE sentence for "no such thread" and for "not yours": a caller learns/// whether a row exists only if it is theirs.pubfn require_thread(ctx: &Ctx<'_>, thread_id: &str) -> Result<Row, ToolFailure> { ctx.db() .get("SELECT * FROM cotton_msg_threads WHERE workspace_id = ? AND id = ?", &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(thread_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new("no such conversation in this database"))}/// The message this verb acts on, scoped to the workspace.pubfn require_message(ctx: &Ctx<'_>, message_id: &str) -> Result<Row, ToolFailure> { ctx.db() .get("SELECT * FROM cotton_msg_messages WHERE workspace_id = ? AND id = ?", &[SqlValue::Text(ctx.workspace_id.to_string()),SqlValue::Text(message_id.to_string()), ], ) .map_err(|error| ToolFailure::new(error.to_string()))? .ok_or_else(|| ToolFailure::new("no such message in this database"))}/// The three columns [`apply_message_write`] needs off a thread row.pubfn write_target<'a>(thread: &'a Row, fallback_id: &'a str) -> MessageWriteThread<'a> {MessageWriteThread { id: thread.text("id").unwrap_or(fallback_id), workspace_id: thread.text("workspace_id").unwrap_or_default(), last_message_at: thread.text("last_message_at"), }}/// The thread's newest VISIBLE row — what the conversation list is quoting.////// "Visible" is the same three-part rule every reader applies: not hidden, not/// cleared away, and — with `exclude` — not one of the rows this call is about/// to hide. Passing the about-to-be-hidden ids rather than re-reading after the/// write is what lets the whole act stay ONE batch.pubfn newest_visible( ctx: &Ctx<'_>, thread: &Row, exclude: &[String],) -> Result<Option<Row>, ToolFailure> {let thread_id = thread.text("id").unwrap_or_default().to_string();letmut sql = String::from("SELECT * FROM cotton_msg_messages WHERE thread_id = ? AND hidden_at IS NULL AND trashed_at IS NULL", );letmut params = vec![SqlValue::Text(thread_id)];ifletSome(cleared) = thread.text("cleared_before").filter(|at| !at.is_empty()) { sql.push_str(" AND sent_at > ?"); params.push(SqlValue::Text(cleared.to_string())); }if !exclude.is_empty() { sql.push_str(" AND id NOT IN ("); sql.push_str(&vec!["?"; exclude.len()].join(", ")); sql.push(')'); params.extend(exclude.iter().map(|id| SqlValue::Text(id.clone()))); } sql.push_str(" ORDER BY sent_at DESC, id DESC LIMIT 1"); ctx.db() .get(&sql, ¶ms) .map_err(|error| ToolFailure::new(error.to_string()))}/// Decode the current keyed media format; an invalid attachment fails the edit.pubfn media_of(row: &Row) -> Result<Vec<cotton_core::messages::MessageMedia>, ToolFailure> {let raw = row.text("media") .ok_or_else(|| ToolFailure::new("message media must be JSON text"))?; serde_json::from_str(raw) .map_err(|error| ToolFailure::new(format!("invalid message media: {error}")))}/// The `meta` column, decoded, or the empty object.pubfn meta_of(row: &Row) -> MessageMeta { row.text("meta") .and_then(|raw| serde_json::from_str(raw).ok()) .unwrap_or_default()}/// A thread patch, queued. Every private-state verb in [`super::threads`] is/// one of these.pubfn patch_thread( ctx: &mutCtx<'_>, thread_id: &str, pairs: Vec<(&str, Value)>,) -> Result<(), ToolFailure> {letmut patch = Map::new();for (key, value) in pairs { patch.insert(key.to_string(), value); } ctx.writer()?.upsert(THREADS, thread_id, patch);Ok(())}/// `now`, as every verb in this module stamps it.pubfn stamp(ctx: &Ctx<'_>) -> String { now_iso(ctx)}#[cfg(test)]mod tests {usesuper::*;// RULE: Invalid media must fail the edit, never erase attachments through an empty preview fallback. #[test]fn malformed_media_is_refused() {for value in [SqlValue::Null, SqlValue::Text("not json".into()), SqlValue::Text(r#"[{"url":"https://example.invalid/old.jpg","contentType":"image/jpeg"}]"#.into())] {let row = Row::new(vec![("media".into(), value)]); assert!(media_of(&row).is_err()); } assert!(media_of(&Row::default()).is_err()); assert!(media_of(&Row::new(vec![("media".into(), SqlValue::Text("[]".into()))])).unwrap().is_empty()); }}