Cotton code
80 lines · 4.7 KB · RustRaw
//! The synced vocabulary rows shared by MCP and the device dictation engine.use serde_json::{json, Map, Value};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{insert_row, now_iso, update_row};use crate::mcp::writer::Retract;const VOCABULARY: &str = "cotton_voice_vocabulary";#[derive(Debug, Clone)]pub struct VoiceTerm { pub term: String, pub source: String }pub fn normalize(raw: &str) -> String { raw.split_whitespace().collect::<Vec<_>>().join(" ") }pub fn upsert_term(ctx: &mut Ctx<'_>, input: &VoiceTerm) -> Result<Value, String> {    let existing = ctx.db().get(        "SELECT id, term, source FROM cotton_voice_vocabulary WHERE workspace_id = ? AND lower(term) = lower(?)",        &[rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(input.term.clone())],    ).map_err(|error| error.to_string())?;    if let Some(row) = existing {        let id = row.text("id").unwrap_or_default().to_string();        let source = row.text("source").unwrap_or_default().to_string();        if input.source == "auto" || source == "manual" { return Ok(json!({"id":id,"term":row.text("term"),"source":source,"changed":false,"added":false})); }        let mut patch = Map::new(); patch.insert("source".into(), Value::from("manual")); patch.insert("term".into(), Value::from(input.term.clone()));        update_row(ctx, VOCABULARY, &id, patch).map_err(|failure| failure.to_string())?;        return Ok(json!({"id":id,"term":input.term,"source":"manual","changed":true,"added":false}));    }    let id = ctx.new_uuid(); let mut patch = Map::new();    patch.insert("term".into(), Value::from(input.term.clone())); patch.insert("source".into(), Value::from(input.source.clone()));    patch.insert("use_count".into(), Value::from(0)); patch.insert("last_used_at".into(), Value::Null); patch.insert("created_at".into(), Value::from(now_iso(ctx)));    insert_row(ctx, VOCABULARY, &id, patch).map_err(|failure| failure.to_string())?;    Ok(json!({"id":id,"term":input.term,"source":input.source,"changed":true,"added":true}))}pub fn forget_term(ctx: &mut Ctx<'_>, id: &str) -> Result<Value, String> {    let found = ctx.db().get("SELECT id FROM cotton_voice_vocabulary WHERE id = ? AND workspace_id = ?", &[rusqlite::types::Value::Text(id.into()),rusqlite::types::Value::Text(ctx.workspace_id.to_string())]).map_err(|error| error.to_string())?;    if found.is_none() { return Ok(json!({"id":id,"removed":false})); }    ctx.writer().map_err(|failure| failure.to_string())?.retract(VOCABULARY,id,Retract::Verb("settings.forgetVoiceTerm"));    Ok(json!({"id":id,"removed":true}))}/// One stop, one transaction: each hinted term heard in the final text gains/// one use, irrespective of repetitions or duplicate hints.pub fn record_use(ctx: &mut Ctx<'_>, transcript: &str, hinted_terms: &[String]) -> Result<Value, String> {    let transcript = normalize(transcript).to_lowercase();    let mut seen = std::collections::BTreeSet::new();    let mut updated = 0;    let at = now_iso(ctx);    let existing = ctx.db().all("SELECT id,term,use_count FROM cotton_voice_vocabulary WHERE workspace_id = ?",        &[rusqlite::types::Value::Text(ctx.workspace_id.into())]).map_err(|e| e.to_string())?;    for hint in hinted_terms.iter().take(100) {        let term = normalize(hint);        let folded = term.to_lowercase();        if folded.is_empty() || !seen.insert(folded.clone()) { continue; }        let boundary = |c: char| !c.is_alphanumeric() && c != '_';        let heard = transcript.match_indices(&folded).any(|(start, found)| {            transcript[..start].chars().next_back().is_none_or(boundary)                && transcript[start + found.len()..].chars().next().is_none_or(boundary)        });        if !heard { continue; }        if let Some(row) = existing.iter().find(|r| r.text("term").is_some_and(|term| normalize(term).to_lowercase() == folded)) {            let id = row.text("id").ok_or("voice term has no id")?;            let mut patch = Map::new();            patch.insert("use_count".into(), json!(row.int("use_count").unwrap_or(0).saturating_add(1)));            patch.insert("last_used_at".into(), json!(at));            update_row(ctx, VOCABULARY, id, patch).map_err(|e| e.to_string())?;        } else {            // Create a generated row with its first use already set, so a            // stop needs only one change for each heard term.            let id = ctx.new_uuid();            let patch = serde_json::from_value(json!({"term":term,"source":"auto","use_count":1,"last_used_at":at,"created_at":at}))                .map_err(|e| e.to_string())?;            insert_row(ctx, VOCABULARY, &id, patch).map_err(|e| e.to_string())?;        }        updated += 1;    }    Ok(json!({"updated":updated}))}