Cotton code
619 lines · 31.0 KB · RustRaw
use super::*;use crate::fixture;use crate::phone::reads::home_tests::workspace;use rusqlite::types::Value as SqlValue;use serde_json::json;/// RULE: Definition provenance never chooses dictation columns or record storage; the engine and voice_words keys describe that behavior, so an edited or imported definition can answer the same names.#[test]fn dictation_columns_do_not_depend_on_definition_provenance() {    let mut definition = cotton_core::definitions::builtin_table_definitions().iter().find(|d| d.id == "person").unwrap().clone();    let expected: Vec<String> = columns(&definition).into_iter().map(str::to_owned).collect();    definition.builtin = false;    assert_eq!(columns(&definition), expected);    definition.voice_words = None;    assert!(columns(&definition).is_empty());    definition.builtin = true;    assert!(columns(&definition).is_empty());    definition.engine = None;    assert_eq!(columns(&definition), vec![definition.title.as_str()]);    definition.builtin = false;    assert_eq!(columns(&definition), vec![definition.title.as_str()]);}#[test]fn records_feed_dictation_manual_spelling_wins_and_deleted_sources_disappear() {    // A learned name is derived, never a synced manual addition: deleting its final source forgets it.    let (_dir, client) = workspace(|db| {        db.run("INSERT INTO cotton_people (id, workspace_id, full_name, org, created_at, updated_at) VALUES ('voice-person', ?, 'Zéphyr Wren', 'Quokka Works', ?, ?)",            &[SqlValue::from(fixture::WORKSPACE.to_string()), SqlValue::from("2026-10-07".to_string()), SqlValue::from("2026-10-07".to_string())]).unwrap();        db.run("INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, created_at) VALUES ('voice-manual', ?, 'ZÉPHYR WREN', 'manual', 0, '2026-10-07')", &[SqlValue::from(fixture::WORKSPACE.to_string())]).unwrap();    });    let first = refresh(&client).unwrap();    assert!(first["biasTerms"]        .as_array()        .unwrap()        .contains(&json!("ZÉPHYR WREN")));    assert!(!first["biasTerms"]        .as_array()        .unwrap()        .contains(&json!("Zéphyr Wren")));    assert!(first["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("Quokka Works")));    assert_eq!(        first["count"].as_u64().unwrap() as usize,        first["words"].as_array().unwrap().len()    );    let derived = first["words"]        .as_array()        .unwrap()        .iter()        .find(|w| w["term"] == "Quokka Works")        .unwrap();    assert_eq!(derived["origins"][0]["table"], "person");    assert_eq!(derived["origins"][0]["recordId"], "voice-person");    client        .with_writer(|file| {            file.driver                .run(                    "UPDATE cotton_people SET archived_at = '2026-10-07' WHERE id = 'voice-person'",                    &[],                )                .unwrap();            Ok(())        })        .unwrap();    let after = refresh(&client).unwrap();    assert!(after["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("ZÉPHYR WREN")));    assert!(!after["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("Quokka Works")));}fn user_table(db: &Driver, id: &str, extra: Value) {    let mut definition = json!({        "id":id, "name":"Name", "plural":"Names", "builtin":false,        "columns":[{"key":"name","type":"text"},{"key":"password","type":"text","secret":true}],        "title":"name", "slip":{"title":"name"}, "tile":{"face":"slip-list"}, "page":[]    });    definition        .as_object_mut()        .unwrap()        .extend(extra.as_object().unwrap().clone());    TableDefinition::from_json(&definition.to_string())        .unwrap()        .validate()        .unwrap();    db.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, '2026-10-07', '2026-10-07')", &[text(id), text(fixture::WORKSPACE), text(&definition.to_string())]).unwrap();    // The made table's own table, as a definition's arrival steps the file.    cotton_store::schema::package_shape::step_file(db).unwrap();}#[test]fn custom_tools_contribute_names_but_never_secret_titles_or_opted_out_columns() {    let (_dir, client) = workspace(|db| {        user_table(db, "pet", json!({}));        user_table(db, "company", json!({}));        user_table(db, "excluded", json!({"voice_words":[]}));        user_table(db, "private", json!({"title":"password"}));        for (table, name) in [            ("pet", "Pamplemousse"),            ("company", "Pamplemousse"),            ("excluded", "Excluded Name"),            ("private", "Private Name"),        ] {            let data = json!({"name":name,"password":"SyntheticSecretMustNotBeSpoken"});            db.run(&format!("INSERT INTO cotton_{table} (id, workspace_id, name, password, created_at, updated_at) VALUES (?, ?, ?, ?, '2026-10-07', '2026-10-07')"), &[text(table),text(fixture::WORKSPACE),text(data["name"].as_str().unwrap()),text(data["password"].as_str().unwrap())]).unwrap();        }    });    let first = refresh(&client).unwrap();    let words = first["words"].as_array().unwrap();    assert!(words        .iter()        .all(|w| !w["term"].as_str().unwrap().contains("Secret")));    assert!(!first["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("Excluded Name")));    assert!(!first["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("Private Name")));    let name = words.iter().find(|w| w["term"] == "Pamplemousse").unwrap();    assert_eq!(name["origins"].as_array().unwrap().len(), 2);    for id in ["pet", "company"] {        client            .with_writer(|file| {                file.driver                    .run(                        &format!("UPDATE cotton_{id} SET deleted_at = '2026-10-07' WHERE id = ?"),                        &[text(id)],                    )                    .unwrap();                Ok(())            })            .unwrap();        let current = refresh(&client).unwrap();        assert_eq!(            current["vocabularyTerms"]                .as_array()                .unwrap()                .contains(&json!("Pamplemousse")),            id == "pet"        );    }}/// RULE: A tool the person made feeds the recogniser its own name and plural, even with no record yet and with its columns opted out, so "add to my allotment beds" is heard; a shipped tool's name is not added.#[test]fn a_custom_tools_own_name_feeds_the_recogniser() {    let (_dir, client) = workspace(|db| {        user_table(            db,            "allotment_bed",            json!({"name":"Allotment bed","plural":"Allotment beds","voice_words":[]}),        );    });    let read = refresh(&client).unwrap();    let terms = read["vocabularyTerms"].as_array().unwrap();    assert!(terms.contains(&json!("Allotment bed")), "{terms:?}");    assert!(terms.contains(&json!("Allotment beds")), "{terms:?}");    let word = read["words"]        .as_array()        .unwrap()        .iter()        .find(|w| w["term"] == "Allotment beds")        .unwrap();    assert_eq!(word["origins"][0]["table"], "tool");    assert_eq!(word["origins"][0]["recordId"], "allotment_bed");    // Shipped tools can be data-only too; their names are ordinary vocabulary.    // Check origins against the catalogue so new shipped tools cannot leak in.    for word in read["words"].as_array().unwrap() {        for origin in word["origins"].as_array().unwrap() {            if origin["table"] == "tool" {                let id = origin["recordId"].as_str().unwrap();                assert!(                    cotton_core::definitions::builtin_table_definition(id).is_none(),                    "shipped tool {id} contributes a name"                );            }        }    }}#[test]fn large_record_context_keeps_manual_priority_and_counts_the_uncapped_unique_words() {    let (_dir, client) = workspace(|db| {        user_table(db, "pet", json!({}));        for index in 0..1200 {            db.run("INSERT INTO cotton_pet (id, workspace_id, name, created_at, updated_at) VALUES (?, ?, ?, '2026-10-07', '2026-10-07')", &[text(&format!("pet-{index}")),text(fixture::WORKSPACE),text(&format!("Pet {index:04}"))]).unwrap();        }        db.run("INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, created_at) VALUES ('manual', ?, 'Zigzag', 'manual', 0, '2026-10-07')", &[text(fixture::WORKSPACE)]).unwrap();    });    let context = refresh(&client).unwrap();    let vocabulary = context["vocabularyTerms"].as_array().unwrap();    assert_eq!(context["count"], vocabulary.len());    for index in 0..1200 {        assert!(vocabulary.contains(&json!(format!("Pet {index:04}"))), "every fixture record contributes its word before bias capping");    }    assert_eq!(context["manualCount"], 1);    assert_eq!(context["automaticCount"].as_u64().unwrap(), context["count"].as_u64().unwrap() - context["manualCount"].as_u64().unwrap());    assert_eq!(context["biasCount"], MAX_BIAS_TERMS);    assert_eq!(context["biasTerms"][0], "Zigzag");    assert_eq!(refresh(&client).unwrap(), context, "an idle pass is stable");    client        .with_file(|file| {            assert_eq!(                file.driver                    .get("SELECT count(*) AS n FROM cotton_voice_vocabulary", &[])                    .unwrap()                    .unwrap()                    .int("n"),                Some(1),                "derived words are never written to the synced manual list"            );            Ok(())        })        .unwrap();}#[tokio::test]async fn the_kept_pass_refreshes_without_opening_the_editor_or_starting_dictation() {    let (_dir, client) = workspace(|_| {});    start_every(        &client,        &tokio::runtime::Handle::current(),        Duration::from_millis(10),    );    async fn wait_for(client: &ClientController, name: &str) {        tokio::time::timeout(Duration::from_secs(5), async {            loop {                if client                    .voice_context                    .lock()                    .unwrap()                    .as_ref()                    .is_some_and(|v| {                        v["vocabularyTerms"]                            .as_array()                            .unwrap()                            .contains(&json!(name))                    })                {                    break;                }                tokio::time::sleep(Duration::from_millis(5)).await;            }        })        .await        .expect("the kept pass refreshed on its own");    }    wait_for(&client, "Alpaca Tester").await;    client        .with_writer(|file| {            file.driver                .run(                    "UPDATE cotton_people SET full_name = 'Juniper Wren' WHERE id = 'person-a'",                    &[],                )                .unwrap();            Ok(())        })        .unwrap();    wait_for(&client, "Juniper Wren").await;    let kept = client.voice_context.lock().unwrap();    assert!(!kept.as_ref().unwrap()["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("Alpaca Tester")));}#[test]fn the_editor_only_lists_manual_additions_and_the_context_read_feeds_the_mic() {    let (_dir, client) = workspace(|db| {        for (id, term, source) in [("typed", "Zigzag", "manual"), ("learned", "Quince", "auto")] {            db.run("INSERT INTO cotton_voice_vocabulary (id, workspace_id, term, source, use_count, created_at) VALUES (?, ?, ?, ?, 0, '2026-10-07')", &[text(id),text(fixture::WORKSPACE),text(term),text(source)]).unwrap();        }    });    let read = |name| {        crate::phone::answer_read(            &client,            crate::phone::reads::read_for(name).unwrap(),            &serde_json::Map::new(),        )        .unwrap()    };    let editor = read("read.voiceVocabulary");    assert_eq!(editor["terms"].as_array().unwrap().len(), 1);    assert_eq!(editor["terms"][0]["term"], "Zigzag");    let context = read("read.voiceContext");    assert_eq!(context["biasTerms"], read("read.take")["biasTerms"]);    assert_eq!(context["manualCount"], 1);    assert!(context["vocabularyTerms"]        .as_array()        .unwrap()        .contains(&json!("Alpaca Tester")));}#[test]fn record_name_filter_never_discards_an_explicit_manual_word() {    let mut words = BTreeMap::new();    let long = "a".repeat(101);    for raw in ["12345", long.as_str()] {        add(&mut words, raw, "records", json!({}), 0, "");        assert!(!words.contains_key(raw));        add(&mut words, raw, "manual", json!({}), 0, "");        assert_eq!(words[raw].term, raw);    }}#[test]fn opening_the_core_starts_the_voice_pass_on_a_phone_without_a_screen_read() {    // The timer must be wired into the real handle, not only callable in a test.    let (dir, seeded_client) = workspace(|_| {});    drop(seeded_client);    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: dir.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: None,        time_zone: Some("UTC".into()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Dev,        manifest: None,    })    .unwrap();    let client = handle.client();    handle.runtime().block_on(async {        tokio::time::timeout(Duration::from_secs(5), async {            loop {                if client                    .voice_context                    .lock()                    .unwrap()                    .as_ref()                    .is_some_and(|v| {                        v["vocabularyTerms"]                            .as_array()                            .unwrap()                            .contains(&json!("Alpaca Tester"))                    })                {                    break;                }                tokio::time::sleep(Duration::from_millis(10)).await;            }        })        .await        .expect("opening the core arms voice context without an editor or mic read");    });}// RULE: The automatic vocabulary gains merchants (Records slips typed by kind):// a service thread's merchant is a name dictation hears, and a thread in the// bin is not.#[test]fn a_records_merchant_feeds_dictation() {    let (_dir, client) = workspace(|db| {        for (id, merchant, trashed) in [("thread-shop", "Quokka Coffee Roasters", None), ("thread-gone", "Binned Bakery", Some("2026-10-07"))] {            db.run(                "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, email_count, sender_kind, record_kind, merchant, trashed_at, created_at, updated_at) \                 VALUES (?, ?, ?, 'Your receipt', 1, 'service', 'receipt', ?, ?, '2026-10-07', '2026-10-07')",                &[text(id), text(fixture::WORKSPACE), text(id), text(merchant), trashed.map_or(SqlValue::Null, text)],            )            .unwrap();        }    });    let context = refresh(&client).unwrap();    let terms = context["vocabularyTerms"].as_array().unwrap();    assert!(terms.contains(&json!("Quokka Coffee Roasters")), "{terms:?}");    assert!(!terms.contains(&json!("Binned Bakery")), "{terms:?}");}/// `threads` mail threads with no merchant beside `merchants` that name one.fn mail_file(dir: &tempfile::TempDir, threads: usize, merchants: usize) -> cotton_store::Driver {    let db = fixture::seeded(&dir.path().join("life.db"));    let workspace = SqlValue::from(fixture::WORKSPACE.to_string());    db.run(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?2)         INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, summary, created_at, updated_at)         SELECT 'bare-' || i, ?1, 'bare-' || i, 'A thread of no merchant ' || i, printf('%.2000c', 'x'), '2026-10-12', '2026-10-12' FROM n",        &[workspace.clone(), SqlValue::from(threads as i64)],    )    .unwrap();    db.run(        "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?2)         INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, merchant, created_at, updated_at)         SELECT 'shop-' || i, ?1, 'shop-' || i, 'Your order', 'Quokka Shop ' || char(64 + i), '2026-10-12', '2026-10-12' FROM n",        &[workspace, SqlValue::from(merchants as i64)],    )    .unwrap();    db}fn steps_of_a_pass(db: &cotton_store::Driver) -> (u64, BTreeMap<String, Word>) {    let before = db.steps();    let mut words = BTreeMap::new();    record_words(db, fixture::WORKSPACE, &mut words).unwrap();    (db.steps() - before, words)}/// RULE: The dictation vocabulary's read grows with the rows that carry a word, never with the table: the mail threads that name a merchant are read through their own index, and a thread with none is never opened.////// One Mac, 12 Oct 2026 01:40Z: `a hold of <personal file> took 10.5 s — nothing/// that named itself; … 1,193,218 steps read … SELECT id, "merchant" FROM/// cotton_email_threads WHERE workspace_id = ? AND trashed_at IS NULL ORDER BY/// id`. The serving Mac runs this pass every 30 s inside its hold, and it read/// all 81k of the owner's threads, wide rows and all, for the 7.6k that name a/// merchant.#[test]fn the_vocabulary_reads_the_threads_that_name_a_merchant_never_every_thread() {    let small = tempfile::tempdir().unwrap();    let (alone, words) = steps_of_a_pass(&mail_file(&small, 0, 12));    assert!(words.contains_key("quokka shop a"), "a merchant is a word");    let big = tempfile::tempdir().unwrap();    let crowd = mail_file(&big, 20_000, 12);    let (beside, words) = steps_of_a_pass(&crowd);    assert_eq!(        words.keys().filter(|word| word.starts_with("quokka shop")).count(),        12,        "every merchant is still heard"    );    assert!(        beside <= alone * 2 + 1_000 && beside < 20_000,        "the pass read {beside} steps beside 20,000 threads that name no merchant, {alone} without them"    );    crowd.watch_statements();    let _ = steps_of_a_pass(&crowd);    let read = crowd        .statements_seen()        .into_iter()        .find(|sql| sql.contains("FROM cotton_email_threads"))        .expect("the pass reads the mail threads");    let plan: Vec<String> = crowd        .all(&format!("EXPLAIN QUERY PLAN {read}"), &[SqlValue::from(fixture::WORKSPACE.to_string())])        .unwrap()        .iter()        .filter_map(|row| row.text("detail").map(str::to_string))        .collect();    assert!(        plan.iter().any(|step| step.contains("COVERING INDEX idx_cotton_email_threads_merchant")),        "{read}: {plan:?}"    );}/// RULE: Every pass over a person's file names itself in the hold it takes: a slow hold that says "nothing that named itself" can be diagnosed only from a stack sample of the live process.#[test]fn the_vocabulary_pass_names_itself_in_its_hold() {    let (_dir, client) = workspace(|_| {});    let tally = cotton_store::held::tally();    refresh(&client).unwrap();    let work = tally.done();    assert!(work.doing.iter().any(|what| what == DOING), "{:?}", work.doing);}/// RULE: Screen names and linked names precede visible titles, manual words, database names and global fill; without a screen only manual, database and global bands apply.#[test]fn screen_context_ranks_records_links_visible_titles_and_manual_words() {    let (_dir, client) = workspace(|db| {        user_table(db, "pet", json!({"columns":[{"key":"name","type":"text"},{"key":"friend","type":"link","link_to":"person"}]}));        for (id, name, friend) in [("current","Zebra Current",Some("person-a")),("visible","Yak Visible",None),("other","Aardvark Other",None)] {            db.run("INSERT INTO cotton_pet (id, workspace_id, name, friend, created_at, updated_at) VALUES (?, ?, ?, ?, '2026-10-14', '2026-10-14')",                &[text(id),text(fixture::WORKSPACE),text(name),friend.map_or(SqlValue::Null,text)]).unwrap();        }        db.run("INSERT INTO cotton_voice_vocabulary (id,workspace_id,term,source,use_count,created_at) VALUES ('manual',?,'Wren Manual','manual',0,'2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();    });    let screen = json!({"screen":{"databaseId":fixture::WORKSPACE,"table":"pet","recordId":"current","visibleRecordIds":["visible"]}});    let answer = context_for(&client, screen.as_object().unwrap()).unwrap();    let terms = answer["biasTerms"].as_array().unwrap();    let at = |term| terms.iter().position(|v| v == term).unwrap();    assert!(at("Zebra Current") < at("Yak Visible"));    assert!(at("Alpaca Tester") < at("Yak Visible"));    assert!(at("Yak Visible") < at("Wren Manual"));    assert!(at("Wren Manual") < at("Aardvark Other"));    let grouped: Vec<_> = answer["biasGroups"].as_array().unwrap().iter()        .flat_map(|g| g["terms"].as_array().unwrap()).collect();    assert_eq!(grouped.len(), terms.len());    for term in terms { assert_eq!(grouped.iter().filter(|value| **value == term).count(),1); }    assert_eq!(answer["biasGroups"][0]["tag"],"manual");    let plain = context(&client).unwrap();    assert_eq!(plain["biasTerms"][0], "Wren Manual");}/// RULE: A final transcript increments each shown hinted term once per stop, using whole terms and preserving manual spelling; generated usage is source auto and unmatched hints never create rows.#[test]fn final_transcript_batches_distinct_whole_term_usage() {    let (_dir, client) = workspace(|db| {        fixture::this_devices_row(db);        db.run("INSERT INTO cotton_voice_vocabulary (id,workspace_id,term,source,use_count,created_at) VALUES ('manual',?,'ZÉPHYR WREN','manual',2,'2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();        cotton_tools::test_fixtures::reconcile(db, "cotton_voice_vocabulary");    });    client.set_self_device_id(Some(fixture::SELF_DEVICE_ID.into()));    let answer = client.write_rows("settings.recordVoiceUse", &mut |ctx|        cotton_tools::dictation::record_use(ctx, "Zéphyr Wren, zéphyr wren and Quokka Works. concatenate",            &["Zéphyr Wren".into(),"zéphyr wren".into(),"Quokka Works".into(),"cat".into(),"Absent".into()])).unwrap();    assert_eq!(answer["answer"]["updated"],2);    client.with_file(|file| {        let rows=file.driver.all("SELECT term,source,use_count,last_used_at FROM cotton_voice_vocabulary ORDER BY source",&[]).unwrap();        assert_eq!(rows.len(),2,"rows={rows:?}; answer={answer}");        assert_eq!(rows[0].text("source"),Some("auto"));        assert_eq!(rows[0].int("use_count"),Some(1));        assert_eq!(rows[1].text("term"),Some("ZÉPHYR WREN"));        assert_eq!(rows[1].int("use_count"),Some(3));        assert!(rows.iter().all(|r| r.text("last_used_at").is_some()));        Ok(())    }).unwrap();}/// RULE: A crowded screen cannot crowd out a person's manual words, and explicit column opt-out and secret titles stay private even on the named screen.#[test]fn screen_cap_keeps_manual_words_and_never_hints_private_titles() {    let (_dir, client) = workspace(|db| {        user_table(db, "private", json!({"title":"password"}));        db.run("INSERT INTO cotton_private (id,workspace_id,name,password,created_at,updated_at) VALUES ('private',?,'Public Name','Hidden Secret','2026-10-14','2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();        user_table(db, "pet", json!({}));        for index in 0..120 {            db.run("INSERT INTO cotton_pet (id,workspace_id,name,created_at,updated_at) VALUES (?,?,?,'2026-10-14','2026-10-14')",&[text(&format!("pet-{index}")),text(fixture::WORKSPACE),text(&format!("Pet {index:04}"))]).unwrap();        }        db.run("INSERT INTO cotton_voice_vocabulary (id,workspace_id,term,source,use_count,created_at) VALUES ('manual',?,'Zigzag Manual','manual',0,'2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();    });    let read = |screen: Value| context_for(&client,json!({"screen":screen}).as_object().unwrap()).unwrap();    let crowded=read(json!({"table":"pet","databaseId":fixture::WORKSPACE}));    assert!(crowded["biasTerms"].as_array().unwrap().contains(&json!("Zigzag Manual")));    assert!(crowded["biasTerms"].as_array().unwrap().len() <= MAX_BIAS_TERMS);    let private=read(json!({"table":"private","recordId":"private","databaseId":fixture::WORKSPACE}));    assert!(!private["vocabularyTerms"].as_array().unwrap().contains(&json!("Hidden Secret")));}/// RULE: Screen priority follows stored person/group links, not a caller-provided vocabulary, and a group view reads only its members.#[test]fn stored_links_and_group_view_supply_screen_names() {    let (_dir, client) = workspace(|db| {        db.run("INSERT INTO cotton_links (id,workspace_id,from_kind,from_id,to_kind,to_id,created_at) VALUES ('voice-link',?,'note','note-a','person','person-a','2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();        db.run("INSERT INTO cotton_groups (id,workspace_id,table_id,name,created_at,updated_at) VALUES ('voice-group',?,'note','Zephyr Group','2026-10-14','2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();        db.run("INSERT INTO cotton_group_members (id,workspace_id,group_id,record_id,place,created_at,updated_at) VALUES ('voice-member',?,'voice-group','note-a',1,'2026-10-14','2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();        db.run("INSERT INTO cotton_voice_vocabulary (id,workspace_id,term,source,use_count,created_at) VALUES ('manual',?,'Manual Priority','manual',0,'2026-10-14')",&[text(fixture::WORKSPACE)]).unwrap();    });    let read = |screen: Value| context_for(&client,json!({"screen":screen}).as_object().unwrap()).unwrap();    let record=read(json!({"table":"note","recordId":"note-a","databaseId":fixture::WORKSPACE,"visibleRecordIds":[]}));    let terms=record["biasTerms"].as_array().unwrap();    let manual=terms.iter().position(|v| v=="Manual Priority").unwrap();    for name in ["Alpaca Tester","Zephyr Group"] {        assert!(terms.iter().position(|v|v==name).unwrap()<manual,"{name}: {terms:?}");    }    let group=read(json!({"table":"note","view":"note/voice-group","databaseId":fixture::WORKSPACE}));    assert!(group["biasTerms"].as_array().unwrap().contains(&json!("Zephyr Group")));}/// RULE: the device's dictation model is compiled from words and names only — every kept name, tagged as the hints are — and never from a note's body, a thought, a message or any whole text: whole texts made a 237 MB corpus per build that held a core of the serving Mac for 23 hours (item 29, 19 Oct 2026), and a vocabulary is kilobytes.#[test]fn the_voice_corpus_is_names_only_and_never_a_whole_text() {    let ws = || SqlValue::from(fixture::WORKSPACE.to_string());    let sentence = |n: usize| format!("Sentence {n} of the invented ledger walks past the quiet orchard toward Velmora Ridge");    let body = (0..130).map(sentence).collect::<Vec<_>>().join(". ");    assert!(body.len() >= 10 * 1024, "a 10 KB note");    let (_dir, client) = workspace(|db| {        db.run("INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('corpus-person', ?, 'Anvika Rathore', '2026-10-14', '2026-10-14')", &[ws()]).unwrap();        db.run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) VALUES ('corpus-note', ?, 'note', 'Orchard ledger', ?, '2026-10-14', '2026-10-14')", &[ws(), SqlValue::from(body.clone())]).unwrap();        db.run("INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, created_at, updated_at) VALUES ('corpus-thought', ?, 'ask Anvika about the Kestrel invoice', '2026-10-14T08:00:00Z', '2026-10-14', '2026-10-14')", &[ws()]).unwrap();        db.run("INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) VALUES ('corpus-thread', ?, 'group', 'Weekend', '2026-10-14', '2026-10-14')", &[ws()]).unwrap();        db.run("INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at) VALUES ('corpus-out', 'corpus-thread', ?, 'out', 'cotton', 'live', 'see you at Koramangala tomorrow', '2026-10-14T09:00:00Z', '2026-10-14')", &[ws()]).unwrap();    });    let corpus = corpus(&client, &serde_json::Map::new()).unwrap();    let people = corpus["names"].as_array().unwrap().iter().find(|g| g["tag"] == "people").unwrap();    assert!(people["terms"].as_array().unwrap().contains(&json!("Anvika Rathore")));    assert!(corpus.get("phrases").is_none(), "the corpus carries no lines: {corpus}");    let answer = corpus.to_string();    for line in (0..130).map(sentence).chain(["ask Anvika about the Kestrel invoice".into(), "see you at Koramangala tomorrow".into()]) {        assert!(!answer.contains(&line), "a whole text reached the corpus: {line}");    }    assert!(answer.len() < 64 * 1024, "a vocabulary is kilobytes: {} bytes", answer.len());}/// RULE: Place columns contribute the person's kept words to dictation, with the same source attribution as stored text; the dataset itself is never a vocabulary source.#[test]fn kept_place_words_feed_dictation_from_the_persons_records() {    let (_dir, client) = workspace(|db| {        user_table(db,"hamlet",json!({"voice_words":["name"],"columns":[            {"key":"name","type":"place","place":{"id":"name_place","country":"country","zone":"timezone"}},            {"key":"name_place","type":"text","readonly":true},            {"key":"country","type":"text","readonly":true},            {"key":"timezone","type":"text","readonly":true}        ]}));        db.run("INSERT INTO cotton_hamlet (id,workspace_id,name,created_at,updated_at) VALUES ('invented-hamlet',?,'Quokkaloom','2026-10-14','2026-10-14')", &[text(fixture::WORKSPACE)]).unwrap();    });    let vocabulary = refresh(&client).unwrap();    let word = vocabulary["words"].as_array().unwrap().iter().find(|word| word["term"] == "Quokkaloom").expect("kept place words are learned");    assert_eq!(word["origins"][0]["table"],"hamlet");    assert_eq!(word["origins"][0]["recordId"],"invented-hamlet");}/// RULE: Dictation uses one language from the personal Me row in every database, defaults to the shipped English choice, and never mixes language codes.#[test]fn me_language_is_single_personal_and_defaults_to_shipped_english() {    let (_dir, client) = workspace(|db| {        db.run("UPDATE cotton_workspaces SET owner_person_id = 'person-a' WHERE id = ?",&[text(fixture::WORKSPACE)]).unwrap();    });    assert_eq!(context(&client).unwrap()["language"],"en");    client.with_writer(|file| {        file.driver.run("UPDATE cotton_people SET language = 'hi' WHERE id = 'person-a'",&[]).unwrap();        Ok(())    }).unwrap();    assert_eq!(context(&client).unwrap()["language"],"hi");    let parsed = cotton_tools::mcp::handlers::records_1::validate::validate_update_person(        json!({"id":"00000000-0000-4000-8000-000000000042","language":"hi"}).as_object().unwrap()).unwrap();    assert_eq!(parsed.language.as_deref(),Some("hi"));    for bad in [json!("en,hi"),json!("en-IN"),json!(["en","hi"]),Value::Null] {        assert!(cotton_tools::mcp::handlers::records_1::validate::validate_update_person(            json!({"id":"00000000-0000-4000-8000-000000000042","language":bad}).as_object().unwrap()).is_err());    }}