Cotton code
315 lines · 14.9 KB · RustRaw
//! `read.activity` — `/activity`, the screen that says what this phone is//! holding and what the assistant has been doing with it.//!//! ## Why this is a rename rather than a new read//!//! `/activity` was already claimed, by `read.replicaFacts` — four facts about//! the file, described in its own words as *"the transparency log's own//! header"*. A screen may hold exactly one read//! (`reads_tests::no_two_reads_share_a_name_or_a_screen`), and 4k adds no//! route (`routes.rs` is held byte-for-byte against Swift's `Route.allPatterns`//! by the `ios` job's `RouteTableTests`), so the runs and the audit trail fold//! into the read that is already there and it takes the screen's name, as every//! other read in the table is named. Nothing in Swift read the old name — there//! is no `readReplicaFacts` constant in `Boundary.swift` — so the rename costs a//! doc row and nothing else.//!//! ## The one rule this module keeps//!//! **Every sentence a person reads about a run is already composed on the//! server and stamped on the row.** `receipt`, `error` and `task` are carried//! VERBATIM; nothing here or above the boundary re-composes them. That is//! [one-implementation-of-who-wins-the-same-schema-and-conflict-rule] applied//! to a sentence, and Cotton note "Assistant runs — why a question becomes a run" states the same//! rule.//!//! ## What is deliberately not here//!//! `_assistant_run_steps` — which tools a run called, in order. It is an//! underscore table, server-local by construction: never an op, never pulled by//! a phone. Serving the trail needs a route, not a read.use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::shell::file::ReadFile;use cotton_store::driver::Driver;/// How many runs the screen may ask for at once, and the default it gets.////// Refused outside the range rather than clamped: the phone asked for/// something, and an answer quietly cut down to a different size is a wrong/// number nobody is told about. `reminders.desired`'s `horizonDays` sets the/// precedent — *"outside `0..=365` ⇒ a refusal, never a clamp back to the/// default"*.const RUNS_DEFAULT: i64 = cotton_tools::mcp::handlers::common::WHOLE_SET_LIMIT;const RUNS_MAX: i64 = 200;/// The same, for the audit half — every row by default, for the same reason.const AUDIT_DEFAULT: i64 = cotton_tools::mcp::handlers::common::WHOLE_SET_LIMIT;const AUDIT_MAX: i64 = 100;/// The states a run that has not finished is in.////// Named once because two readers count them — this screen and Home's "Working/// on" row — and two lists of the same two words is the drift a shared/// constant exists to prevent.const UNFINISHED: &str = "state IN ('queued','running')";/// `/activity` — the replica's own facts, the assistant's runs, and what an/// assistant has done in this database.pub fn activity(replica: &ReadFile<'_>, args: &Map<String, Value>) -> Result<Value, String> {    let limit = bounded(args, "limit", RUNS_DEFAULT, RUNS_MAX)?;    let audit_limit = bounded(args, "auditLimit", AUDIT_DEFAULT, AUDIT_MAX)?;    let db = replica.driver;    let workspace_id = replica.workspace_id;    Ok(json!({        // The header — the four facts `read.replicaFacts` has always answered,        // carried across unchanged so nothing 4b wrote has to be re-derived.        // They NEST now, and only because folding two lists in beside them        // would leave a top level whose six keys belong to three subjects.        // `replica` (the path) became `replica.path`; nothing else is renamed.        //        // `path` IS GONE (2026-09-15). It printed the file's place on disk —        // on a phone paired to a Mac, that Mac's home folder name — and the        // row only ever meant to say which file is being read. `held` says it:        // a copy on this device, or the file this process serves. No        // filesystem path crosses this boundary to a screen.        "replica": {            "workspaceId": replica.workspace_id,            // The id this file's OPS wear: `_meta.author_id`, minted on the            // file's first write — not the device id `_meta` named it at open.            // Null before anything was written, because no op wears one yet.            "deviceId": file_author(db)?,            "held": replica.held.as_str(),            // The outbox's own count, asked of the store rather than remembered            // here: a number this layer cached would be a second answer to "is            // anything waiting", and the honest one is one query old at most.            "pending": cotton_client::sync::cycle::current_pending(replica.driver),        },        "runs": runs(db, workspace_id, limit)?,        "working": working_on(db, workspace_id)?,        "audit": audit(db, workspace_id, audit_limit)?,        "auditTruncated": audit_truncated(db, workspace_id, audit_limit)?,    }))}/// The file's author, or null on a file nothing has written to yet.fn file_author(db: &Driver) -> Result<Value, String> {    Ok(db        .get("SELECT author_id FROM _meta", &[])        .map_err(|error| error.to_string())?        .and_then(|row| row.text("author_id").filter(|id| !id.is_empty()).map(str::to_string))        .map_or(Value::Null, Value::from))}/// The runs, newest first.////// **Ordered by `COALESCE(finished_at, started_at, queued_at)`**, which is the/// only instant every state has: a `queued` row has none of the first two, a/// `running` row has no `finished_at`, and ordering by any single column would/// put a whole state at one end of the list. `id ASC` breaks a tie the way/// Home's session-bus read does, so two devices at least agree with each other.////// Weighed against `list_runs`: there is no such tool. `cotton_assistant_runs`/// is in `SUPPORTING_TABLES` and the only verb that touches it is `cancel_run`/// — nobody lists a run for an assistant — so this is a query written here/// rather than a handler restated.fn runs(db: &Driver, workspace_id: &str, limit: i64) -> Result<Value, String> {    let rows = db        .all(            "SELECT id, source_kind, source_id, record_kind, record_id, session_id, class, state, \             task, receipt, turns, input_tokens, output_tokens, cost_usd, result_note_id, \             stopped_reason, error, queued_at, started_at, finished_at \               FROM cotton_assistant_runs WHERE workspace_id = ? \              ORDER BY COALESCE(finished_at, started_at, queued_at) DESC, id ASC LIMIT ?",            &[text(workspace_id), SqlValue::Integer(limit)],        )        .map_err(|error| error.to_string())?;    Ok(Value::Array(        rows.iter()            .map(|row| {                json!({                    "id": row.text("id"),                    "sourceKind": row.text("source_kind"),                    "sourceId": row.text("source_id"),                    "recordKind": row.text("record_kind"),                    "recordId": row.text("record_id"),                    "sessionId": row.text("session_id"),                    "class": row.text("class"),                    "state": row.text("state"),                    // The three sentences the server composed. Carried, never                    // rebuilt — see the module note.                    "task": row.text("task"),                    "receipt": row.text("receipt"),                    "error": row.text("error"),                    "turns": row.int("turns").unwrap_or(0),                    "inputTokens": row.int("input_tokens").unwrap_or(0),                    "outputTokens": row.int("output_tokens").unwrap_or(0),                    // NULL is "not costed", which is not the same as free, so                    // it stays null rather than becoming 0.0.                    "costUsd": or_null(row.real("cost_usd")),                    "resultNoteId": row.text("result_note_id"),                    "stoppedReason": row.text("stopped_reason"),                    "queuedAt": row.text("queued_at"),                    "startedAt": row.text("started_at"),                    "finishedAt": row.text("finished_at"),                })            })            .collect(),    ))}/// How many runs are in flight, and the oldest one's task.////// **Two readers, one function**: `/activity` draws it as `working` and Home/// draws it as `workingOn`, and a second implementation of "how many runs are/// in flight" is two screens able to disagree about the same queue.////// **The count is `SELECT COUNT(*)` over the whole table, never the length of/// the capped list above.** Measuring `runs` would answer "50" for a workspace/// with four hundred runs and never say so, which is the silent wrong answer/// this repo bans (`reads.rs`'s own note on why Home's figures are queries).////// `count: 0` ⇒ both `oldest*` are null, and the object is never absent: the/// Swift decoder is written for present-or-null, as every other figure in these/// reads is.pub fn working_on(db: &Driver, workspace_id: &str) -> Result<Value, String> {    let count = db        .get(            &format!(                "SELECT COUNT(*) AS n FROM cotton_assistant_runs \                  WHERE workspace_id = ? AND {UNFINISHED}"            ),            &[text(workspace_id)],        )        .map_err(|error| error.to_string())?        .and_then(|row| row.int("n"))        .unwrap_or(0);    // The OLDEST by `queued_at`, which is the order the worker serves the queue    // in (`assistant::worker::read_queue`, `ORDER BY queued_at`) — so the run    // named here is the one that has been waiting longest, whether it is    // `queued` or already `running`.    let oldest = db        .get(            &format!(                "SELECT task, queued_at FROM cotton_assistant_runs \                  WHERE workspace_id = ? AND {UNFINISHED} \                  ORDER BY queued_at ASC, id ASC LIMIT 1"            ),            &[text(workspace_id)],        )        .map_err(|error| error.to_string())?;    Ok(json!({        "count": count,        // The task VERBATIM. The sentence the design asks for — "Working on 2 ·        // Researching X · 12 min" — is composed on the screen out of this task        // and this instant; the AGE in words is `CottonUI/Format`'s and never        // this layer's.        "oldestTask": oldest.as_ref().and_then(|row| row.text("task")),        "oldestQueuedAt": oldest.as_ref().and_then(|row| row.text("queued_at")),    }))}/// What an assistant has done in this database, newest first.////// **`token_hash` is never selected**: the column is a/// hash of a secret this device saw exactly once at mint, and a read that/// carried it would put it on every screen refresh for no reader at all.////// `token_name` is joined from `cotton_mcp_tokens` because the audit row holds/// only the id, and a screen that showed a uuid would be asking the person to/// remember which connection that was.////// **LEFT, not INNER, and it is a defence rather than a case.** The schema/// cascades — `cotton_mcp_audit.token_id` REFERENCES `cotton_mcp_tokens(id) ON/// DELETE CASCADE`, and foreign keys are ON at every open — so an audit row/// cannot outlive its token in a consistent file, and the null arm here is/// currently unreachable. It is written anyway because the alternative is a/// list whose LENGTH depends on a join: an INNER join that lost a name would/// drop the row, and a transparency log that silently shortens itself is the/// exact failure this screen exists to make impossible. A missing name is a/// `null` on a row that is still there.fn audit(db: &Driver, workspace_id: &str, limit: i64) -> Result<Value, String> {    let rows = db        .all(            "SELECT a.id AS id, a.token_id AS token_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 = ? \              ORDER BY a.created_at DESC, a.id ASC LIMIT ?",            &[text(workspace_id), SqlValue::Integer(limit)],        )        .map_err(|error| error.to_string())?;    Ok(Value::Array(        rows.iter()            .map(|row| {                json!({                    "id": row.text("id"),                    "tokenId": row.text("token_id"),                    "tokenName": row.text("token_name"),                    "tool": row.text("tool"),                    "ok": row.int("ok").unwrap_or(0) != 0,                    "argsSummary": row.text("args_summary"),                    "createdAt": row.text("created_at"),                })            })            .collect(),    ))}/// Whether the file holds more audit rows than were handed up.////// A `COUNT(*)` rather than `rows.len() == limit`, for the reason/// [`working_on`]'s count is one: a list that happens to be exactly `limit`/// long is not evidence that anything was left behind, and a screen drawing/// "there is more" off that coincidence would say it half the time it is false.fn audit_truncated(db: &Driver, workspace_id: &str, limit: i64) -> Result<bool, String> {    let total = db        .get(            "SELECT COUNT(*) AS n FROM cotton_mcp_audit WHERE workspace_id = ?",            &[text(workspace_id)],        )        .map_err(|error| error.to_string())?        .and_then(|row| row.int("n"))        .unwrap_or(0);    Ok(total > limit)}/// A whole-number argument inside its declared range, or a refusal naming it.////// Absent — or an explicit `null`, which this boundary treats as absent, since/// a Swift optional encodes that way and asking for "no opinion" is not asking/// for something out of range — is the default. Anything else out of range, or/// not a whole number at all, is an `Err`, which becomes `unreadable` at the/// boundary with this sentence in it. Both readings are pinned by/// `a_limit_outside_its_range_is_refused_with_the_range_named`.fn bounded(args: &Map<String, Value>, name: &str, default: i64, max: i64) -> Result<i64, String> {    use cotton_tools::mcp::handlers::common::{WHOLE_SET, WHOLE_SET_LIMIT};    match args.get(name) {        // No opinion IS the whole set: this is a screen's read and nothing        // else's, and a screen that draws fifty of two hundred runs with no        // way to reach the rest is the shortfall every screen read is held        // against. A number is still a number, refused out of range below.        None | Some(Value::Null) => Ok(default),        Some(Value::String(word)) if word == WHOLE_SET => Ok(WHOLE_SET_LIMIT),        Some(value) => value            .as_i64()            .filter(|asked| (1..=max).contains(asked))            .ok_or_else(|| format!("`{name}` is a whole number of rows between 1 and {max}")),    }}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn or_null(value: Option<f64>) -> Value {    value.map_or(Value::Null, |value| json!(value))}#[cfg(test)]#[path = "activity_tests.rs"]mod tests;