Cotton code
508 lines · 20.5 KB · RustRaw
//! `list_keep_rules`, `set_keep_rule`, `clear_keep_rule` — what a phone keeps,//! as the owner reads and changes it.//!//! The rules are rows of `cotton_device_keep` and the one judge that reads//! them is `cotton_store::keep`. THESE VERBS ADD NO SECOND READING: a rule//! written here is the row the judge reads — validated by the store's own//! `keep::check_rule`, at the id the store derives//! (`derived_id::device_keep_id`), with the columns `keep::set_rule` writes —//! and nothing is copied anywhere else. The write goes through this context's//! writer rather than `keep::set_rule`'s own mint so that the ops land in the//! answer: a screen redraws from the tables a write moved, and a serving Mac//! wakes its phones only for a write that minted (guard://! `keep_rules_tests::a_rule_set_here_is_the_row_keep_set_rule_writes`).//!//! The phone's own screen calls the same handlers (`keep.rules`, `keep.set`,//! `keep.clear` in `cotton-ffi`), so there is one write path.//!//! - A MAC KEEPS EVERY ROW: it may take over serving, so a row rule for one is//!   refused (by `keep::check_rule`). What it keeps of its BYTES is one choice//!   (sync programme, lane D, 12 Oct 2026): `kind: "bytes"`, rule//!   `everything` or `rows_only`, read off and written as the Mac's Storage//!   rules for every byte tool (`cotton_store::storage_rules::MacKeeps`) — so//!   Storage and the device row say one thing. A serving Mac keeps everything//!   whatever it says, and its list says so (`serving`).//! - NOTHING NARROWS A PHONE WHILE `keep::NARROWING_GUARDED` IS FALSE. Keep//!   owns that flag and turns it on with the test that drives a phone copy//!   against a served Mac. Until then a table may be kept `all` and a group or//!   a record `always` — both only widen or pin — and `none` and `days:N` are//!   refused with a sentence saying they come after the next update. The list//!   carries the flag (`narrowing`) so a screen offers those choices greyed//!   rather than keeping a copy of it.use cotton_store::keep::{    self, TableRule, ALWAYS, KIND_GROUP, KIND_RECORD, KIND_TABLE, NARROWABLE, PHONE_DEFAULTS,};use cotton_store::protocol::derived_id::device_keep_id;use cotton_store::storage_rules::{self, MacKeeps};use cotton_store::schema::specs::{columns_of, spec_for};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{now_iso, optional_string};use crate::mcp::protocol::ToolFailure;use crate::mcp::writer::Retract;/// What a narrowing rule is refused with while keep's guard is off. A/// screen shows the words after "after the next update" beside a greyed/// choice, so the phrase is held here once.pub const AFTER_THE_NEXT_UPDATE: &str = "after the next update";/// The refusal itself.pub fn narrowing_refusal() -> String {    format!(        "Keeping less than everything on a phone comes {AFTER_THE_NEXT_UPDATE}. Until then a phone \         keeps all of every table, and you can keep a group or a record on it always."    )}/// The refusal a Mac's ROW rules get from these verbs.pub const A_MAC_KEEPS_EVERYTHING: &str =    "A Mac keeps every row: it may take over serving, so only what it keeps of its files can be changed.";/// The kind of the one rule a Mac has: what it keeps of its bytes.pub const KIND_BYTES: &str = "bytes";/// The choices of a Mac's `bytes` rule, in the order a menu lists them, with/// their words.pub static MAC_CHOICES: &[(&str, &str)] = &[    ("everything", "Everything"),    ("rows_only", "Rows only — files come when you open them and go 30 days later"),];/// What a Mac that serves says beside its choice.pub const A_SERVING_MAC_KEEPS_EVERYTHING: &str =    "While this Mac serves it keeps everything; rows only applies when another Mac serves.";/// The words a table a rule may narrow is called by on a page. Every table of/// `keep::NARROWABLE` has a line (guard:/// `keep_rules_tests::every_table_a_rule_may_narrow_has_words`).pub static TABLE_WORDS: &[(&str, &str)] =    &[        ("cotton_email_threads", "Mail"),        ("cotton_msg_threads", "Messages"),        ("cotton_imports", "Message imports"),        ("cotton_stories", "Statuses"),    ];/// The choices a table's line offers, in the order a menu lists them.const TABLE_CHOICES: &[&str] = &["all", "days:30", "days:90", "days:180", "days:365", "none"];/// Is `rule` on a table one that keeps less than everything?pub fn narrows(kind: &str, rule: &str) -> bool {    kind == KIND_TABLE && matches!(TableRule::parse(rule), Some(TableRule::None | TableRule::Days(_)))}/// A rule in words: "everything", "3 months", "never", "always".pub fn rule_words(rule: &str) -> String {    match TableRule::parse(rule) {        Some(TableRule::All) => "everything".to_string(),        Some(TableRule::None) => "never".to_string(),        Some(TableRule::Days(days)) => {            let (count, unit) = if days % 365 == 0 {                (days / 365, "year")            } else if days % 30 == 0 {                (days / 30, "month")            } else if days % 7 == 0 {                (days / 7, "week")            } else {                (days, "day")            };            if count == 1 {                format!("1 {unit}")            } else {                format!("{count} {unit}s")            }        }        None if rule == ALWAYS => "always".to_string(),        None => rule.to_string(),    }}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn failure(error: impl std::fmt::Display) -> ToolFailure {    ToolFailure::new(error.to_string())}fn required(args: &Map<String, Value>, key: &str) -> Result<String, ToolFailure> {    optional_string(args, key)        .filter(|value| !value.trim().is_empty())        .ok_or_else(|| ToolFailure::new(format!("{key} is required")))}/// The device key a `device` argument names: a key as `cotton_devices`/// carries it, or a device row's id (what `list_devices` answers as `id`).fn device_key(ctx: &Ctx<'_>, device: &str) -> Result<Option<String>, ToolFailure> {    Ok(ctx        .db()        .get(            "SELECT device_id FROM cotton_devices WHERE device_id = ?1 OR id = ?1 \             ORDER BY (device_id = ?1) DESC, (revoked_at IS NULL) DESC LIMIT 1",            &[text(device)],        )        .map_err(failure)?        .and_then(|row| row.text("device_id").map(str::to_string)))}/// A record rule's target, with a definition id taken as the table its/// records live in: `note:<id>` is `cotton_notes:<id>`, a table a person/// defined is its own table, `cotton_<table>:<id>` (`tables::made_table`). A/// target already naming a store table stands.pub fn record_target(target: &str) -> String {    let Some((table, row_id)) = keep::record_target(target) else {        return target.to_string();    };    if spec_for(table).is_some() || made_of(table).is_some() {        return target.to_string();    }    match cotton_core::definitions::builtin_store_table(table) {        Some(store) => keep::record_target_of(store, row_id),        None => keep::record_target_of(&crate::mcp::handlers::tables::made_table(table), row_id),    }}/// The made table whose own store table `table` is: a name no compiled spec/// owns, `cotton_<id>` with `<id>` a table id.fn made_of(table: &str) -> Option<&str> {    if !cotton_store::schema::package_shape::may_arrive(table) {        return None;    }    table.strip_prefix("cotton_").filter(|id| cotton_core::definitions::is_valid_id(id))}/// A group's name, as its page heads it.fn group_name(ctx: &Ctx<'_>, id: &str) -> Result<String, ToolFailure> {    let db = ctx.db();    if let Some(row) = db        .get("SELECT title FROM cotton_media_albums WHERE id = ?", &[text(id)])        .map_err(failure)?    {        let title = row.text("title").unwrap_or_default();        return Ok(format!("Album {title}").trim().to_string());    }    let name = db        .get("SELECT name FROM cotton_groups WHERE id = ?", &[text(id)])        .map_err(failure)?        .and_then(|row| row.text("name").map(str::to_string))        .filter(|name| !name.trim().is_empty());    Ok(name.unwrap_or_else(|| "A group".to_string()))}/// The columns a record is named by, first held wins.const TITLE_COLUMNS: &[&str] = &["title", "name", "subject", "display_name", "caption", "text", "body"];/// A record's name, as its slip heads it — or "A record" when it says none.fn record_name(ctx: &Ctx<'_>, target: &str) -> Result<String, ToolFailure> {    let fallback = || Ok("A record".to_string());    let Some((table, row_id)) = keep::record_target(target) else {        return fallback();    };    // A made table's record is named by its definition's title column.    if let Some(id) = made_of(table) {        return Ok(made_record_name(ctx, id, row_id)?.unwrap_or_else(|| "A record".to_string()));    }    // Only a table this build knows is read, so a name in a stored row can    // never become SQL.    let (Some(spec), Some(columns)) = (spec_for(table), columns_of(table)) else {        return fallback();    };    let row = ctx        .db()        .get(&format!("SELECT * FROM {} WHERE id = ?", spec.name), &[text(row_id)])        .map_err(failure)?;    let Some(row) = row else { return fallback() };    let data: Option<Value> = row.text("data").and_then(|raw| serde_json::from_str(raw).ok());    for column in TITLE_COLUMNS {        let held = if columns.iter().any(|(name, _)| name == column) {            row.text(column).map(str::to_string)        } else {            data.as_ref().and_then(|data| data.get(*column)).and_then(Value::as_str).map(str::to_string)        };        if let Some(name) = held.map(|name| name.trim().to_string()).filter(|name| !name.is_empty()) {            let mut clipped: String = name.chars().take(60).collect();            if clipped.len() < name.len() {                clipped.push('…');            }            return Ok(clipped);        }    }    fallback()}/// A made table's record's title, clipped; `None` when its definition, its/// table or its title is not there.fn made_record_name(ctx: &Ctx<'_>, table: &str, row_id: &str) -> Result<Option<String>, ToolFailure> {    use crate::mcp::handlers::tables;    let Ok(definition) = tables::definition(ctx, table) else {        return Ok(None);    };    if definition.has_engine() || definition.engine.is_some() {        return Ok(None);    }    let store = tables::made_table(&definition.id);    let db = ctx.db();    if db        .get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[text(&store)])        .map_err(failure)?        .is_none()    {        return Ok(None);    }    let Some(row) = db.get(&format!("SELECT * FROM {store} WHERE id = ?"), &[text(row_id)]).map_err(failure)? else {        return Ok(None);    };    let stored = tables::stored_from_row(&definition, &row);    let name = match stored.data.get(&definition.title) {        Some(Value::String(words)) => words.trim().to_string(),        Some(Value::Number(number)) => number.to_string(),        _ => String::new(),    };    if name.is_empty() {        return Ok(None);    }    let mut clipped: String = name.chars().take(60).collect();    if clipped.len() < name.len() {        clipped.push('…');    }    Ok(Some(clipped))}fn table_name(table: &str) -> String {    TABLE_WORDS        .iter()        .find(|(name, _)| *name == table)        .map(|(_, words)| (*words).to_string())        .unwrap_or_else(|| table.to_string())}fn line(name: &str, kind: &str, target: &str, rule: &str, default: bool) -> Value {    let words = rule_words(rule);    json!({        "kind": kind,        "target": target,        "rule": rule,        "default": default,        "name": name,        "words": words,        "says": format!("{name}: {words}"),        "narrows": narrows(kind, rule),    })}/// `list_keep_rules { device }` — one line per rule, the defaults beside the/// rules somebody set.pub fn list_keep_rules(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let device = required(args, "device")?;    let Some(key) = device_key(ctx, &device)? else {        return Err(ToolFailure::new(format!("{device} is no device of this database")));    };    let db = ctx.db();    let narrowing = keep::NARROWING_GUARDED;    if !keep::is_phone(db, &key).map_err(failure)? {        let keeps = storage_rules::mac_keeps(db, ctx.workspace_id, &key).map_err(failure)?;        let serving = cotton_store::serving::serving_fact(db, ctx.workspace_id)            .map_err(failure)?            .is_some_and(|fact| fact.device_credential_id == key);        let words = MAC_CHOICES            .iter()            .find(|(rule, _)| *rule == keeps.as_str())            .map_or("Set tool by tool in Storage", |(_, words)| *words);        return Ok(json!({            "device": key,            "phone": false,            "says": A_MAC_KEEPS_EVERYTHING,            "narrowing": narrowing,            "rules": [],            "choices": [],            "keeps": keeps.as_str(),            "keepsWords": words,            "serving": serving,            "servingNote": if serving { json!(A_SERVING_MAC_KEEPS_EVERYTHING) } else { Value::Null },            "keepsChoices": MAC_CHOICES.iter().map(|(rule, words)| json!({"rule": rule, "words": words})).collect::<Vec<_>>(),        }));    }    let stored = keep::rules_of(db, &key).map_err(failure)?;    // Cotton's defaults narrow a phone a Mac syncs from; a phone with no Mac    // behind it keeps everything (`Keep::of_device`).    let defaults = keep::has_a_mac(db, &key).map_err(failure)?;    let mut lines: Vec<Value> = Vec::new();    // Every table a rule may narrow has a line: its own rule, or Cotton's    // default for a phone.    for (table, _column) in NARROWABLE {        let name = table_name(table);        match stored.iter().find(|row| row.kind == KIND_TABLE && row.target == *table) {            Some(row) => lines.push(line(&name, KIND_TABLE, table, &row.rule, false)),            None => {                let rule = PHONE_DEFAULTS                    .iter()                    .find(|(name, _, _)| name == table && defaults)                    .map_or(TableRule::All, |(_, rule, _)| *rule);                lines.push(line(&name, KIND_TABLE, table, &rule.as_text(), true));            }        }    }    for row in &stored {        let name = match row.kind.as_str() {            KIND_TABLE if NARROWABLE.iter().any(|(table, _)| *table == row.target) => continue,            KIND_TABLE => table_name(&row.target),            KIND_GROUP => group_name(ctx, &row.target)?,            KIND_RECORD => record_name(ctx, &row.target)?,            _ => continue,        };        lines.push(line(&name, &row.kind, &row.target, &row.rule, false));    }    let choices: Vec<Value> = TABLE_CHOICES        .iter()        .map(|rule| {            let offered = narrowing || !narrows(KIND_TABLE, rule);            let mut words = rule_words(rule);            if let Some(first) = words.get(..1) {                words = format!("{}{}", first.to_uppercase(), &words[1..]);            }            json!({                "rule": rule,                "words": words,                "offered": offered,                "note": if offered { Value::Null } else { json!(AFTER_THE_NEXT_UPDATE) },            })        })        .collect();    Ok(json!({        "device": key,        "phone": true,        "narrowing": narrowing,        "rules": lines,        "choices": choices,    }))}/// `set_keep_rule { device, kind, target, rule }`.pub fn set_keep_rule(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let device = required(args, "device")?;    let kind = required(args, "kind")?;    if kind == KIND_BYTES {        let choice = MacKeeps::parse(&required(args, "rule")?).map_err(failure)?;        return set_mac_keeps(ctx, &device, choice);    }    let mut target = required(args, "target")?;    let rule = required(args, "rule")?;    if kind == KIND_RECORD {        target = record_target(&target);    }    let known = device_key(ctx, &device)?;    let db = ctx.db();    let workspace_id = ctx.workspace_id;    // A device of this file that is not a phone is a Mac, in these words; one    // the file does not know is the store's to refuse below.    if let Some(key) = &known {        if !keep::is_phone(db, key).map_err(failure)? {            return Err(ToolFailure::new(A_MAC_KEEPS_EVERYTHING));        }    }    let key = known.unwrap_or(device);    // The store's own checks, verbatim: a live device, a phone, a rule    // somebody could keep.    keep::check_rule(db, workspace_id, &key, &kind, &target, &rule).map_err(failure)?;    // Keep's guard, read where the rule would otherwise be accepted.    if narrows(&kind, &rule) && !keep::NARROWING_GUARDED {        return Err(ToolFailure::new(narrowing_refusal()));    }    let id = device_keep_id(&key, &kind, &target);    let name = match kind.as_str() {        KIND_GROUP => group_name(ctx, &target)?,        KIND_RECORD => record_name(ctx, &target)?,        _ => table_name(&target),    };    let answer = json!({ "id": id, "rule": line(&name, &kind, &target, &rule, false) });    let held = db        .get("SELECT rule FROM cotton_device_keep WHERE id = ?", &[text(&id)])        .map_err(failure)?        .map(|row| row.text("rule").unwrap_or_default().to_string());    // The same rule again changes nothing and writes nothing.    if held.as_deref() == Some(rule.as_str()) {        return Ok(answer);    }    let at = now_iso(ctx);    let mut patch = Map::new();    if held.is_none() {        patch.insert("id".into(), json!(id));        patch.insert("workspace_id".into(), json!(workspace_id));        patch.insert("device_id".into(), json!(key));        patch.insert("kind".into(), json!(kind));        patch.insert("target".into(), json!(target));        patch.insert("created_at".into(), json!(at));    }    patch.insert("rule".into(), json!(rule));    patch.insert("updated_at".into(), json!(at));    let writer = ctx.writer()?;    writer.upsert(keep::TABLE, &id, patch);    ctx.commit()?;    Ok(answer)}/// `clear_keep_rule { device, kind, target }` — back to Cotton's default.pub fn clear_keep_rule(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let device = required(args, "device")?;    let kind = required(args, "kind")?;    // A Mac's bytes rule cleared is Cotton's default: everything.    if kind == KIND_BYTES {        return set_mac_keeps(ctx, &device, MacKeeps::Everything);    }    let mut target = required(args, "target")?;    if kind == KIND_RECORD {        target = record_target(&target);    }    let key = device_key(ctx, &device)?.unwrap_or(device);    let db = ctx.db();    if !keep::is_phone(db, &key).map_err(failure)? {        return Err(ToolFailure::new(A_MAC_KEEPS_EVERYTHING));    }    // Clearing a table's rule hands it back to Cotton's default, which may    // itself keep less: the same guard as setting it.    if kind == KIND_TABLE && !keep::NARROWING_GUARDED {        let default = PHONE_DEFAULTS.iter().find(|(table, _, _)| *table == target);        if default.is_some_and(|(_, rule, _)| *rule != TableRule::All) {            return Err(ToolFailure::new(narrowing_refusal()));        }    }    let id = device_keep_id(&key, &kind, &target);    let held = db        .get("SELECT id FROM cotton_device_keep WHERE id = ?", &[text(&id)])        .map_err(failure)?        .is_some();    if held {        ctx.writer()?.retract(keep::TABLE, &id, Retract::Relation);        ctx.commit()?;    }    Ok(json!({ "id": id, "cleared": held }))}/// A Mac's one rule: everything, or rows only — its byte tools' Storage/// rules, written through this context's writer so the ops land in the answer.fn set_mac_keeps(ctx: &mut Ctx<'_>, device: &str, choice: MacKeeps) -> ToolResult {    let Some(key) = device_key(ctx, device)? else {        return Err(ToolFailure::new(format!("{device} is no device of this database")));    };    let at = now_iso(ctx);    let workspace_id = ctx.workspace_id;    let patches = storage_rules::mac_keeps_patches(ctx.db(), workspace_id, &key, choice, &at).map_err(failure)?;    let answer = json!({ "device": key, "kind": KIND_BYTES, "rule": choice.as_str() });    // The same choice again changes nothing and writes nothing.    if patches.is_empty() {        return Ok(answer);    }    let writer = ctx.writer()?;    for (id, patch) in patches {        writer.upsert(storage_rules::TABLE, &id, patch);    }    ctx.commit()?;    Ok(answer)}#[cfg(test)]#[path = "keep_rules_tests.rs"]mod tests;