Cotton code
520 lines · 32.3 KB · RustRaw
use super::*;use chrono::TimeZone;use serde_json::json;fn now() -> DateTime<Utc> {    Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()}fn request(id: &str, asked: &str, state: &str, tables: Value) -> Value {    json!({        "id": id, "token_id": format!("tok-{id}"), "token_name": "Claude", "client": "Claude (claude.ai)",        "tables": tables, "reason": "To find the address Asha sent.", "minutes": 15,        "worker_pub": "AAAA", "requested_at": asked, "expires_at": "2026-11-11T09:05:00Z", "state": state,    })}fn lines() -> LineSet {    LineSet::shipped(LINES).expect("the unlock lines ship")}fn label(table: &str) -> Option<String> {    match table {        "message" => Some("Messages".into()),        "note" => Some("Notes".into()),        _ => None,    }}/// The card's choice row of durations, `on` the one given.fn durations(on: u32) -> Value {    json!([        {"minutes": 15, "label": "15 minutes", "on": on == 15},        {"minutes": 60, "label": "1 hour", "on": on == 60},        {"minutes": 1440, "label": "1 day", "on": on == 1440},        {"minutes": 0, "label": "Until I turn it off", "on": on == 0},    ])}/// GOLDEN: the card for the oldest waiting request: who asks, the reason, a toggle per table on, the kit's words.#[test]fn the_card_is_the_oldest_waiting_request_worded_by_its_tables() {    let rows = vec![        request("r2", "2026-11-11T08:58:00Z", "waiting", json!(["note"])),        request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["message", "note", "sealed_diary"])),        request("r0", "2026-11-11T08:50:00Z", "granted", json!(["message"])),    ];    let card = card(&rows, now(), label, &lines()).expect("a request waits");    assert_eq!(        serde_json::to_value(&card).unwrap(),        json!({            "face": "unlock.card", "requestId": "r1", "client": "Claude (claude.ai)", "tokenName": "Claude",            "title": "Let Claude (claude.ai) read some of what you keep?",            "reason": "To find the address Asha sent.",            "tables": [                {"table": "message", "label": "Messages", "on": true},                {"table": "note", "label": "Notes", "on": true},                {"table": "sealed_diary", "label": "sealed_diary", "on": true},            ],            "minutes": 15, "durations": durations(15), "expiresAt": "2026-11-11T09:05:00Z", "behind": 1,            "fields": {                "title": "Let Claude (claude.ai) read some of what you keep?",                "asker": "Claude (claude.ai) · Claude",                "reason": "To find the address Asha sent.",                "toggles": [                    {"table": "message", "label": "Messages", "on": true},                    {"table": "note", "label": "Notes", "on": true},                    {"table": "sealed_diary", "label": "sealed_diary", "on": true},                ],                "minutes": "15 minutes",                "durations": durations(15),                "expires": "Waits 5 more minutes",                "queue": "1 more request waits",            },            "acts": [                {"id": "allow", "label": "Allow", "method": "unlock.allow", "receipt": "Allowed", "presence": true},                {"id": "decline", "label": "Not now", "method": "unlock.decline", "receipt": "Not now", "presence": false},            ],            "ask": {                "who": "Claude",                "what": "What it can read",                "everything": {"label": "Only what it asked for", "line": "Notes, Messages, Everything else"},                "choose": {"label": "Let me choose", "line": "Tick only the things it may read."},                "groups": [                    {"id": "notes", "label": "Notes", "line": "Notes, journal, thoughts and saved articles", "tables": ["note"], "on": true},                    {"id": "messages", "label": "Messages", "line": "Chats, calls and posts", "tables": ["message"], "on": true},                    {"id": "other", "label": "Everything else", "line": "Anything you keep that isn't listed above", "tables": ["sealed_diary"], "on": true},                ],                "howLong": "For how long",                "howLongLine": "When the time is up, it will ask you again.",                "settings": "You can see or change this any time in Settings, under Your Claude.",            },        })    );}/// The card words a lone request in the singular, without a queue, and an open window's row by its minutes left.#[test]fn one_table_says_the_singular_and_a_window_says_what_is_left() {    let mut row = request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["note"]));    row["minutes"] = json!(60);    row["expires_at"] = json!("2026-11-11T09:00:30Z");    row["token_name"] = json!("Claude (claude.ai)");    let card = card(&[row], now(), label, &lines()).unwrap();    assert_eq!(card.fields["title"], "Allow Claude (claude.ai) to read Notes?");    assert_eq!(card.fields["asker"], "Claude (claude.ai)", "a token named as its client is said once");    assert_eq!(card.fields["minutes"], "1 hour");    assert_eq!(card.minutes, 60);    assert_eq!(serde_json::to_value(&card.durations).unwrap(), durations(60));    assert_eq!(card.fields["expires"], "Waits 1 more minute");    assert!(!card.fields.contains_key("queue"));    assert_eq!(window_said(&["note".into(), "message".into()], "2026-11-11T09:11:20Z", now(), label, &lines()), "Notes and Messages · 12 minutes left");    assert_eq!(window_acts().iter().map(|a| (a.id.as_str(), a.label.as_str())).collect::<Vec<_>>(), vec![("end", "End")]);}/// A copy keeps a list column as its JSON text: read the same.#[test]fn a_copys_list_text_reads_as_the_list() {    let rows = vec![request("r1", "2026-11-11T08:57:00Z", "waiting", json!("[\"message\"]"))];    assert_eq!(card(&rows, now(), label, &lines()).unwrap().title, "Allow Claude (claude.ai) to read Messages?");}/// An expired or answered request is no card, and no fast poll.#[test]fn nothing_waits_after_expiry_or_an_answer() {    let rows = vec![request("r1", "2026-11-11T08:50:00Z", "waiting", json!(["message"])), request("r2", "2026-11-11T08:58:00Z", "declined", json!(["message"]))];    let late = Utc.with_ymd_and_hms(2026, 11, 11, 9, 5, 0).unwrap();    assert!(card(&rows, late, label, &lines()).is_none());    assert_eq!(poll_seconds(&rows, late), None);    assert_eq!(poll_seconds(&rows, now()), Some(POLL_SECONDS));}/// RULE (ruling R4, 15 Nov 2026): Allow grants a non-empty subset of what was asked, sorted, for any of the four durations whatever the request suggested; the suggestion when none is chosen.#[test]fn allow_takes_a_subset_and_any_of_the_four_durations() {    let r = request_of(&request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["note", "message"]))).unwrap();    assert_eq!(allowed(&r, now(), None, None), Ok((vec!["message".into(), "note".into()], 15)));    for minutes in DURATIONS {        assert_eq!(allowed(&r, now(), Some(&["note".into()]), Some(minutes)), Ok((vec!["note".into()], minutes)), "the person's pick wins: {minutes}");    }    assert_eq!(allowed(&r, now(), Some(&[]), None).unwrap_err().code(), "bad_tables");    assert_eq!(allowed(&r, now(), Some(&["email".into()]), None).unwrap_err().code(), "bad_tables");    for minutes in [1, 5, 16, 30, 1441] {        assert_eq!(allowed(&r, now(), None, Some(minutes)).unwrap_err().code(), "bad_minutes", "{minutes}");    }    let late = Utc.with_ymd_and_hms(2026, 11, 11, 9, 5, 0).unwrap();    assert_eq!(allowed(&r, late, None, None).unwrap_err().code(), "request_not_waiting");}/// After a window: each handed table moves once past the version it was handed at.#[test]fn advance_moves_each_handed_table_once() {    let handed = vec![("message".to_string(), 3), ("note".to_string(), 1)];    assert_eq!(to_advance(&handed, |t| if t == "message" { 3 } else { 1 }), vec!["message".to_string(), "note".to_string()]);    assert_eq!(to_advance(&handed, |t| if t == "message" { 4 } else { 1 }), vec!["note".to_string()]);    assert!(to_advance(&handed, |_| 9).is_empty());    assert!(grant_ended(&json!({"ended_at": "2026-11-11T09:10:00Z"})));    assert!(!grant_ended(&json!({"ended_at": null})));}/// RULE: the face draws the card's fields and calls the unlock methods: every slot names a field the card answers.#[test]fn the_face_names_only_what_the_card_answers() {    let face: Value = serde_json::from_str(FACE).expect("the face reads");    assert_eq!(face["id"], FACE_ID);    let rows = vec![request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["message"]))];    let card = serde_json::to_value(card(&rows, now(), label, &lines()).unwrap()).unwrap();    for slot in face["slots"].as_array().unwrap() {        let field = slot["field"].as_str().unwrap();        assert!(card.get(field).is_some(), "the face's slot {} reads {field}, which the card does not answer", slot["slot"]);    }    let methods: Vec<&str> = face["acts"].as_array().unwrap().iter().chain(face["window"]["acts"].as_array().unwrap()).map(|a| a["method"].as_str().unwrap()).collect();    assert_eq!(methods, ["unlock.allow", "unlock.decline", "unlock.end"]);}/// RULE (12 Nov 2026): an Allow held while this device's vault founds keeps the card standing with the setting-up line and no acts; one that could not be completed says why and hands the acts back; a held Allow on another request changes nothing.#[test]fn a_held_allow_shows_the_setting_up_line_and_no_acts_until_it_completes() {    let rows = vec![request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["note"]))];    let held = card_held(&rows, now(), label, &lines(), Some(Held::Pending("r1"))).expect("the card stands");    assert_eq!(held.status.as_deref(), Some("Setting up your account… The window opens by itself once this is done."));    assert!(held.acts.is_empty(), "nothing to tap while the Allow is held");    let failed = card_held(&rows, now(), label, &lines(), Some(Held::Failed { request_id: "r1", sentence: "The person key is unreadable" })).unwrap();    assert_eq!(failed.status.as_deref(), Some("The person key is unreadable"));    assert_eq!(failed.acts.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(), vec!["allow", "decline"]);    let other = card_held(&rows, now(), label, &lines(), Some(Held::Pending("r9"))).unwrap();    assert_eq!(other, card(&rows, now(), label, &lines()).unwrap());    assert!(serde_json::to_value(&other).unwrap().get("status").is_none(), "no status when nothing is held");}/// RULE (12 Nov 2026): a held Allow is kept only within its request's life: answered, declined or expired, it is dropped.#[test]fn a_held_allow_is_kept_only_while_its_request_waits() {    let rows = vec![request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["note"])), request("r2", "2026-11-11T08:57:00Z", "declined", json!(["note"]))];    assert!(keep_held(&rows, now(), "r1"));    assert!(!keep_held(&rows, now(), "r2"), "answered");    assert!(!keep_held(&rows, now(), "r3"), "never asked");    assert!(!keep_held(&rows, Utc.with_ymd_and_hms(2026, 11, 11, 9, 5, 0).unwrap(), "r1"), "expired");}/// RULE (ruling R4): the request suggests one of the four durations (0, standing, included; anything else reads as 15), and the card's choice row has the suggestion on.#[test]fn the_request_suggests_a_duration_and_the_card_turns_it_on() {    for (asked, read) in [(json!(0), 0), (json!(60), 60), (json!(1440), 1440), (json!(15), 15), (json!(5), 15), (json!(30), 15), (json!(-1), 15), (json!(1.5), 15), (Value::Null, 15)] {        let mut row = request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["note"]));        row["minutes"] = asked.clone();        let r = request_of(&row).unwrap_or_else(|| panic!("{asked} still reads"));        assert_eq!(r.minutes, read, "{asked}");        let card = card(&[row], now(), label, &lines()).unwrap();        assert_eq!(serde_json::to_value(&card.durations).unwrap(), durations(read));        assert_eq!(card.fields["durations"], durations(read));        assert_eq!(allowed(&r, now(), None, None).unwrap().1, read, "Allow with no pick grants the suggestion");    }    let mut standing = request("r1", "2026-11-11T08:57:00Z", "waiting", json!(["note"]));    standing["minutes"] = json!(0);    assert_eq!(card(&[standing], now(), label, &lines()).unwrap().fields["minutes"], "Until I turn it off");}/// RULE (ruling R4): an open window says what it has left in minutes, in hours past two hours, and a standing one says it stays until turned off; a standing grant is open until it ends.#[test]fn windows_say_minutes_hours_or_until_turned_off() {    let tables = vec!["note".to_string()];    assert_eq!(window_said(&tables, "2026-11-11T10:00:00Z", now(), label, &lines()), "Notes · 60 minutes left");    assert_eq!(window_said(&tables, "2026-11-11T11:00:00Z", now(), label, &lines()), "Notes · 120 minutes left");    assert_eq!(window_said(&tables, "2026-11-12T08:59:00Z", now(), label, &lines()), "Notes · 24 hours left");    assert_eq!(window_said(&tables, "2026-11-11T11:01:00Z", now(), label, &lines()), "Notes · 3 hours left");    assert_eq!(window_said(&tables, STANDING_ENDS_AT, now(), label, &lines()), "Notes · until you turn it off");    let standing = json!({"id": "g1", "tables": ["note", "message"], "standing": true, "ends_at": STANDING_ENDS_AT, "ended_at": null});    assert!(grant_standing(&standing) && grant_open(&standing, now()));    assert_eq!(grant_said(&standing, now(), label, &lines()), "Notes and Messages · until you turn it off");    assert!(grant_standing(&json!({"standing": 1, "ends_at": "2026-11-11T09:15:00Z"})), "a copy keeps a bool as 1");    assert!(!grant_open(&json!({"standing": true, "ends_at": STANDING_ENDS_AT, "ended_at": "2026-11-11T08:59:00Z"}), now()), "ended is ended");    assert!(!grant_open(&json!({"standing": false, "ends_at": "2026-11-11T08:59:00Z"}), now()));    assert!(grant_open(&json!({"standing": false, "ends_at": "2026-11-11T09:01:00Z"}), now()));}/// RULE (ruling R4): the read log is newest first, at most fifty, each row saying which assistant read how many rows of which tables, and when.#[test]fn reads_are_newest_first_and_say_who_read_what_and_when() {    let read = |id: &str, at: &str, n: u64| json!({"id": id, "grant_id": "g1", "client": "Claude (claude.ai)", "tables": "[\"note\",\"message\"]", "tool": "list_records", "rows": n, "read_at": at});    let rows = vec![read("a", "2026-11-11T08:55:00Z", 12), read("b", "2026-11-11T09:00:00Z", 1), read("c", "2026-11-10T07:00:00Z", 3), read("d", "2026-11-11T06:00:00Z", 0), json!({"id": "x", "client": "Claude"})];    let said: Vec<String> = reads(&rows, now(), label, &lines()).into_iter().map(|r| r.said).collect();    assert_eq!(        said,        [            "Claude (claude.ai) read 1 item from Notes and Messages · just now",            "Claude (claude.ai) read 12 items from Notes and Messages · 5 minutes ago",            "Claude (claude.ai) read 0 items from Notes and Messages · 3 hours ago",            "Claude (claude.ai) read 3 items from Notes and Messages · 1 day ago",        ]    );    let first = &reads(&rows, now(), label, &lines())[0];    assert_eq!((first.grant_id.as_deref(), first.tool.as_deref(), first.rows), (Some("g1"), Some("list_records"), 1));    let many: Vec<Value> = (0..60).map(|i| read(&format!("r{i:02}"), &format!("2026-11-11T08:{i:02}:00Z").replace("08:6", "07:0"), 1)).collect();    assert_eq!(reads(&many, now(), label, &lines()).len(), READS_SHOWN);    assert_eq!(SHELL_TABLES, ["unlock_request", "unlock_grant", "assistant_read", "assistant_ask"]);}/// The one card for your Claude: no duration, the kit's promise as its reason, every table on.#[test]fn the_account_card_asks_no_duration_and_says_the_promise() {    let mut row = request("r9", "2026-11-11T08:59:00Z", "waiting", json!(["message", "note"]));    row["account"] = json!(1);    row["member_id"] = json!("mem-1");    row["minutes"] = json!(0);    row["expires_at"] = json!("9999-12-31T23:59:59.999Z");    assert_eq!(poll_seconds(std::slice::from_ref(&row), now()), None);    let card = card(&[row], now(), label, &lines()).unwrap();    assert!(card.account);    assert_eq!(card.title, "Let your Claude read your data");    assert!(card.durations.is_empty());    assert!(card.fields.get("durations").is_none() && card.fields.get("minutes").is_none());    // It stands until answered (the Worker files it to 9999): no countdown, and it alone keeps no fast sync.    assert!(card.fields.get("expires").is_none());    assert!(card.reason.as_deref().unwrap().starts_with("Cotton cannot read your data on its own."));    assert!(card.tables.iter().all(|t| t.on));    assert_eq!(request_of(&json!({"id": "x", "token_id": "t", "client": "c", "tables": ["note"], "worker_pub": "A", "requested_at": "2026-11-11T08:59:00Z", "expires_at": "2026-11-11T09:05:00Z", "state": "waiting", "account": true, "member_id": "m"})).unwrap().member_id.as_deref(), Some("m"));}/// RULE (owner, 23 Nov 2026: the card listed about forty tables by their raw names, Runs and Dev jobs among them): every/// table a shipped kit defines is named once in the core's map, under a group a person knows or as hidden (the system's/// own), so a new table is placed on purpose; one the map does not name falls into Other.#[test]fn every_shipped_table_lands_in_one_group_or_is_hidden() {    let named = named_tables();    let mut seen = std::collections::BTreeMap::new();    for (group, table) in &named {        assert!(seen.insert(*table, *group).is_none(), "{table} is named twice in kits/keys/reads.json");    }    let (mut missing, mut checked) = (Vec::new(), 0);    // Every kit's table files, as this crate ships them (kits/<kit>/tables/<id>.json).    let kits = cotton_store::manifest_dir().join("kits");    for kit in std::fs::read_dir(&kits).expect("the kits folder lists") {        let tables = kit.unwrap().path().join("tables");        let Ok(files) = std::fs::read_dir(&tables) else { continue };        for file in files {            let path = file.unwrap().path();            let Some(id) = path.file_name().and_then(|n| n.to_str()).and_then(|n| n.strip_suffix(".json")).map(str::to_string) else { continue };            checked += 1;            if !seen.contains_key(id.as_str()) {                missing.push(id);            }        }    }    assert!(checked > 150, "the sweep read {checked} table files: it is reading the wrong place");    missing.sort();    missing.dedup();    assert!(missing.is_empty(), "these tables are in no group and not hidden (add each to kits/keys/reads.json): {missing:?}");    assert_eq!(group_of("a_table_no_kit_defines"), Some(OTHER), "an unknown table falls into Other");    assert_eq!(group_ids().last(), Some(&OTHER), "Other comes last");    let words = lines();    for id in group_ids() {        assert!(words.say(&format!("card.groups.{id}.label"), &[]).is_some_and(|l| !l.is_empty()), "{id} has no label");        assert!(words.say(&format!("card.groups.{id}.line"), &[]).is_some_and(|l| !l.is_empty()), "{id} has no line");    }}/// RULE: the system's own tables (what assistants read, dev jobs, blocked senders, the keys and tokens) are/// never offered; saved secrets are hidden too, and the grant leaves them out anyway (seal::agent::NEVER).#[test]fn internal_tables_are_never_offered() {    for table in ["assistant_read", "dev_job", "blocked_sender", "memory", "session", "seal_key", "vault_key", "unlock_request", "unlock_grant", "mcp_token", "device"] {        assert_eq!(group_of(table), None, "{table} is the system's own");    }    for table in crate::seal::agent::NEVER {        assert_eq!(group_of(table), None, "{table} is never offered");    }    let mut row = request("r9", "2026-11-11T08:59:00Z", "waiting", json!(["assistant_read", "dev_job", "note", "email", "photo", "story_scene"]));    row["account"] = json!(true);    row["member_id"] = json!("mem-1");    row["expires_at"] = json!("9999-12-31T23:59:59.999Z");    row["connected_at"] = json!("2026-11-11T08:00:00Z");    let card = card(&[row], now(), label, &lines()).unwrap();    let offered: Vec<&str> = card.ask.groups.iter().map(|g| g.id.as_str()).collect();    assert_eq!(offered, ["notes", "mail", "photos", "scripts"]);    assert!(card.ask.groups.iter().all(|g| g.on && !g.tables.iter().any(|t| ["assistant_read", "dev_job"].contains(&t.as_str()))));    assert_eq!(card.ask.who, "Claude · connected 1 hour ago");    assert_eq!(card.ask.everything.label, "Everything you keep in Cotton");    assert_eq!(card.ask.how_long_line, "It can read whenever you ask it something, until you stop it in Settings, under Your Claude.");    assert!(card.ask.choose.is_some());}/// RULE: the grant given is the grant chosen. Everything grants every table asked, hidden ones too; chosen groups grant/// exactly their asked tables and nothing hidden; no group, or one the card did not offer, is refused by name.#[test]fn the_tables_granted_are_the_groups_chosen() {    let asked = json!(["assistant_read", "note", "journal_entry", "email", "email_thread", "photo", "sealed_diary"]);    let r = request_of(&request("r1", "2026-11-11T08:57:00Z", "waiting", asked)).unwrap();    let mut all: Vec<String> = r.tables.clone();    all.sort();    assert_eq!(chosen_tables(&r, None), Ok(all.clone()), "Everything is every table asked");    assert_eq!(chosen_tables(&r, Some(&["mail".into()])), Ok(vec!["email".to_string(), "email_thread".into()]));    assert_eq!(chosen_tables(&r, Some(&["notes".into(), "other".into()])), Ok(vec!["journal_entry".to_string(), "note".into(), "sealed_diary".into()]));    let every_group: Vec<String> = card(&[request("r1", "2026-11-11T08:57:00Z", "waiting", json!(r.tables))], now(), label, &lines()).unwrap().ask.groups.iter().map(|g| g.id.clone()).collect();    let picked = chosen_tables(&r, Some(&every_group)).unwrap();    assert!(!picked.contains(&"assistant_read".to_string()), "a hidden table goes only with Everything");    assert_eq!(picked.len(), all.len() - 1);    assert_eq!(chosen_tables(&r, Some(&[])).unwrap_err().code(), "bad_tables");    assert_eq!(chosen_tables(&r, Some(&["health".into()])).unwrap_err().code(), "bad_tables", "a group the card did not offer");    // What Allow then grants is exactly that set.    assert_eq!(allowed(&r, now(), Some(&chosen_tables(&r, Some(&["mail".into()])).unwrap()), None), Ok((vec!["email".to_string(), "email_thread".into()], 15)));}/// RULE: Settings › Your Claude in an app whose kit names no groups (Words, Days, Story) chooses by the core's groups:/// each sealed table in its group, one no group names in Everything else, the system's own left out, each worded.#[test]fn your_claude_chooses_by_the_cores_groups_where_the_kit_names_none() {    let sealed: Vec<String> = ["note", "event", "todo", "photo", "dev_job", "assistant_read", "sealed_diary"].map(String::from).to_vec();    let groups = groups_of(&sealed);    assert_eq!(groups, vec![("notes".to_string(), vec!["note".to_string()]), ("calendar".into(), vec!["event".into(), "todo".into()]), ("photos".into(), vec!["photo".into()]), ("other".into(), vec!["sealed_diary".into()])]);    let grant = json!({"id": "g", "account": true, "granted_at": "2026-11-11T08:00:00Z", "tables": sealed, "withheld": [], "ask": [], "off": []});    let shown = super::super::assistants::groups(&[grant.clone()], &groups, &sealed, &lines(), true);    assert_eq!(shown.iter().map(|g| g.label.as_str()).collect::<Vec<_>>(), ["Notes", "Calendar", "Photos", "Everything else"]);    assert!(shown.iter().all(|g| !g.line.is_empty() && g.access == "on"));    // Photos as the card says it, not as Comms words its own Photos ("Sent and received").    let line = |id: &str| lines().say(&format!("card.groups.{id}.line"), &[]).unwrap();    assert_eq!(shown[2].line, line("photos"));    let comms = super::super::assistants::groups(&[grant], &[("photos".to_string(), vec!["photo".to_string()])], &sealed, &lines(), false);    assert_eq!(comms[0].line, lines().say("account.groups.photos.line", &[]).unwrap(), "a kit's own group keeps its own words");}// The iPhone's sample card for its UI checks (apps/cotton …/Fixtures/unlock-card-seed.json, `-unlock-card-seed account|timed`):// the core's own card for two invented requests, so every word the sheet draws is the core's. The account card asks for// forty tables a kit defines, the system's own among them, as the owner's did in Story; the timed one for two groups.// cargo test -p cotton-core --lib write_unlock_card_seed -- --ignored#[test]#[ignore]fn write_unlock_card_seed() {    let tables: Vec<String> = named_tables().into_iter().map(|(_, table)| table.to_string()).take(40).collect();    let mut account = request("seed-account", "2026-11-11T08:57:00Z", "waiting", json!(tables));    account["account"] = json!(1);    account["member_id"] = json!("mem-seed");    account["minutes"] = json!(0);    account["token_name"] = json!("Asha's Claude");    account["expires_at"] = json!("9999-12-31T23:59:59.999Z");    account["reason"] = Value::Null;    let mut timed = request("seed-timed", "2026-11-11T08:58:00Z", "waiting", json!(["note", "message", "event"]));    timed["token_name"] = json!("Asha's Claude");    timed["connected_at"] = json!("2026-11-08T09:00:00Z");    // Let me choose over the groups whose lines run long (Recordings, Photos, Scripts, Contacts): a Scripts row that    // wrapped with room to spare while Photos stood on one line (coordinator, 24 Nov 2026).    let mut groups = request("seed-groups", "2026-11-11T08:59:00Z", "waiting", json!(["note", "event", "message", "meetings_meeting", "photo", "story_scene", "contact"]));    groups["token_name"] = json!("Asha's Claude");    groups["connected_at"] = json!("2026-11-08T09:00:00Z");    let words = lines();    let answer = |row: Value| {        let card = card(&[row.clone()], now(), label, &words).expect("the seed's request is answered");        json!({ "card": card, "pollSeconds": poll_seconds(&[row], now()) })    };    // Three of the person's own Claude Code machines waiting together: the card offers Allow all (f1d096c29d).    let machines = vec![        code_ask("seed-m1", "2026-11-11T08:57:00Z", "seed-lane-one", Some("mac-c")),        code_ask("seed-m2", "2026-11-11T08:58:00Z", "seed-lane-two", Some("mac-d")),        code_ask("seed-m3", "2026-11-11T08:58:30Z", "seed-lane-three", Some("mac-a")),    ];    let several = json!({ "card": card(&machines, now(), label, &words).expect("the seed's requests are answered"), "pollSeconds": poll_seconds(&machines, now()) });    let seed = json!({        "_about": "The core's own unlock.card answers for invented requests (rules/unlock_tests.rs write_unlock_card_seed), drawn by the iPhone's sheet under -unlock-card-seed account|timed|groups|several. Nothing here is anyone's real request.",        "account": answer(account),        "timed": answer(timed),        "groups": answer(groups),        "several": several,    });    let path = cotton_store::manifest_dir().join("../../apps/cotton/Sources/CottonUI/Resources/Fixtures/unlock-card-seed.json");    std::fs::write(&path, serde_json::to_string_pretty(&seed).unwrap() + "\n").expect("the seed is written");}/// A lane's or a pasted token's ask, as the Worker stamps it: `asker: code`, its machine when the mint said one.fn code_ask(id: &str, asked: &str, lane: &str, machine: Option<&str>) -> Value {    let mut row = request(id, asked, "waiting", json!(["note"]));    row["token_name"] = json!(format!("Lane {lane}"));    row["client"] = json!(format!("Lane {lane}"));    row["asker"] = json!("code");    if let Some(machine) = machine {        row["machine"] = json!(machine);    }    row}// RULE: The card names what asks in plain words, never a token's own name (owner, 23 Nov 2026: it said// "Lane …"): a lane or pasted token is Claude Code on its machine, or Claude Code when no machine was said; a// row from before the stamp, named "Lane …", is Claude Code too; an assistant connected by sign-in keeps its name.#[test]fn the_card_names_the_asker_as_claude_code_on_its_machine() {    let c = card(&[code_ask("r1", "2026-11-11T08:58:00Z", "build-ios", Some("mac-c"))], now(), label, &lines()).unwrap();    assert_eq!(c.fields["asker"], "Claude Code on mac-c");    assert!(c.title.contains("Claude Code on mac-c"), "{}", c.title);    assert!(!serde_json::to_string(&c.fields).unwrap().contains("Lane "), "no token name is said");    let c = card(&[code_ask("r1", "2026-11-11T08:58:00Z", "build-ios", None)], now(), label, &lines()).unwrap();    assert_eq!(c.fields["asker"], "Claude Code");    let mut before = code_ask("r1", "2026-11-11T08:58:00Z", "build-android", None);    before.as_object_mut().unwrap().remove("asker");    assert_eq!(card_of(&before)["asker"], "Claude Code");    let mut app = request("r1", "2026-11-11T08:58:00Z", "waiting", json!(["note"]));    app["asker"] = json!("app");    app["token_name"] = json!("Claude (claude.ai)");    assert_eq!(card_of(&app)["asker"], "Claude (claude.ai)");    let mut code_client = app.clone();    code_client["client"] = json!("claude-code");    code_client["token_name"] = json!("claude-code");    assert_eq!(card_of(&code_client)["asker"], "Claude Code");    // The account card's who line says when it connected, in the same words.    let mut account = code_ask("r1", "2026-11-11T08:58:00Z", "x", Some("mac-d"));    account["account"] = json!(true);    account["connected_at"] = json!("2026-11-11T08:00:00Z");    let c = card(&[account], now(), label, &lines()).unwrap();    assert_eq!(c.ask.who, "Claude Code on mac-d · connected 1 hour ago");}fn card_of(row: &Value) -> Value {    serde_json::to_value(card(std::slice::from_ref(row), now(), label, &lines()).unwrap().fields).unwrap()}// RULE: Several of the person's own Claude Code machines waiting together are offered Allow all on the first card// (owner, 23 Nov 2026: three cards came one after another): its ids this card's first, the others named once each by// machine. One alone, the one card for their Claude, and an assistant connected by sign-in are never in it.#[test]fn allow_all_gathers_the_persons_own_machines_that_wait() {    let rows = vec![        code_ask("r1", "2026-11-11T08:57:00Z", "build-ios", Some("mac-c")),        code_ask("r2", "2026-11-11T08:58:00Z", "build-android", Some("ci-box")),        code_ask("r3", "2026-11-11T08:58:30Z", "words", Some("mac-d")),        request("r4", "2026-11-11T08:59:00Z", "waiting", json!(["note"])),    ];    let c = card(&rows, now(), label, &lines()).unwrap();    let all = c.allow_all.expect("three of his machines wait");    assert_eq!(all.label, "Allow all 3");    assert_eq!(all.request_ids, vec!["r1", "r2", "r3"]);    assert_eq!(all.line, "Also waiting: Claude Code on ci-box and Claude Code on mac-d");    assert_eq!(allow_all_ids(&rows, now(), &["r3".into(), "r4".into(), "r1".into()]).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), vec!["r3", "r1"]);    let same = vec![code_ask("r1", "2026-11-11T08:57:00Z", "a", Some("mac-d")), code_ask("r2", "2026-11-11T08:58:00Z", "b", Some("mac-d"))];    assert_eq!(card(&same, now(), label, &lines()).unwrap().allow_all.unwrap().line, "All 2 come from Claude Code on mac-d.");    assert!(card(&rows[..1], now(), label, &lines()).unwrap().allow_all.is_none(), "one alone is just Allow");    let app_first = vec![rows[3].clone(), rows[0].clone(), rows[1].clone()];    let mut app_first = app_first;    app_first[0]["requested_at"] = json!("2026-11-11T08:50:00Z");    assert!(card(&app_first, now(), label, &lines()).unwrap().allow_all.is_none(), "a sign-in assistant's card answers alone");}/// RULE (Cotton Sites, question 14): Sites' list is never granted, not with Everything, not by name, not to a standing/// grant, whatever an assistant asked for; an ask for it alone grants nothing.#[test]fn sites_list_is_never_granted() {    let asked = json!(["note", "site", "email"]);    let r = request_of(&request("r1", "2026-11-11T08:57:00Z", "waiting", asked)).unwrap();    assert_eq!(chosen_tables(&r, None), Ok(vec!["email".to_string(), "note".into()]), "Everything leaves it out");    assert_eq!(allowed(&r, now(), None, None).unwrap().0, vec!["email".to_string(), "note".into()]);    assert_eq!(allowed(&r, now(), Some(&["site".to_string(), "note".into()]), None).unwrap().0, vec!["note".to_string()]);    let only = request_of(&request("r2", "2026-11-11T08:57:00Z", "waiting", json!(["site"]))).unwrap();    assert_eq!(allowed(&only, now(), None, None).unwrap_err().code(), "bad_tables");    let grant = json!({ "withheld": [], "off": [], "ask": [] });    assert!(crate::rules::assistants::to_hand(&grant, &["site".to_string(), "note".into()], &[], |_| 1).iter().all(|(t, _)| t != "site"));}