479 lines · 21.0 KB · RustRaw
//! RULE (the transforms contract, 22 Oct 2026): every line key the code asks//! for exists in its set's kit file. A key the kit does not ship resolves to//! nothing — the reading edge says an empty string or the key's own path//! (`ci.say`, `dispatch.say` fall back to `"{set}.{line}"`) — so a typo or a//! line removed from `kits/shell/lines/<set>.json` would show a person a blank//! or a dotted path, and only on the screen that reads it. Nothing else//! catches that: the call compiles, the kit parses, and a database's rows//! never add a fixed line the kit lacks (`shell_lines::resolved` ignores it).//!//! The scan reads cotton-core, cotton-tools, cotton-ffi, cotton-server and cotton-rules'//! source as text (no compile, test items cut out) and takes every literal//! key handed to `shell_lines::resolve(set, "key", ..)`, to `.say("key", ..)`//! on a line set, and to a file's own wrapper around either (`say(lines,//! "key", ..)`, a `let line = |path, fills| resolve(..)` closure). A key built//! at run time (`&format!("untitled.{kind}")`) is not a literal and is the//! caller's to test.//!//! The Swift side too (architect, 22 Oct 2026): `ShellLines.line` says a//! missing line as its raw `set.path`, and "cards.note.continued" reached the//! screen that way. Every literal key in `ShellLines.line(set, "key")` and//! `ShellLines.onThisHost(set, "key")` (which reads `key.phone` and `key.mac`)//! under apps/cotton/Sources must be in the kit, read as text with no Swift//! build. A key that may stay missing for a while is listed in//! `line_keys_allowed.txt` next to this file, one `path set.key — reason`//! per line; an entry nothing asks for any more fails, so the list only//! shrinks.mod rust_text;use rust_text::{calls, definitions, source_files, tokens, workspace, Call, Definition, Tok, Token};use serde_json::Value;use std::collections::{BTreeMap, BTreeSet};use std::path::PathBuf;const CRATES: [&str; 5] = ["cotton-core", "cotton-tools", "cotton-ffi", "cotton-server", "cotton-rules"];/// Every kit line set by id, parsed.fn kit_sets() -> BTreeMap<String, Value> { let dir = workspace().join("crates/cotton-core/kits/shell/lines"); let mut sets = BTreeMap::new(); for entry in std::fs::read_dir(&dir).expect("the kit's line directory") { let path = entry.unwrap().path(); if path.extension().is_some_and(|ext| ext == "json") { let id = path.file_stem().unwrap().to_string_lossy().to_string(); let file = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).expect("a kit line file parses"); sets.insert(id, file); } } sets}/// A dotted line key: lowercase words joined by dots (a map key such as a/// currency code may be upper case).fn looks_like_key(text: &str) -> bool { !text.is_empty() && text.split('.').all(|part| { !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') }) && text.chars().next().is_some_and(|c| c.is_ascii_lowercase())}fn has_line(set: &Value, key: &str) -> bool { matches!(set.pointer(&format!("/{}", key.replace('.', "/"))), Some(Value::String(_) | Value::Object(_)))}struct File<'a> { path: &'a PathBuf, stem: String, tokens: &'a [Token<'a>], calls: Vec<Call<'a>>, definitions: Vec<Definition<'a>>,}/// What a sayer call resolves against.#[derive(Clone, Debug)]enum Sets { /// One named set. Named(String), /// The sets the file itself names (any set when it names none). OfFile,}/// A function or closure that hands its `index`th parameter to a resolve as/// the key.#[derive(Clone, Debug)]struct Wrapper { index: usize, sets: Sets,}fn is_resolve(call: &Call) -> bool { // `shell_lines::resolve(set, key, ..)`, and cotton-rules' `lines::resolve(set, key, fills)`. call.name == "resolve" && !call.method && call.path.last().is_some_and(|segment| matches!(*segment, "shell_lines" | "lines")) || call.name == "resolve" && !call.method && call.path.is_empty() && call.args.len() == 4}fn is_line_set(call: &Call) -> bool { matches!(call.name, "of_rows" | "shipped") && call.path.last().is_some_and(|segment| *segment == "LineSet")}#[test]fn every_line_key_the_code_asks_for_is_in_its_kit_set() { let started = std::time::Instant::now(); let root = workspace(); let kit = kit_sets(); let paths: Vec<PathBuf> = CRATES.iter().flat_map(|krate| source_files(&root.join("crates").join(krate).join("src"))).collect(); let sources: Vec<String> = paths.iter().map(|path| std::fs::read_to_string(path).unwrap()).collect(); let tokens: Vec<Vec<Token>> = sources.iter().map(|source| tokens(source)).collect(); let files: Vec<File> = paths .iter() .zip(&tokens) .map(|(path, tokens)| File { path, stem: path.file_stem().unwrap().to_string_lossy().to_string(), tokens, calls: calls(tokens), definitions: definitions(tokens), }) .collect(); // `pub const LINES: &str = "<set>"`, by file stem. let mut consts: BTreeMap<String, String> = BTreeMap::new(); for file in &files { for w in file.tokens.windows(7) { if let (Tok::Ident("const"), Tok::Ident("LINES"), Tok::Punct(b'='), Tok::Str(set)) = (w[0].tok, w[1].tok, w[5].tok, w[6].tok) { { consts.insert(file.stem.clone(), set.to_string()); } } } } let set_of = |file: &File, call: &Call| -> Option<String> { if let Some(set) = call.literal(0) { return Some(set.to_string()); } let path = call.path_arg(0)?; if *path.last()? != "LINES" { return None; } let stem = if path.len() == 1 { file.stem.as_str() } else { path[path.len() - 2] }; consts.get(stem).cloned() }; // A helper returning a LineSet names that set at its call sites too. // For example, card_words constructs "cards" outside records.rs; a // separate "format" set in records.rs must not hide its cards keys. let mut providers: BTreeMap<(String, String), BTreeSet<String>> = BTreeMap::new(); for file in &files { for call in file.calls.iter().filter(|call| is_line_set(call)) { let Some(set) = set_of(file, call) else { continue }; let Some(definition) = file.definitions.iter().rev().find(|definition| definition.at < call.at) else { continue }; let signature: Vec<_> = file.tokens[definition.at..call.at].iter() .take_while(|token| token.tok != Tok::Punct(b'{')).collect(); if signature.windows(3).any(|tokens| matches!( (tokens[0].tok, tokens[1].tok, tokens[2].tok), (Tok::Punct(b'-'), Tok::Punct(b'>'), Tok::Ident("LineSet")) )) { providers.entry((file.stem.clone(), definition.name.to_string())).or_default().insert(set); } } } // The sets each file names, and its wrappers. let mut named: BTreeMap<&PathBuf, BTreeSet<String>> = BTreeMap::new(); let mut wrappers: BTreeMap<(String, String), Wrapper> = BTreeMap::new(); for file in &files { let mine = named.entry(file.path).or_default(); for call in &file.calls { let owner = call.path.last().copied().unwrap_or(&file.stem); if let Some(sets) = providers.get(&(owner.to_string(), call.name.to_string())) { mine.extend(sets.iter().cloned()); } if is_resolve(call) || is_line_set(call) { if let Some(set) = set_of(file, call) { mine.insert(set); } } } for call in &file.calls { let (key_index, sets) = if is_resolve(call) { (1, set_of(file, call).map(Sets::Named)) } else if call.method && call.name == "say" { (0, Some(Sets::OfFile)) } else { continue; }; let Some(param) = call.name_arg(key_index) else { continue }; let Some(sets) = sets else { continue }; let Some(definition) = file.definitions.iter().rev().find(|d| d.at < call.at && d.params.contains(¶m)) else { continue; }; let index = definition.params.iter().position(|p| *p == param).unwrap(); wrappers.insert((file.stem.clone(), definition.name.to_string()), Wrapper { index, sets }); } } let mut asked = 0; let mut missing = Vec::new(); for file in &files { let file_sets = &named[file.path]; for call in &file.calls { let (key, sets) = if is_resolve(call) { let Some(key) = call.literal(1) else { continue }; (key, set_of(file, call).map(Sets::Named)) } else if call.method && call.name == "say" && !wrappers.contains_key(&(file.stem.clone(), "say".into())) { let Some(key) = call.literal(0) else { continue }; (key, Some(Sets::OfFile)) } else { let owner = if call.path.is_empty() || call.path == ["self"] || call.path == ["Self"] { file.stem.clone() } else { call.path.last().unwrap().to_string() }; let Some(wrapper) = wrappers.get(&(owner, call.name.to_string())) else { continue }; let Some(key) = call.literal(wrapper.index) else { continue }; (key, Some(wrapper.sets.clone())) }; if !looks_like_key(key) { continue; } let candidates: Vec<String> = match sets { Some(Sets::Named(set)) => vec![set], _ if !file_sets.is_empty() => file_sets.iter().cloned().collect(), _ => kit.keys().cloned().collect(), }; asked += 1; let found = candidates.iter().any(|set| kit.get(set).is_some_and(|file| has_line(file, key))); if !found { let at = file.path.strip_prefix(&root).unwrap_or(file.path).display().to_string(); let said = candidates.iter().map(|set| set.as_str()).collect::<Vec<_>>().join("|"); missing.push(format!("{at}:{} asks for {said}.{key}", call.line)); } } } let took = started.elapsed(); assert!(asked > 100, "the scan found only {asked} keys — it has stopped seeing the calls"); assert!(missing.is_empty(), "line keys no kit set ships ({asked} asked, {took:?}):\n{}", missing.join("\n"));}/// `line_keys_allowed.txt`: `(path, set.key) -> reason`.fn allowed() -> BTreeMap<(String, String), String> { let text = std::fs::read_to_string(cotton_store::manifest_dir().join("tests/line_keys_allowed.txt")) .expect("tests/line_keys_allowed.txt"); let mut allowed = BTreeMap::new(); for line in text.lines().map(str::trim).filter(|line| !line.is_empty() && !line.starts_with('#')) { let (entry, reason) = line.split_once(" — ").unwrap_or_else(|| panic!("`{line}` names no reason after ` — `")); let (path, key) = entry.trim().split_once(' ').unwrap_or_else(|| panic!("`{line}` is not `path set.key — reason`")); assert!(!reason.trim().is_empty(), "`{line}` names no reason"); allowed.insert((path.to_string(), key.trim().to_string()), reason.to_string()); } allowed}fn swift_files(dir: &std::path::Path, files: &mut Vec<PathBuf>) { let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { swift_files(&path, files); } else if path.extension().is_some_and(|ext| ext == "swift") { files.push(path); } }}/// The `cards` keys the Android shell asks by literal (`lines.line("cards",/// "faces.total")`): a face drawn only on Android reads its words there.fn kotlin_asked_cards() -> BTreeSet<String> { fn kotlin_files(dir: &std::path::Path, files: &mut Vec<PathBuf>) { let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { kotlin_files(&path, files); } else if path.extension().is_some_and(|ext| ext == "kt") { files.push(path); } } } let mut files = Vec::new(); kotlin_files(&workspace().join("apps/android"), &mut files); let call = ".line(\"cards\", \""; let mut asked = BTreeSet::new(); for path in files { let source = std::fs::read_to_string(&path).unwrap(); for line in source.lines().filter(|line| !line.trim_start().starts_with("//")) { for (start, _) in line.match_indices(call) { let rest = &line[start + call.len()..]; if let Some(end) = rest.find('"') { asked.insert(rest[..end].to_string()); } } } } asked}/// The string literals of one Swift argument made only of literals, names/// and a ternary (`shown ? "a" : "b"`); `None` for anything built/// (interpolation, `+`, a call).fn swift_literals(arg: &str) -> Option<Vec<&str>> { let mut out = Vec::new(); let mut rest = arg.trim(); while !rest.is_empty() { if let Some(after) = rest.strip_prefix('"') { let end = after.find('"')?; let text = &after[..end]; if text.contains('\\') { return None; } out.push(text); rest = after[end + 1..].trim_start(); } else { let end = rest.find('"').unwrap_or(rest.len()); let between = &rest[..end]; if !between.chars().all(|c| c.is_alphanumeric() || " ?:._!".contains(c)) { return None; } rest = &rest[end..]; } } Some(out)}/// One literal key a Swift call asks for: where, and `set.key`.struct Asked { at: String, line: usize, set: String, key: String,}/// Every literal key `ShellLines.line(set, "key")` and/// `ShellLines.onThisHost(set, "key")` (which reads `key.phone` and/// `key.mac`) ask for in the apps' Swift — the app and the faces package.fn swift_asked() -> Vec<Asked> { let root = workspace(); let mut files = Vec::new(); for dir in ["apps/cotton/Sources", "apps/loom/Sources"] { swift_files(&root.join(dir), &mut files); } files.sort(); let mut asked = Vec::new(); for path in &files { let source = std::fs::read_to_string(path).unwrap(); let at = path.strip_prefix(&root).unwrap_or(path).display().to_string(); for (number, line) in source.lines().enumerate() { if line.trim_start().starts_with("//") { continue; } for (call, host) in [("ShellLines.line(", false), ("ShellLines.onThisHost(", true)] { for (start, _) in line.match_indices(call) { let args = &line[start + call.len()..]; // `"set", <key>` then `,` or `)` at depth zero. let Some(after) = args.strip_prefix('"') else { continue }; let Some(end) = after.find('"') else { continue }; let set = &after[..end]; let Some(rest) = after[end + 1..].trim_start().strip_prefix(',') else { continue }; let mut depth = 0; let mut quoted = false; let close = rest .char_indices() .find(|&(_, c)| { match c { '"' => quoted = !quoted, '(' | '[' if !quoted => depth += 1, ')' | ']' if !quoted && depth > 0 => depth -= 1, ')' | ',' if !quoted && depth == 0 => return true, _ => {} } false }) .map_or(rest.len(), |(i, _)| i); let Some(keys) = swift_literals(&rest[..close]) else { continue }; for key in keys { let keys = if host { vec![format!("{key}.phone"), format!("{key}.mac")] } else { vec![key.to_string()] }; for key in keys { asked.push(Asked { at: at.clone(), line: number + 1, set: set.to_string(), key }); } } } } } } asked}#[test]fn every_line_key_swift_asks_for_is_in_its_kit_set() { let kit = kit_sets(); let mut allowed = allowed(); let asked = swift_asked(); let mut missing = Vec::new(); for Asked { at, line, set, key } in &asked { if kit.get(set).is_some_and(|file| has_line(file, key)) { continue; } if allowed.remove(&(at.clone(), format!("{set}.{key}"))).is_none() { missing.push(format!("{at}:{line} asks for {set}.{key}")); } } assert!(asked.len() > 100, "the scan found only {} keys — it has stopped seeing the calls", asked.len()); assert!(missing.is_empty(), "line keys Swift asks for that no kit set ships ({} asked):\n{}", asked.len(), missing.join("\n")); let stale: Vec<String> = allowed.keys().map(|(path, key)| format!("{path} {key}")).collect(); assert!(stale.is_empty(), "line_keys_allowed.txt entries nothing asks for any more — delete them:\n{}", stale.join("\n"));}/// The ids of the faces this build draws (`face_ids.json`, the registry's list).fn face_ids() -> Vec<String> { let path = cotton_store::manifest_dir().join("src/definitions/face_ids.json"); serde_json::from_str(&std::fs::read_to_string(path).expect("face_ids.json")).expect("face_ids.json parses")}/// A face's title key under `cards.faces.titles` (`FaceRegistry.title`: dots become underscores).fn title_key(face: &str) -> String { face.replace('.', "_")}/// Every string leaf under `value`, as dotted paths below `prefix`.fn leaves(value: &Value, prefix: &str, out: &mut Vec<String>) { match value { Value::Object(map) => { for (key, inner) in map { leaves(inner, &format!("{prefix}.{key}"), out); } } _ => out.push(prefix.to_string()), }}/// RULE (coordinator, 2 Nov 2026): a line nothing reads is not kept. The/// faces' words (`cards.faces`) are each asked for by a face in Swift or in/// the Android shell's Kotlin by its literal key, and a face's title (`cards.faces.titles.<face>`, which/// `FaceRegistry.title` reads by the face's id) names a face this build draws./// `faces.choice` and `faces.ok` stood here unread.#[test]fn every_face_line_is_read() { let kit = kit_sets(); let faces = &kit["cards"]["faces"]; let mut lines = Vec::new(); leaves(faces, "faces", &mut lines); let mut asked: BTreeSet<String> = swift_asked().into_iter().filter(|asked| asked.set == "cards").map(|asked| asked.key).collect(); asked.extend(kotlin_asked_cards()); let titled: BTreeSet<String> = face_ids().iter().map(|face| format!("faces.titles.{}", title_key(face))).collect(); let unread: Vec<&String> = lines .iter() .filter(|line| if line.starts_with("faces.titles.") { !titled.contains(*line) } else { !asked.contains(*line) }) .collect(); assert!(lines.len() > 20, "the faces group holds only {} lines — the scan has stopped reading it", lines.len()); assert!(unread.is_empty(), "cards lines nothing reads — remove them from kits/shell/lines/cards.json:\n{unread:#?}");}/// RULE (coordinator, 2 Nov 2026): every face a kit table offers (its card's/// `offers`) has a title (`cards.faces.titles`), so the face choice and/// VoiceOver say its name, never its raw id.#[test]fn every_offered_face_has_a_title() { let titles = &kit_sets()["cards"]["faces"]["titles"]; let kits = workspace().join("crates/cotton-core/kits"); let (mut offered, mut carded) = (BTreeSet::new(), 0); for kit in std::fs::read_dir(&kits).unwrap().flatten() { let Ok(tables) = std::fs::read_dir(kit.path().join("tables")) else { continue }; for table in tables.flatten() { let table: Value = serde_json::from_str(&std::fs::read_to_string(table.path()).unwrap()).unwrap(); let card = &table["card"]; carded += usize::from(card.is_object()); for face in card["offers"].as_array().into_iter().flatten().filter_map(Value::as_str) { offered.insert(face.to_string()); } } } assert!(carded > 20, "the kit tables carry only {carded} cards — the scan has stopped reading them"); assert!(offered.len() > 1, "the kit tables offer {} faces — People offers three", offered.len()); let untitled: Vec<&String> = offered.iter().filter(|face| !titles[title_key(face)].is_string()).collect(); assert!(untitled.is_empty(), "faces a kit table offers with no title in cards.faces.titles:\n{untitled:#?}");}