Cotton code
170 lines · 7.0 KB · RustRaw
//! `settings.*` — the five writes the tool surface owes no verb.//!//! ## Why these are methods and not tools//!//! 4p's four writes were each a WRITTEN REFUSAL on a primitive: `create_thought`//! does not exist because a thought is something the person SAID, and so on.//! **These five are a different class, and the distinction is the reason they//! are methods rather than a fifth and sixth Owner tool.**//!//! Every table below is a `SUPPORTING_TABLE` — classified rather than declared//! (`cotton-core`'s `primitives.rs`), which is to say the verb grid owes it no//! entry at all://!//! * `cotton_voice_vocabulary` — *"infrastructure — dictation bias terms"*;//! * `cotton_msg_owner_settings` — *"chat — the owner's handle and message-me//!   settings"*.//!//! So there is no refusal to widen and no primitive to add a verb to: a "no"//! here would be a missing entry rather than a written reason, and this repo's//! rule is that a missing entry is never a no. The honest shape is the one//! `capture.create` already uses — the app's own write, through//! [`crate::authoring::author_through_outbox`], which is the SAME `Ctx::phone`,//! the same writer, the same outbox and the same `data` event every tool call//! from this device takes. Nothing about these rows is special; only who may//! write them.//!//! Inventing tools for them would have the opposite effect of the one wanted://! an assistant could then rename the person's dictionary, revoke its own//! access, or move where they live.//!//! Home's arrangement is not here: the app never edits itself (owner, 16 Oct//! 2026), so Home's order is set over MCP only — `arrange_tools` writes the//! row through `cotton_tools::home_arrangement`, the one place that write lives.use serde_json::Value;use cotton_tools::mcp::dispatch::Ctx;use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::owner;pub const METHODS: [&str; 4] = [    "settings.forgetVoiceTerm",    "settings.openFlow",    "settings.voiceTerm",    "settings.recordVoiceUse",];/// How many words a term may be, by where it came from.////// A term the recogniser LEARNED is capped tighter than one a person typed:/// two against three. Both caps are the phone's own — anything longer is/// ignored by the recogniser anyway, and the form says so.const MAX_WORDS_AUTO: usize = 2;const MAX_WORDS_MANUAL: usize = 3;pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "settings.openFlow" => super::settings_flows::open_flow(handle, request),        "settings.recordVoiceUse" => {            let transcript = owner::text(request, "text")?;            let terms: Vec<String> = serde_json::from_value(request["hintedTerms"].clone())                .map_err(|_| MethodError::new("invalid_args", "hintedTerms must be an array of strings"))?;            if terms.len() > 100 || terms.iter().any(|term| term.len() > 1024) {                return Err(MethodError::new("invalid_args", "At most 100 bounded hints are accepted"));            }            let _personal = handle.client().name_database(None)                .map_err(|reason| MethodError::new("write_refused", reason))?;            write(handle, method, &mut |ctx| cotton_tools::dictation::record_use(ctx, &transcript, &terms))        }        "settings.voiceTerm" => {            let term = voice_term(request)?;            write(handle, method, &mut |ctx| upsert_term(ctx, &term))        }        "settings.forgetVoiceTerm" => {            let id = owner::text(request, "id")?;            write(handle, method, &mut |ctx| forget_term(ctx, &id))        }        other => Err(MethodError::new(            "unknown_method",            format!("`{other}` is not a settings write"),        )),    }}fn write(    handle: &CottonHandle,    label: &str,    body: &mut dyn FnMut(&mut Ctx<'_>) -> Result<Value, String>,) -> Result<Value, MethodError> {    handle        .client()        .write_rows(label, body)        .map(crate::authoring::own_answer)        .map_err(|reason| MethodError::new("write_refused", reason))}// ── the voice dictionary ──────────────────────────────────────────────────/// A term as it will be stored, and where it came from.#[derive(Debug, Clone)]pub struct VoiceTerm {    pub term: String,    /// `manual` for a word the person typed, `auto` for one dictation learned.    pub source: String,}/// `normalizeVocabularyTerm` — trim, then collapse every run of whitespace to/// one space. **Casing is preserved**: the whole point of the dictionary is that/// a name is spelled the way the person writes it.pub fn normalize(raw: &str) -> String {    cotton_tools::dictation::normalize(raw)}fn voice_term(request: &Value) -> Result<VoiceTerm, MethodError> {    let source = owner::one_of(        &owner::optional_text(request, "source").unwrap_or_else(|| "manual".to_string()),        &["manual", "auto"],        "source",    )?;    let term = normalize(        request            .get("term")            .and_then(Value::as_str)            .unwrap_or_default(),    );    if term.is_empty() {        return Err(MethodError::new("invalid_term", "A term cannot be empty"));    }    let cap = if source == "auto" {        MAX_WORDS_AUTO    } else {        MAX_WORDS_MANUAL    };    if term.split(' ').count() > cap {        return Err(MethodError::new(            "invalid_term",            format!("Dictation listens for a name or a short phrase of at most {cap} words — add the longer one in parts."),        ));    }    Ok(VoiceTerm { term, source })}/// Add a word, or promote one dictation learned to one the person owns.////// The three rules, all of them about not overwriting a person's own spelling:////// * an incoming `auto` never touches a row that exists — accrual must not///   re-case a word somebody typed;/// * a row that is already `manual` is never touched by anything;/// * an `auto` row meeting a `manual` write is PROMOTED, and takes the typed///   spelling with it. Promotion is one-way; `manual` never becomes `auto`.////// The lookup is case-insensitive and matches the file's own unique index/// exactly, so "Nilgiri" and "nilgiri" are one word rather than two rows that/// cannot both exist.pub fn upsert_term(ctx: &mut Ctx<'_>, input: &VoiceTerm) -> Result<Value, String> {    cotton_tools::dictation::upsert_term(ctx, &cotton_tools::dictation::VoiceTerm { term: input.term.clone(), source: input.source.clone() })}/// Take a word out.////// Scoped by workspace as well as by id — deliberately, so an id from somewhere/// else is a visible no-op rather than a silent delete. A word that is already/// gone is a SUCCESS: the screen's rename is add-then-delete, and a delete that/// refused because the row went first would leave a rename looking failed.pub fn forget_term(ctx: &mut Ctx<'_>, id: &str) -> Result<Value, String> {    cotton_tools::dictation::forget_term(ctx, id)}