//! Device-local dictation context. A kept projection, never another synced copy//! of a person's names: replacing a pass removes names whose final source went.use std::collections::{BTreeMap, BTreeSet};use std::sync::Arc;use std::time::Duration;use cotton_core::definitions::{ builtin_store_table, ColumnType, TableDefinition,};use cotton_store::{driver::Driver, schema::table_specs::TABLE_SPECS};use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};usecrate::shell::client::ClientController;const EVERY: Duration = Duration::from_secs(30);const MAX_BIAS_TERMS: usize = 100;/// What this pass is called in a slow hold's line: it reads every [`EVERY`],/// and a hold that does not name itself is diagnosed from a stack sample or/// not at all.const DOING: &str = "the dictation vocabulary (voice words)";#[derive(Clone)]structWord { term: String, source: &'static str, origins: Vec<Value>, uses: i64, last_used: String,}fn add( words: &mut BTreeMap<String, Word>, raw: &str, source: &'static str, origin: Value, uses: i64, last_used: &str,) {let term = super::settings_writes::normalize(raw);// A person's explicit addition always survives; the bounds only decide// which record values are names rather than prose, addresses or URLs.if term.is_empty() || (source == "records" && (term.chars().count() > 100 || term.split_whitespace().count() > 8 || !term.chars().any(char::is_alphabetic) || term.contains('@') || term.contains("://"))) {return; }let word = words.entry(term.to_lowercase()).or_insert_with(|| Word { term: term.clone(), source, origins: Vec::new(), uses, last_used: last_used.into(), });if source == "manual" || (word.source == "dictation" && source == "records") { word.term = term; word.source = source; } word.uses = word.uses.max(uses);if last_used > word.last_used.as_str() { word.last_used = last_used.into(); }if !word.origins.contains(&origin) { word.origins.push(origin); }}fn text(s: &str) -> SqlValue {SqlValue::Text(s.to_string())}fn columns(definition: &TableDefinition) -> Vec<&str> {let names: Vec<&str> = match &definition.voice_words {Some(keys) => keys.iter().map(String::as_str).collect(),Noneif definition.engine.is_none() => vec![definition.title.as_str()],None => Vec::new(), }; names .into_iter() .filter(|key| { definition.column(key).is_some_and(|c| { matches!(c.column_type, ColumnType::Text | ColumnType::Place) && c.secret != Some(true) && c.computed.is_none() }) }) .collect()}fn definitions(db: &Driver, workspace: &str) -> Result<Vec<TableDefinition>, String> {// Use the same resolved overlay as record reads: seeded and authored rows// are reconciled once, before an engine interprets their behavior keys. cotton_tools::definitions::table_definitions_from_driver(db, workspace) .map(|catalogue| catalogue.definitions) .map_err(|error| error.to_string())}fn record_words( db: &Driver, workspace: &str, words: &mut BTreeMap<String, Word>,) -> Result<(), String> {// The file's tables, read once: asking per made table scans the whole// schema each time, and a kitted file holds hundreds of tables.letmut tables: Option<BTreeSet<String>> = None;for definition in definitions(db, workspace)? {// A view's rows are its source's, heard once, as the source's.if definition.source.is_some() {continue; }// A custom tool's name and plural are heard like a record's name// (Spec 10.6). Shipped names are ordinary recogniser vocabulary,// including shipped packages that keep records without an engine.if definition.engine.is_none() && cotton_core::definitions::builtin_table_definition(&definition.id).is_none() {let origin = json!({"databaseId":workspace, "table":"tool", "recordId":definition.id, "column":"name", "label":"Tools"});for name in [&definition.name, &definition.plural] { add(words, name, "records", origin.clone(), 0, ""); } }let columns = columns(&definition);if columns.is_empty() {continue; }let records: Vec<(String, Value)> = if definition.engine.is_some() {letSome(table) = builtin_store_table(&definition.id) else {continue; };let spec = TABLE_SPECS .iter() .find(|s| s.name == table) .ok_or_else(|| format!("No storage for {}", definition.id))?;let has = |key: &str| spec.columns.iter().any(|(name, _)| *name == key);// All identifiers here are the compiled storage map's, never input SQL.let selected: Vec<_> = columns.iter().filter(|key| has(key)).copied().collect();if selected.is_empty() {continue; }letmut sql = format!("SELECT id, {} FROM {table} WHERE workspace_id = ?", selected .iter() .map(|c| format!("\"{c}\"")) .collect::<Vec<_>>() .join(", ") );for key in ["archived_at", "trashed_at", "deleted_at"] {if has(key) { sql.push_str(&format!(" AND {key} IS NULL")); } }// A row with none of its words is no word, so it is never read: a// table where few rows carry one — the mail threads that name a// merchant are 7.6k of the owner's 81k — is read through its// partial index of those rows alone, never row by wide row (a// 10.5 s hold of the serving Mac's file every 30 s, 12 Oct 2026). sql.push_str(&format!(" AND ({})", selected .iter() .map(|c| format!("\"{c}\" IS NOT NULL")) .collect::<Vec<_>>() .join(" OR ") ));if has("status") { sql.push_str(" AND status != 'archived'"); } sql.push_str(" ORDER BY id"); db.all(&sql, &[text(workspace)]) .map_err(|e| e.to_string())? .iter() .map(|row| {letmut data = serde_json::Map::new();for key in &selected {ifletSome(raw) = row.text(key) {// Multiple names (a list of aliases) are stored as JSON.let value = serde_json::from_str::<Vec<String>>(raw) .map_or_else(|_| json!(raw), |v| json!(v)); data.insert((*key).into(), value); } } ( row.text("id").unwrap_or_default().into(),Value::Object(data), ) }) .collect() } else {// A made table's records are rows of its own table, one column a// key (`tables::made_table`); one this file does not hold yet has// none.use cotton_tools::mcp::handlers::tables::{made_table, stored_from_row};let store = made_table(&definition.id);if tables.is_none() { tables = Some( db.all("SELECT name FROM sqlite_master WHERE type = 'table'", &[]) .map_err(|e| e.to_string())? .iter() .filter_map(|row| row.text("name").map(str::to_string)) .collect(), ); }if !tables.as_ref().is_some_and(|held| held.contains(&store)) {continue; } db.all(&format!("SELECT * FROM {store} WHERE workspace_id = ? AND deleted_at IS NULL ORDER BY id"), &[text(workspace)]) .map_err(|e| e.to_string())? .iter() .map(|row| {let stored = stored_from_row(&definition, row); (stored.id, Value::Object(stored.data)) }) .collect() };for (id, data) in records {if definition .archived .as_ref() .and_then(|key| data.get(key)) .is_some_and(|v| !v.is_null() && v != false && v != "") {continue; }for column in &columns {let origin = json!({"databaseId":workspace, "table":definition.id, "recordId":id, "column":column, "label":definition.plural});match &data[*column] {Value::String(raw) => add(words, raw, "records", origin, 0, ""),Value::Array(names) => {for name in names.iter().filter_map(Value::as_str) { add(words, name, "records", origin.clone(), 0, ""); } } _ => {} } } } }Ok(())}/// Rebuild from the held files on THIS device. The read paths call the same/// pass as the timer, so a freshly renamed contact is heard at the next mic.pub(crate) fn refresh(client: &ClientController) -> Result<Value, String> {// Serialise scans and publication: an older pass cannot replace a newer one.letmut cached = client.voice_context.lock().map_err(|e| e.to_string())?;letmut words = BTreeMap::new();let held = client.databases()?;letmut personal_id = None;for database in held.iter() {// A not-yet-downloaded database contributes no local names. A database// created offline DOES: pending means the server has not admitted it.if client.arriving(&database.id).is_some() {continue; }if database.personal { personal_id = Some(database.id.clone()); }let read = || { client.with_file_in(&database.id, |file| { cotton_store::held::doing(DOING);letmut words = BTreeMap::new(); record_words(file.driver, file.workspace_id, &mut words)?;if database.personal {for row in file.driver.all("SELECT id, term, source, use_count, last_used_at FROM cotton_voice_vocabulary WHERE workspace_id = ? ORDER BY term COLLATE NOCASE, id", &[text(file.workspace_id)]).map_err(|e| e.to_string())? {let source = if row.text("source") == Some("manual") { "manual" } else { "dictation" }; add(&mut words, row.text("term").unwrap_or_default(), source, json!({"databaseId":file.workspace_id,"table":"voice_word","recordId":row.text("id"),"column":"term","label":if source == "manual" {"Your additions"} else {"Dictation"}}), row.int("use_count").unwrap_or(0), row.text("last_used_at").unwrap_or_default()); } }Ok(json!(words.values().map(|w| json!({"term":w.term,"source":w.source,"origins":w.origins,"uses":w.uses,"lastUsed":w.last_used})).collect::<Vec<_>>())) }) };// The same file/WAL stamp cache as Today: idle replicas are not opened// on each timer tick.let found = client.indexed_read(&database.id, "voice-context", read)?;if !database.personal {// A project's database name is a name in its own right, including// a database made offline before it has its first project record. add( &mut words, &database.name,"records", json!({"databaseId":database.id, "table":"database", "recordId":database.id,"column":"name", "label":"Databases", }),0,"", ); }for word in found.as_array().into_iter().flatten() {let source = match word["source"].as_str() {Some("manual") => "manual",Some("dictation") => "dictation", _ => "records", };for origin in word["origins"].as_array().into_iter().flatten() { add( &mut words, word["term"].as_str().unwrap_or_default(), source, origin.clone(), word["uses"].as_i64().unwrap_or(0), word["lastUsed"].as_str().unwrap_or_default(), ); } } } client.close_idle_databases();letmut ranked: Vec<_> = words.values().collect(); ranked.sort_by(|a, b| { (a.source != "manual") .cmp(&(b.source != "manual")) .then_with(|| b.uses.cmp(&a.uses)) .then_with(|| b.last_used.cmp(&a.last_used)) .then_with(|| a.term.to_lowercase().cmp(&b.term.to_lowercase())) });let bias: Vec<_> = ranked .iter() .take(MAX_BIAS_TERMS) .map(|word| &word.term) .collect();let manual = words .values() .filter(|word| word.source == "manual") .count();letmut sources: BTreeMap<(String, String, String), BTreeSet<String>> = BTreeMap::new();for (key, word) in &words {for origin in &word.origins {let get = |k| origin[k].as_str().unwrap_or_default().to_string(); sources .entry((get("databaseId"), get("table"), get("label"))) .or_default() .insert(key.clone()); } }let answer = json!({"count":words.len(), "manualCount":manual, "automaticCount":words.len()-manual, "biasCount":bias.len(),"sources":sources.into_iter().map(|((database, table, label), terms)| json!({"databaseId":database,"table":table,"label":label,"count":terms.len()})).collect::<Vec<_>>(),"words":words.values().map(|word| json!({"term":word.term,"source":word.source,"origins":word.origins})).collect::<Vec<_>>(),"vocabularyTerms":words.values().map(|word| &word.term).collect::<Vec<_>>(), "biasTerms":bias,// Every word in rank order with the databases it comes from — what// [`context`] re-ranks for the database open now; never answered. RANKED: ranked.iter().map(|word| json!([word.term, word.source == "manual", word.origins.iter().filter_map(|origin| origin["databaseId"].as_str()).collect::<BTreeSet<_>>()])).collect::<Vec<_>>(), });let changed = cached.as_ref() != Some(&answer); *cached = Some(answer.clone()); drop(cached);if changed {ifletSome(workspace) = personal_id { client.emit_data( &workspace, vec![crate::methods::shell_kept::VOICE_VOCABULARY.into()],"voice-context", ); } }Ok(answer)}/// The open database's share of the bias room left below the screen and the/// person's own additions; the rest is the person's own names'.const OPEN_SHARE: (usize, usize) = (2, 3);/// How the room left is split between the open database's names (`open`/// waiting) and the person's own (`own` waiting): `OPEN_SHARE` and the rest,/// each side's unused room going to the other.fn shared_room(room: usize, open: usize, own: usize) -> (usize, usize) {let open_share = room * OPEN_SHARE.0 / OPEN_SHARE.1;let own_share = room - open_share;let open_taken = open.min(open_share + own_share.saturating_sub(own));let own_taken = own.min(room - open_taken); (open_taken, own_taken)}/// The kept pass's private key: every word, ranked, with its databases.const RANKED: &str = "ranked";/// A microphone passes its screen; the core owns every ranking band.pub(crate) fn context(client: &ClientController) -> Result<Value, String> { context_for(client, &serde_json::Map::new())}pub(crate) fn context_for(client: &ClientController, args: &serde_json::Map<String, Value>) -> Result<Value, String> {let screen = args.get("screen").filter(|v| v.is_object());let _database = match screen.and_then(|s| s["databaseId"].as_str()) {Some(id) => Some(client.name_database(Some(id))?),None => None, };letmut answer = refresh(client)?;let ranked = answer.as_object_mut().unwrap().remove(RANKED).unwrap_or_default();let personal = client.databases()?.into_iter().find(|database| database.personal).map(|database| database.id);let open: BTreeSet<String> = matchcrate::shell::client::named_database() {Some(named) => BTreeSet::from([named]),None => client.shown_databases().into_iter().collect(), };letmut screen_words = BTreeMap::new();letmut bands = BTreeMap::<String, u8>::new();ifletSome(screen) = screen { screen_names(client, screen, &mut screen_words, &mut bands)?; }// The kept pass already orders use count and recency. Stable sorting keeps// those tie breakers inside each screen/manual/database/global band.letmut ordered: Vec<(String, u8, bool)> = ranked.as_array().into_iter().flatten().map(|word| {let term = word[0].as_str().unwrap_or_default().to_string();let ids = || word[2].as_array().into_iter().flatten().filter_map(Value::as_str);let here = ids().any(|id| open.contains(id));let own = personal.as_deref().is_some_and(|personal| ids().any(|id| id == personal));let band = bands.get(&term.to_lowercase()).copied().unwrap_or_else(|| {if word[1] == true { 2 } elseif here { 3 } else { 4 } }); (term, band, own) }).collect();letmut seen: BTreeSet<String> = ordered.iter().map(|(term, _, _)| term.to_lowercase()).collect();for (key, word) in &screen_words {if seen.insert(key.clone()) { ordered.push((word.term.clone(), bands[key], false)); answer["words"].as_array_mut().unwrap().push(json!({"term":word.term,"source":word.source,"origins":word.origins})); answer["vocabularyTerms"].as_array_mut().unwrap().push(json!(word.term)); } } ordered.sort_by_key(|(_, band, _)| *band);// Reserve space for ALL manual additions even when the screen fills the cap.let manual: BTreeSet<_> = ranked.as_array().into_iter().flatten().filter(|w| w[1] == true) .filter_map(|w| w[0].as_str()).map(str::to_lowercase).collect();letmut remaining_manual = manual.len().min(MAX_BIAS_TERMS);letmut bias = Vec::new();// Below the screen and the person's own additions, the open database's// names and the person's own names from the personal database SHARE the// room left (`OPEN_SHARE` of it the open one's), each side giving the room// it does not use to the other: a shared database whose kit fills the cap// never silently drops the owner's own people (architect, 22 Oct 2026).let (mut open_side, mut own_side, mut rest) = (Vec::new(), Vec::new(), Vec::new());for (term, band, own) in ordered {if band <= 2 {if manual.contains(&term.to_lowercase()) { remaining_manual = remaining_manual.saturating_sub(1); } elseif bias.len() + remaining_manual >= MAX_BIAS_TERMS {continue; }if bias.len() < MAX_BIAS_TERMS { bias.push(term); } } elseif band == 3 { open_side.push(term); } elseif own { own_side.push(term); } else { rest.push(term); } }let room = MAX_BIAS_TERMS.saturating_sub(bias.len());let (open_room, own_room) = shared_room(room, open_side.len(), own_side.len()); bias.extend(open_side.into_iter().take(open_room)); bias.extend(own_side.into_iter().take(own_room));let left = MAX_BIAS_TERMS.saturating_sub(bias.len()); bias.extend(rest.into_iter().take(left));letmut sources = BTreeMap::<(String, String, String), BTreeSet<String>>::new();for word in answer["words"].as_array().into_iter().flatten() {for origin in word["origins"].as_array().into_iter().flatten() {let get = |key: &str| origin[key].as_str().unwrap_or_default().to_string(); sources.entry((get("databaseId"),get("table"),get("label"))).or_default() .insert(word["term"].as_str().unwrap_or_default().to_lowercase()); } } answer["sources"] = json!(sources.into_iter().map(|((database,table,label),terms)| json!({"databaseId":database,"table":table,"label":label,"count":terms.len()})).collect::<Vec<_>>());let tags = ["manual","people","places","projects","screen"];letmut groups = BTreeMap::<&str, Vec<&String>>::new();for term in &bias {let origins = answer["words"].as_array().into_iter().flatten() .find(|word| word["term"].as_str().is_some_and(|word| word.to_lowercase() == term.to_lowercase())) .map(|word| &word["origins"]);let tag = tag_of(manual.contains(&term.to_lowercase()), origins.unwrap_or(&Value::Null)); groups.entry(tag).or_default().push(term); } answer["biasGroups"] = json!(tags.into_iter().filter_map(|tag| groups.get(tag).map(|terms| json!({"tag":tag,"terms":terms}))).collect::<Vec<_>>()); answer["biasCount"] = json!(bias.len()); answer["biasTerms"] = json!(bias); answer["language"] = json!(language(client)?); answer["count"] = json!(answer["words"].as_array().unwrap().len()); answer["automaticCount"] = json!(answer["count"].as_u64().unwrap() - answer["manualCount"].as_u64().unwrap());Ok(answer)}/// Why a word is heard, as the recogniser's tagged groups name it: the/// person's own addition, then a person's, a place's or a project's name, and/// every other name (a tool, a merchant, a character) last. One answer for the/// screen's ranked hundred and the device's language model alike.fn tag_of(manual: bool, origins: &Value) -> &'static str {let has = |table: &str| origins.as_array().into_iter().flatten().any(|origin| origin["table"] == table);if manual { "manual" }elseif has("person") { "people" }elseif has("location") { "places" }elseif has("project") || has("database") { "projects" }else { "screen" }}/// `read.voiceCorpus` — what THIS device compiles its own dictation language/// model from (`CottonUI/Capture/VoiceModel.swift`): EVERY name the kept pass/// holds, tagged as the hints are — words and names only, never a note's/// body, a thought, a message or any whole text, so the compiled corpus stays/// kilobytes and the system's compiler never chews through a life's writing/// (item 29, 19 Oct 2026: whole texts made a 237 MB corpus per build)./// Answered to the app alone: the corpus and the model compiled from it never/// leave the device.pub(crate) fn corpus(client: &ClientController, _args: &serde_json::Map<String, Value>) -> Result<Value, String> {let answer = refresh(client)?;let tags = ["manual", "people", "places", "projects", "screen"];letmut names = BTreeMap::<&str, Vec<&str>>::new();for word in answer["words"].as_array().into_iter().flatten() {letSome(term) = word["term"].as_str() else { continue }; names.entry(tag_of(word["source"] == "manual", &word["origins"])).or_default().push(term); }Ok(json!({"names": tags.into_iter().filter_map(|tag| names.get(tag).map(|terms| json!({"tag":tag,"terms":terms}))).collect::<Vec<_>>(), }))}/// Me is the personal database's owner row, irrespective of the open screen./// With no linked owner yet, the definition supplies the English default.pub(crate) fn language(client: &ClientController) -> Result<String, String> {let _personal = client.name_database(None)?; client.with_file(|file| {let definition = cotton_tools::definitions::table_definitions_from_driver(file.driver, file.workspace_id) .map_err(|e| e.to_string())?.definitions.into_iter().find(|d| d.id == "person") .ok_or("No People definition")?;let default = definition.column("language").and_then(|c| c.default.as_ref()) .and_then(Value::as_str).ok_or("People has no language default")?;let row = file.driver.get("SELECT p.language FROM cotton_people p JOIN cotton_workspaces w ON w.owner_person_id = p.id AND w.id = p.workspace_id WHERE w.id = ? AND p.archived_at IS NULL AND p.trashed_at IS NULL", &[text(file.workspace_id)]).map_err(|e| e.to_string())?;Ok(row.as_ref().and_then(|r| r.text("language")).unwrap_or(default).to_string()) })}fn screen_names(client: &ClientController, screen: &Value, words: &mut BTreeMap<String, Word>, bands: &mut BTreeMap<String, u8>) -> Result<(), String> {letSome(table) = screen["table"].as_str() else { returnOk(()); };let definitions = client.with_file(|file| cotton_tools::definitions::table_definitions_from_driver(file.driver, file.workspace_id) .map(|d| d.definitions).map_err(|e| e.to_string()))?;letSome(definition) = definitions.iter().find(|d| d.id == table) else {returnErr(format!("Unknown voice screen table: {table}")); };let database = crate::shell::client::named_database().unwrap_or_default();letmut include = |definition: &TableDefinition, record: &Value, band: u8| {if !record["deleted_at"].is_null() || !record["data"]["trashed_at"].is_null() || !record["data"]["archived_at"].is_null() {return; }let data = &record["data"];letmut keys = columns(definition);if definition.voice_words.as_ref().is_none_or(|keys| !keys.is_empty()) && definition.column(&definition.title).is_some_and(|c| matches!(c.column_type, ColumnType::Text | ColumnType::Place) && c.secret != Some(true) && c.computed.is_none()) { keys.push(&definition.title); }for key in keys {let origin = json!({"databaseId":database,"table":definition.id,"recordId":record["id"],"column":key,"label":definition.plural});let values = match &data[key] {Value::String(value) => vec![value.as_str()],Value::Array(values) => values.iter().filter_map(Value::as_str).collect(), _ => Vec::new(), };for value in values {let normalized = super::settings_writes::normalize(value).to_lowercase(); add(words, value, "records", origin.clone(), 0, "");if words.contains_key(&normalized) { bands.entry(normalized).and_modify(|old| *old = (*old).min(band)).or_insert(band); } } } };ifletSome(id) = screen["recordId"].as_str() {let record = client.read_tool("get_record_by_table", json!({"table":table,"id":id}).as_object().unwrap())?; include(definition, &record, 0);if record["deleted_at"].is_null() {let linked = client.with_file(|file| {let db = file.driver;letmut linked = Vec::<(String, String)>::new();for row in db.all("SELECT to_kind AS kind, to_id AS record FROM cotton_links WHERE workspace_id = ? AND from_kind = ? AND from_id = ? AND to_database IS NULL UNION SELECT from_kind AS kind, from_id AS record FROM cotton_links WHERE workspace_id = ? AND to_kind = ? AND to_id = ? AND to_database IS NULL", &[text(file.workspace_id),text(table),text(id),text(file.workspace_id),text(table),text(id)]).map_err(|e| e.to_string())? { linked.push((row.text("kind").unwrap_or_default().into(), row.text("record").unwrap_or_default().into())); }for row in db.all("SELECT project_id FROM cotton_project_links WHERE workspace_id = ? AND record_kind = ? AND record_id = ?", &[text(file.workspace_id),text(table),text(id)]).map_err(|e| e.to_string())? { linked.push(("project".into(), row.text("project_id").unwrap_or_default().into())); }Ok(linked) })?;for (target, linked_id) in linked.into_iter().take(MAX_BIAS_TERMS) {ifletSome(linked_definition) = definitions.iter().find(|d| d.id == target) {ifletOk(linked) = client.read_tool("get_record_by_table", json!({"table":target,"id":linked_id}).as_object().unwrap()) { include(linked_definition, &linked, 0); } } }for column in &definition.columns {letSome(target) = column.link_to.as_deref() else { continue; };if column.secret == Some(true) { continue; }letSome(linked_definition) = definitions.iter().find(|d| d.id == target) else { continue; };let ids: Vec<&str> = match &record["data"][&column.key] {Value::String(id) => vec![id],Value::Array(ids) => ids.iter().filter_map(Value::as_str).collect(), _ => Vec::new(), };for id in ids.into_iter().take(MAX_BIAS_TERMS) {ifletOk(linked) = client.read_tool("get_record_by_table", json!({"table":target,"id":id}).as_object().unwrap()) { include(linked_definition, &linked, 0); } } } } }letmut list_args = json!({"table":table,"limit":MAX_BIAS_TERMS});let view = screen["view"].as_str();let group_from_view = view.and_then(|v| v.strip_prefix(&format!("{table}/")));let group_id = screen["group"].as_str().or_else(|| screen["group"]["id"].as_str()).or(group_from_view);ifletSome(group_id) = group_id { list_args["where"] = json!({"group":group_id}); } elseifletSome(column) = screen["group"]["column"].as_str() { list_args["where"] = json!({}); list_args["where"][column] = screen["group"]["value"].clone(); }ifletSome(section) = view.filter(|v| !v.contains('/')) { list_args["section"] = json!(section); list_args["today"] = json!(client.clock().now().format("%Y-%m-%d").to_string());ifletSome(zone) = client.time_zone() { list_args["timezone"] = json!(zone); } }// Explicit visible ids are the renderer's selection, never hint words.// The same generic read enforces deletion and secret-column rules.ifletSome(ids) = screen["visibleRecordIds"].as_array() {if ids.is_empty() { list_args = json!({"table":table}); } else { list_args = json!({"table":table,"ids":ids.iter().take(MAX_BIAS_TERMS).collect::<Vec<_>>()}); } }if !screen["visibleRecordIds"].as_array().is_some_and(Vec::is_empty) {let list = client.read_rows("read.voiceContext", &mut |ctx| cotton_tools::mcp::handlers::tables::list_answer(ctx, list_args.as_object().unwrap(), cotton_tools::mcp::handlers::tables::Total::Skipped).map_err(|e| e.to_string()))?;for record in list["records"].as_array().into_iter().flatten() { include(definition, record, 1); } }let groups = client.with_file(|file| {let sql = if screen["recordId"].is_string() {"SELECT g.id,g.name FROM cotton_groups g WHERE g.workspace_id = ? AND g.table_id = ? AND g.deleted_at IS NULL AND EXISTS (SELECT 1 FROM cotton_group_members m WHERE m.group_id = g.id AND m.workspace_id = g.workspace_id AND m.record_id = ?)" } else {"SELECT id,name FROM cotton_groups WHERE workspace_id = ? AND table_id = ? AND deleted_at IS NULL" };letmut params = vec![text(file.workspace_id),text(table)];ifletSome(id) = screen["recordId"].as_str() { params.push(text(id)); } file.driver.all(sql, ¶ms).map_err(|e| e.to_string()) })?;for row in groups {let band = if screen["recordId"].is_string() || group_id == row.text("id") { 0 } else { 1 };let name = row.text("name").unwrap_or_default();let key = super::settings_writes::normalize(name).to_lowercase(); add(words, name, "records", json!({"databaseId":database,"table":"group","recordId":row.text("id"),"column":"name","label":"Groups"}),0,"");if words.contains_key(&key) { bands.entry(key).or_insert(band); } }ifletSome(grouping) = &definition.group {for heading in grouping.sections.iter().flatten().filter_map(|s| s.heading.as_deref()) {let key = super::settings_writes::normalize(heading).to_lowercase(); add(words, heading, "records", json!({"databaseId":database,"table":table,"column":grouping.column,"label":definition.plural}), 0, "");if words.contains_key(&key) { bands.entry(key).or_insert(1); } } }Ok(())}pub(crate) fn start(client: &Arc<ClientController>, runtime: &tokio::runtime::Handle) { start_every(client, runtime, EVERY);}fn start_every( client: &Arc<ClientController>, runtime: &tokio::runtime::Handle, interval: Duration,) {let weak = Arc::downgrade(client); runtime.spawn(asyncmove {letmut every = tokio::time::interval(interval); every.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);loop { every.tick().await;letSome(client) = weak.upgrade() else {break; };ifletOk(Err(error)) = tokio::task::spawn_blocking(move || refresh(&client)).await { tracing::debug!("voice context will retry: {error}"); } } });}#[cfg(test)]#[path = "voice_words_tests.rs"]mod tests;