Cotton code
186 lines · 7.9 KB · RustRaw
//! RULE (owner, 21 Nov 2026): every word a Cotton app puts on a screen is a//! word a person already knows from other apps, and says what happens to//! their data, never to our system. No kit line and no act label may say//! "rows", "object", "business", "replica", "seal_…", "sealed",//! "definition", "outbox", "tombstone", "kit", "workspace", "unlocked", or//! call syncing "backing up".//!//! Scanned: every string of every line set (`kits/shell/lines/*.json`) and//! every act's label, confirm and receipt in the kits and the personal//! tools' manifests, with `{placeholders}` taken out first (a placeholder's//! name never reaches a screen).//!//! Not scanned, each for a stated reason://! - [`MAC_AND_DEVELOPER_SETS`]: line sets only the Mac app, the developer//!   tools or CI say, which name machines and repositories for their own//!   people (the brief: every phone app, Books to Comms);//! - [`ASSISTANT_AND_AUTHOR_PATHS`]: refusals an assistant or a definition's//!   author reads (a definition is invalid; an MCP argument is not an//!   object), never a person on a phone;//! - [`ALLOWED`]: a line whose word is the person's own thing (a table's row//!   inside their note, the text cursor, the phone's own screen lock).use std::path::{Path, PathBuf};use serde_json::Value;/// The words that may never reach a screen, matched whole, any case.const BANNED: &[&str] = &[    "row", "rows", "object", "objects", "business", "businesses", "replica", "replicas", "sealed", "definition",    "definitions", "outbox", "tombstone", "tombstones", "kit", "kits", "workspace", "workspaces", "unlocked", "backup",    "backups", "back up", "backing up", "backed up", "cursor",];/// Matched as a prefix: an internal name (`seal_key`).const BANNED_PREFIXES: &[&str] = &["seal_"];const MAC_AND_DEVELOPER_SETS: &[&str] = &["host", "developer", "ci", "code", "dispatch", "machines", "diagnostics", "definitions", "chrome"];const ASSISTANT_AND_AUTHOR_PATHS: &[&str] = &[    "refusal.definition.",    "refusal.card.",    "refusal.records.",    "refusal.runner.",    "refusal.questions.",    "refusal.memory.",    "refusal.recurrence.",    "refusal.send.shape.",    // The briefing an assistant reads over MCP (the Worker says it).    "unlock.brief.",    // The Mac's own board lines: its off-Mac backup disk.    "board.backup.",];const ALLOWED: &[(&str, &str)] = &[    ("notes.format.table_row_add", "a row of the person's own table in a note"),    ("notes.format.table_row_remove", "a row of the person's own table in a note"),    ("notes.type.hide_marks_hint", "the text cursor"),    ("refusal.keychain_locked.body.phone", "the phone's own screen lock"),    ("refusal.keychain_locked.body.mac", "the Mac's own screen lock"),];fn kits() -> PathBuf {    cotton_store::manifest_dir().join("kits")}/// `text` with every `{placeholder}` taken out.fn unfilled(text: &str) -> String {    let mut out = String::with_capacity(text.len());    let mut depth = 0;    for c in text.chars() {        match c {            '{' => depth += 1,            '}' if depth > 0 => depth -= 1,            _ if depth == 0 => out.push(c),            _ => {}        }    }    out}/// The banned word `text` says, if any.fn says_banned(text: &str) -> Option<&'static str> {    let text = unfilled(text).to_lowercase();    let words: Vec<&str> = text.split(|c: char| !(c.is_alphanumeric() || c == '_')).filter(|w| !w.is_empty()).collect();    for banned in BANNED {        let parts: Vec<&str> = banned.split(' ').collect();        if words.windows(parts.len()).any(|window| window == parts.as_slice()) {            return Some(banned);        }    }    BANNED_PREFIXES.iter().copied().find(|prefix| words.iter().any(|word| word.starts_with(prefix)))}fn walk(value: &Value, path: &str, out: &mut Vec<(String, String)>) {    match value {        Value::String(text) => out.push((path.to_string(), text.clone())),        Value::Object(fields) => {            for (key, field) in fields {                if path.is_empty() && (key == "id" || key == "format_version") {                    continue;                }                walk(field, &if path.is_empty() { key.clone() } else { format!("{path}.{key}") }, out);            }        }        Value::Array(items) => items.iter().enumerate().for_each(|(at, item)| walk(item, &format!("{path}[{at}]"), out)),        _ => {}    }}fn read(path: &Path) -> Value {    serde_json::from_slice(&std::fs::read(path).expect("the file reads")).expect("the file is JSON")}/// Every line a screen may say: `(where, words)`.fn screen_lines() -> Vec<(String, String)> {    let mut lines = Vec::new();    let mut sets: Vec<PathBuf> = std::fs::read_dir(kits().join("shell/lines")).expect("the line sets").map(|entry| entry.expect("an entry").path()).collect();    sets.sort();    for set in sets.iter().filter(|path| path.extension().is_some_and(|ext| ext == "json")) {        let name = set.file_stem().and_then(|stem| stem.to_str()).expect("a set's name").to_string();        if MAC_AND_DEVELOPER_SETS.contains(&name.as_str()) {            continue;        }        let mut found = Vec::new();        walk(&read(set), "", &mut found);        lines.extend(found.into_iter().map(|(path, text)| (format!("{name}.{path}"), text)));    }    // Each act's words, in every kit and every personal tool.    let mut definitions: Vec<PathBuf> = Vec::new();    for entry in std::fs::read_dir(kits()).expect("the kits") {        let kit = entry.expect("a kit").path().join("kit.json");        if kit.exists() {            definitions.push(kit);        }    }    for entry in std::fs::read_dir(kits().join("personal/tools")).expect("the tools") {        let manifest = entry.expect("a tool").path().join("manifest.json");        if manifest.exists() {            definitions.push(manifest);        }    }    definitions.sort();    for definition in definitions {        let value = read(&definition);        let named = definition.strip_prefix(kits()).unwrap_or(&definition).display().to_string();        for (at, act) in value["acts"].as_array().into_iter().flatten().enumerate() {            for field in ["label", "confirm", "receipt"] {                if let Some(text) = act[field].as_str() {                    lines.push((format!("{named} acts[{at}].{field}"), text.to_string()));                }            }        }        if let Some(line) = value["server"]["line"].as_str() {            lines.push((format!("{named} server.line"), line.to_string()));        }    }    lines}#[test]fn no_screen_line_says_an_internal_word() {    let offending: Vec<String> = screen_lines()        .into_iter()        .filter(|(path, _)| !ASSISTANT_AND_AUTHOR_PATHS.iter().any(|prefix| path.starts_with(prefix)))        .filter(|(path, _)| !ALLOWED.iter().any(|(allowed, _)| path == allowed))        .filter_map(|(path, text)| says_banned(&text).map(|word| format!("{path} says “{word}”: {text}")))        .collect();    assert!(offending.is_empty(), "lines a person would read that say our system's words, not theirs:\n{}", offending.join("\n"));}#[test]fn the_guard_catches_what_it_bans() {    assert_eq!(says_banned("Backing up… 3 of 9 rows"), Some("rows"));    assert_eq!(says_banned("Back up now"), Some("back up"));    assert_eq!(says_banned("waits for seal_key"), Some("seal_"));    assert_eq!(says_banned("Your vault is sealed"), Some("sealed"));    assert_eq!(says_banned("Cotton {kit} {date}"), None, "a placeholder's name is not said");    assert_eq!(says_banned("Sync now"), None);    assert_eq!(says_banned("Arrowsmith"), None, "a word that only holds a banned one is not it");}#[test]fn every_allowance_still_names_a_line() {    let paths: Vec<String> = screen_lines().into_iter().map(|(path, _)| path).collect();    for (allowed, why) in ALLOWED {        assert!(paths.iter().any(|path| path == allowed), "{allowed} is allowed ({why}) but no line is there any more");    }}