//! The generic verbs over `/activity`'s two built-in tables, whose engine //! (`assistant`) keeps no table by those names. Each is a VIEW //! (`cotton_core::definitions::VIEW_TABLES`) over what the old Activity //! screen read (`cotton_ffi::phone::activity`, `read.activity`): //! //! - **`activity`** — one record, id `this`: what this database is, as the //! device reading it says. `workspace_id` is the file's own; `device_id` and //! `held` (WHICH file — a copy on this device, or the file this Mac serves, //! never a path on any disk) come from `ToolServices::this_file`, which only //! the owner's own app fills; `pending` counts the changes still waiting in //! this file's outbox, and is absent when it cannot be counted. //! - **`assistant_call`** — `cotton_mcp_audit` joined to the connection's name //! (LEFT: a call whose connection is gone keeps its row, nameless), newest //! first. `token_hash` is never read. `outcome` is `ok` or `refused`. //! //! **Read in the owner's own app only.** Nothing an assistant could reach read //! these rows before — no tool lists a run or the audit trail — and a //! connection reading what every other connection asked for is a new door, so //! a read through any other connection is refused. //! //! **No writes.** Every create, update and delete on either is refused and //! writes nothing. use cotton_core::definitions::TableDefinition; use cotton_core::rules::activity_words::call_outcome; use cotton_core::records::{holds, matches_query, Data, Verb, WhereClause}; use rusqlite::types::Value as SqlValue; use serde_json::Value; use super::builtin::Op; use super::{sql_err, Page, Stored}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::Valid; use crate::mcp::protocol::ToolFailure; /// What this database is. pub const ACTIVITY: &str = "activity"; /// The connected assistants' calls. pub const CALLS: &str = "assistant_call"; /// The `activity` table's one record. pub const THIS: &str = "this"; /// What `held` reads when no device said how it holds the file. const NOT_KNOWN: &str = "Not known yet"; /// Is this one of the two activity tables? pub fn is_activity(definition: &TableDefinition) -> bool { definition.has_engine() && [ACTIVITY, CALLS].contains(&definition.id.as_str()) } /// A write may take its record away: none here does. pub(super) fn update_takes_it_away(_definition: &TableDefinition) -> bool { false } /// Only the owner's own app reads these tables — see the module header. fn owner_reads(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<()> { if ctx.is_owner_app() { Ok(()) } else { Err(ToolFailure::new(format!( "{} is read in the owner's own app only", definition.plural ))) } } // ── the records ───────────────────────────────────────────────────────────── fn stored(id: String, data: Data, created_at: Option) -> Stored { Stored { id, data, created_at, updated_at: None, deleted_at: None, byline: None, } } fn put(data: &mut Data, key: &str, value: Option) { if let Some(value) = value.filter(|value| !value.is_null()) { data.insert(key.to_string(), value); } } /// The `activity` record: what this database is, as this device reads it. fn this_record(ctx: &Ctx<'_>, definition: &TableDefinition) -> Stored { let file = ctx.services.this_file.as_ref(); let mut data = Data::new(); data.insert("title".into(), Value::from(definition.name.clone())); data.insert("workspace_id".into(), Value::from(ctx.workspace_id)); put( &mut data, "device_id", file.and_then(|file| file.device_id.clone()).map(Value::from), ); let held = file.map_or(NOT_KNOWN, |file| file.held.sentence()); data.insert("held".into(), Value::from(held)); // A count asked of the outbox itself, never remembered; one that cannot // be counted is unknown, which is not the same as nothing waiting. put( &mut data, "pending", cotton_store::outbox::pending_count(ctx.read.driver()) .ok() .map(Value::from), ); stored(THIS.to_string(), data, None) } fn call_record(row: &cotton_store::Row) -> Stored { let text = |column: &str| row.text(column).map(|text| Value::from(text.to_string())); let mut data = Data::new(); put(&mut data, "tool", text("tool")); put(&mut data, "token_name", text("token_name")); data.insert("outcome".into(), Value::from(call_outcome(row.int("ok")))); put(&mut data, "args_summary", text("args_summary")); put(&mut data, "created_at", text("created_at")); stored( row.text("id").unwrap_or_default().to_string(), data, row.text("created_at").map(str::to_string), ) } /// `LIMIT ? OFFSET ?` for a read: the page itself (and one more, to know /// whether there is a next) when nothing narrows it in memory, else every /// row. fn window(narrowed: bool, offset: i64, limit: i64) -> (i64, i64) { if narrowed { (-1, 0) } else { (limit + 1, offset) } } fn calls(ctx: &Ctx<'_>, id: Option<&str>, window: (i64, i64)) -> Valid> { let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())]; let only = id.map_or("", |id| { params.push(SqlValue::Text(id.to_string())); " AND a.id = ?" }); params.push(SqlValue::Integer(window.0)); params.push(SqlValue::Integer(window.1)); // `token_hash` is never selected; the connection's NAME is joined, and a // LEFT join keeps a call whose connection is gone. let rows = ctx .read .driver() .all( &format!( "SELECT a.id AS id, t.name AS token_name, a.tool AS tool, \ a.args_summary AS args_summary, a.ok AS ok, a.created_at AS created_at \ FROM cotton_mcp_audit a \ LEFT JOIN cotton_mcp_tokens t ON t.id = a.token_id \ WHERE a.workspace_id = ?{only} \ ORDER BY a.created_at DESC, a.id ASC LIMIT ? OFFSET ?" ), ¶ms, ) .map_err(sql_err)?; Ok(rows.iter().map(call_record).collect()) } pub(super) fn read_one( ctx: &Ctx<'_>, definition: &TableDefinition, id: &str, ) -> Valid> { owner_reads(ctx, definition)?; let one = (2, 0); Ok(match definition.id.as_str() { ACTIVITY => (id == THIS).then(|| this_record(ctx, definition)), _ => calls(ctx, Some(id), one)?.into_iter().next(), }) } pub(super) fn list( ctx: &Ctx<'_>, definition: &TableDefinition, project: Option<&str>, query_text: Option<&str>, clauses: &[WhereClause], offset: i64, limit: i64, ) -> Valid { let zone = crate::mcp::handlers::common::where_zone(ctx)?; owner_reads(ctx, definition)?; if project.is_some() { return Err(ToolFailure::new(format!( "{} do not belong to projects", definition.plural ))); } let narrowed = query_text.is_some() || !clauses.is_empty(); let read = window(narrowed, offset, limit); let found = match definition.id.as_str() { ACTIVITY => vec![this_record(ctx, definition)], _ => calls(ctx, None, read)?, }; let skip = if narrowed || definition.id == ACTIVITY { offset } else { 0 }; let listed: Vec = found .into_iter() .filter(|stored| { query_text.is_none_or(|words| matches_query(definition, &stored.data, words)) && clauses.iter().all(|clause| holds(&stored.data, clause, &zone)) }) .collect(); // A narrowed list (and `this`) was read whole, so it counts itself; an // unnarrowed one read one page, so its whole count is asked of the table. let total = if narrowed || definition.id == ACTIVITY { listed.len() as i64 } else { whole_count(ctx)? }; let mut records: Vec = listed .into_iter() .skip(usize::try_from(skip).unwrap_or(usize::MAX)) .take(usize::try_from(limit + 1).unwrap_or(usize::MAX)) .collect(); let more = records.len() as i64 > limit; records.truncate(limit as usize); Ok(Page { records, more, total, }) } /// How many calls this workspace holds in all. fn whole_count(ctx: &Ctx<'_>) -> Valid { let table = "cotton_mcp_audit"; Ok(ctx .read .driver() .get( &format!("SELECT COUNT(*) AS n FROM {table} WHERE workspace_id = ?"), &[SqlValue::Text(ctx.workspace_id.to_string())], ) .map_err(sql_err)? .and_then(|row| row.int("n")) .unwrap_or(0)) } // ── writes ────────────────────────────────────────────────────────────────── /// Why `definition` takes no write of this kind, in its own words. fn refusal(definition: &TableDefinition) -> String { match definition.id.as_str() { ACTIVITY => "Activity is what this database is, read as it stands; nothing on it is \ written by hand" .to_string(), _ => "Calls are the record of what connected assistants did here, and nothing in it is \ written by hand" .to_string(), } } /// The tools a write's plan calls — what `builtin::plan` answers for these /// tables: none. pub(super) fn plan(_id: &str, _op: Op<'_>) -> Vec<&'static str> { Vec::new() } /// Why a change to one of these tables cannot be undone — none can. pub(super) fn undo_refusal(definition: &TableDefinition, _verb: Verb) -> String { refusal(definition) } /// A write to these tables is never possible. pub(super) fn writable(definition: &TableDefinition) -> Valid<()> { Err(ToolFailure::new(refusal(definition))) } pub(super) fn refused(definition: &TableDefinition) -> ToolFailure { ToolFailure::new(refusal(definition)) } /// `update_record` on either table: refused, nothing written. pub(super) fn update( _ctx: &mut Ctx<'_>, definition: &TableDefinition, _id: &str, _patch: &Data, ) -> Valid<()> { Err(refused(definition)) }