//! `dictation.create` — one utterance into the corpus.//!//! ## Why this is a METHOD and not a tool//!//! Grep the catalogue for `dictat` and nothing comes back: none of the 186//! tools writes `cotton_dictations`. That is not an oversight to fill with a//! `create_dictation` verb — a dictation is the RAW MATERIAL of the keyboard//! flywheel, the thing the person said before anybody decided what it//! meant, and `cotton_dictations` is a supporting table rather than a primitive//! (`cotton_core::primitives`'s `SUPPORTING_TABLES` classification). An//! assistant that could append to the corpus could put sentences in the mining//! set that the person never uttered, and every downstream reader — the prompt//! blocks, the voice vocabulary, the settings screen's stats — would count them.//!//! So the corpus has exactly one author, and it is the app. Same class as//! `capture.create` and the `_media` ledger: a write the tool surface//! deliberately owes no verb. The body runs 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 already uses.//!//! ## One caller//!//! `/take` writes `source: "take"` (deliberate speech). The keyboard is voice//! only (Spec 10.6): it keeps nothing typed, so `typed` — the column's value//! for the keyboard's old typed bursts — is refused here like `wispr`; rows an//! older keyboard wrote stay readable.//!//! `wispr` is the column's other source the column admits and it is refused here by//! name: it is an IMPORT provenance — history from another tool that was never//! spoken to Cotton — and it arrives with an `external_id` for idempotency that//! this method has no argument for. An import is not something a phone screen//! does.use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, now_iso};usecrate::handle::CottonHandle;usecrate::methods::MethodError;/// The one provenance a PHONE authors. `wispr` is the importer's and `typed`/// the retired keyboard capture's; both are refused by name below.pubconst PHONE_DICTATION_SOURCES: [&str; 1] = ["take"];/// What the take screen or the outbox drain sent.#[derive(Debug, Clone, PartialEq, Eq)]pubstructDictationArgs {pub text: String,pub source: String,pub duration_ms: Option<i64>,/// Counted by the WRITER, because the writer is the only one that knows:/// the take screen counts the text it just polished. Absent means "count it/// here".pub words: Option<i64>,/// When it was SAID. Absent stamps the row with now — a live take; a caller/// writing later passes the instant it was said, so it sorts where it/// happened rather than where it was written.pub spoken_at: Option<String>,}const EMPTY: &str = "a dictation cannot be empty";pubfn validate(request: &Value) -> Result<DictationArgs, MethodError> {let text = request .get("text") .and_then(Value::as_str) .map(|text| text.trim_matches(cotton_store::protocol::js::is_js_whitespace)) .filter(|text| !text.is_empty()) .ok_or_else(|| MethodError::new("bad_request", EMPTY))? .to_string();let source = request .get("source") .and_then(Value::as_str) .unwrap_or_default() .to_string();if !PHONE_DICTATION_SOURCES.contains(&source.as_str()) {returnErr(MethodError::new("bad_request", format!("`source` is {} — a phone authors deliberate speech only: the keyboard keeps \ nothing typed, and `wispr` is the importer's provenance, which carries an \ idempotency key this method has no argument for", PHONE_DICTATION_SOURCES.join(" or ") ), )); }// NOT CLAMPED TO ZERO, refused. A negative word count is not a smaller one,// it is a broken caller — and the corpus's whole value is that the figure// beside each row can be trusted.let words = match request.get("words") {None | Some(Value::Null) => None,Some(value) => {let words = value .as_f64() .filter(|words| words.is_finite() && *words >= 0.0);match words {Some(words) => Some(cotton_core::js_number::math_round(words) as i64),None => {returnErr(MethodError::new("bad_request","`words` is a non-negative count of the words in the text", )) } } } };let duration_ms = match request.get("durationMs") {None | Some(Value::Null) => None,Some(value) => {let duration = value.as_f64().filter(|n| n.is_finite()).ok_or_else(|| {MethodError::new("bad_request", "`durationMs` is a finite number") })?;let rounded = cotton_core::js_number::math_round(duration);if rounded < i64::MIN as f64 || rounded >= -(i64::MIN as f64) {returnErr(MethodError::new("bad_request","`durationMs` exceeds the integer range", )); }Some(rounded as i64) } };let spoken_at = request .get("spokenAt") .and_then(Value::as_str) .map(|text| text.trim_matches(cotton_store::protocol::js::is_js_whitespace)) .filter(|at| !at.is_empty()) .map(str::to_string);Ok(DictationArgs { text, source, words, spoken_at, duration_ms, })}/// How many words a text holds, when the caller did not count.////// Whitespace-separated runs, the same arithmetic the keyboard's own/// `countWords` uses — one rule, so a take counted by the app and a burst/// counted here cannot disagree about the same sentence.pubuse cotton_core::js_text::count_words;/// `dictation.create` — one row in the corpus.pubfn create(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let args = validate(request)?; handle .client() .write_rows("dictation.create", &mut |ctx| write_dictation(ctx, &args)) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason))}/// The row itself, so a test can drive it over a `Ctx` without a handle.pubfn write_dictation(ctx: &mutCtx<'_>, args: &DictationArgs) -> Result<Value, String> {let id = ctx.new_uuid();let now = now_iso(ctx);letmut patch = Map::new(); patch.insert("text".to_string(), Value::from(args.text.clone()));// ALWAYS NULL. The column held the pre-polish recognition, and there is no// polish: what the recogniser said IS the text, so a second copy of it would// be a column that says nothing. The column stays for the import provenance// that owns it. patch.insert("raw_text".to_string(), Value::Null); patch.insert("source".to_string(), Value::from(args.source.clone()));// Always NULL for a keyboard row: iOS gives a keyboard extension no public// API for its host app, so a value here would be a guess. patch.insert("host_app".to_string(), Value::Null); patch.insert("words".to_string(),Value::from(args.words.unwrap_or_else(|| count_words(&args.text))), );// The recorder supplies duration; a caller without one omits it. patch.insert("duration_ms".to_string(), args.duration_ms.map_or(Value::Null, Value::from), ); patch.insert("spoken_at".to_string(),Value::from(args.spoken_at.clone().unwrap_or_else(|| now.clone())), );// The import idempotency key, which no phone write has: it exists so a// re-run of the Wispr import skips what it already brought in. patch.insert("external_id".to_string(), Value::Null); insert_row(ctx, "cotton_dictations", &id, patch).map_err(|failure| failure.to_string())?;Ok(json!({ "id": id }))}