//! RULE (the transforms contract, 22 Oct 2026): every sentence a person reads //! is a LINE — a row of the `lines` table from `kits/shell/lines/.json`, //! resolved database-first — never a literal in the core's transforms, rules, records or //! definitions. A transform returns a typed form and the reading edge says it //! with the database's lines, so a rewording is a row and never a build; a //! sentence typed into Rust is one the owner cannot reword and an assistant //! cannot translate. //! //! The scan reads `cotton-core/src/{transforms,rules,records,definitions}` and //! `cotton-rules/src` (the pure rules the Worker runs as WASM) as text — no //! compile, test files and `#[cfg(test)]` items cut out — and flags a string //! literal that reads like a sentence: twelve characters or more with a //! space before a lowercase word, and not SQL, XML markup, a line key, a path, a format //! of only placeholders, or a message only a developer reads (`expect`, //! `panic!`, `assert!`, a log macro). Every hit standing today is in //! `sentence_literals_allowed.txt` next to this file with why it stays — an //! AI prompt, a refusal not yet moved to set `refusal`, a stored marker //! a database already holds — and a new one fails here: say it as a line, or //! add it to the list with its reason. //! //! The list may only shrink (architect's ruling, 22 Oct 2026). An entry //! nothing matches any more FAILS, as the line-keys guard does: a sentence //! worked off into a line would otherwise stay allowed and come back //! unnoticed. And [`ALLOWED_CEILING`] is a ratchet: more entries than it fails. //! A push that moves entries into lines lowers the ceiling to the new count //! in the same commit. A lane that adds a sentence a person reads adds a line, //! never an entry; the ceiling rises only with a reason in the commit message //! that names the architect's ruling allowing it. mod rust_text; use rust_text::{source_files, tokens, workspace, Tok, Token}; /// The core's transforms, rules, records and definitions (`engine/` until T10 /// split it, 22 Oct 2026). A folder that vanishes fails the scan rather than /// leaving it reading nothing. /// How many entries `sentence_literals_allowed.txt` may hold — lowered by /// every push that works entries off, raised only by an architect's ruling /// named in the commit message (the module comment says why). const ALLOWED_CEILING: usize = 123; const DIRS: [&str; 5] = [ "crates/cotton-core/src/transforms", "crates/cotton-core/src/rules", "crates/cotton-core/src/records", "crates/cotton-core/src/definitions", // The pure rules the phone core re-exports and the Worker runs as WASM: a // sentence here reaches a person through MCP answers and refusals too. "crates/cotton-rules/src", ]; /// Calls and macros whose string is read by a developer, never a person. const DEVELOPER_ONLY: [&str; 18] = [ "expect", "expect_err", "panic", "unreachable", "todo", "unimplemented", "assert", "assert_eq", "assert_ne", "debug_assert", "debug_assert_eq", "debug_assert_ne", "trace", "debug", "info", "warn", "error", "eprintln", ]; const SQL: [&str; 12] = ["SELECT ", "INSERT ", "UPDATE ", "DELETE ", "CREATE ", "WITH ", "ALTER ", "DROP ", "PRAGMA ", "REPLACE ", "BEGIN", "ATTACH "]; /// Whether `text` reads like a sentence a person would read. fn sentence_like(text: &str) -> bool { let joined = unbroken(text); let text = joined.trim(); if text.chars().count() < 12 { return false; } let upper = text.to_ascii_uppercase(); if SQL.iter().any(|sql| upper.starts_with(sql)) || upper.contains(" FROM ") || upper.contains(" WHERE ") || sql_fragment(text) { return false; } if !text.contains(' ') && (text.contains('/') || text.contains('.') || text.contains("::")) { return false; } // Markup: an XML template (`` as the source // spells it) is a file format, not a sentence. if text.starts_with(" depth += 1, '}' => depth -= 1, _ if depth == 0 => bare.push(c), _ => {} } } let words: Vec<&str> = bare.split_whitespace().collect(); // A space before a lowercase word. words.iter().skip(1).any(|word| word.chars().next().is_some_and(|c| c.is_lowercase()) && word.chars().filter(|c| c.is_alphabetic()).count() >= 2) && words.iter().filter(|word| word.chars().any(char::is_alphabetic)).count() >= 2 } /// The literal with each `\` line continuation joined as Rust joins it. fn unbroken(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; while let Some(at) = rest.find("\\\n") { out.push_str(&rest[..at]); rest = rest[at + 2..].trim_start(); } out.push_str(rest); out } /// Upper-case SQL words a fragment of a query is made of (`JOIN t ON t.id = /// x.id`, `t.name AS title`); a sentence uses at most one, and with no /// `table.column` or `=` beside it. const SQL_WORDS: [&str; 30] = [ "JOIN", "ON", "AS", "AND", "OR", "NOT", "NULL", "IS", "IN", "ORDER", "BY", "GROUP", "LIMIT", "OFFSET", "SET", "VALUES", "LEFT", "INNER", "COALESCE", "CASE", "WHEN", "THEN", "END", "ELSE", "EXISTS", "DISTINCT", "ASC", "DESC", "LIKE", "UNION", ]; fn sql_fragment(text: &str) -> bool { let words = text .split(|c: char| !c.is_ascii_alphanumeric() && c != '_') .filter(|word| SQL_WORDS.contains(word)) .count(); let bytes = text.as_bytes(); let dotted = bytes.windows(3).any(|w| w[0].is_ascii_alphabetic() && w[1] == b'.' && w[2].is_ascii_alphabetic()); words >= 2 || text.contains("||") || (words == 1 && (dotted || text.contains('=') || text.contains('?') || text.contains(") AS "))) } /// The name of the call or macro each string literal is an argument of. fn callers<'a>(tokens: &[Token<'a>]) -> Vec> { let mut stack: Vec> = Vec::new(); let mut out = Vec::with_capacity(tokens.len()); for (i, token) in tokens.iter().enumerate() { match token.tok { Tok::Punct(b'(' | b'[' | b'{') => { let before = |k: usize| i.checked_sub(k).map(|k| tokens[k].tok); let name = match (before(1), before(2)) { (Some(Tok::Ident(name)), _) => Some(name), (Some(Tok::Punct(b'!')), Some(Tok::Ident(name))) => Some(name), _ => None, }; // A macro's braces/brackets count as its call; a plain block // keeps the enclosing call (a closure body in `.map_err(..)`). let inherited = if token.tok == Tok::Punct(b'{') && name.is_none() { stack.last().copied().flatten() } else { None }; stack.push(name.or(inherited)); } Tok::Punct(b')' | b']' | b'}') => { stack.pop(); } _ => {} } out.push(stack.last().copied().flatten()); } out } /// `sentence_literals_allowed.txt`: `path "literal or prefix" — reason`. fn allowed() -> Vec<(String, String, String)> { let text = std::fs::read_to_string(cotton_store::manifest_dir().join("tests/sentence_literals_allowed.txt")) .expect("tests/sentence_literals_allowed.txt"); text.lines() .map(str::trim) .filter(|line| !line.is_empty() && !line.starts_with('#')) .map(|line| { let (path, rest) = line.split_once(" \"").unwrap_or_else(|| panic!("`{line}` is not `path \"literal\" — reason`")); let (literal, reason) = rest.rsplit_once("\" — ").unwrap_or_else(|| panic!("`{line}` names no reason after `\" — `")); assert!(!reason.trim().is_empty(), "`{line}` names no reason"); (path.to_string(), literal.to_string(), reason.to_string()) }) .collect() } #[test] fn no_sentence_is_a_literal_in_the_cores_transforms_rules_records_or_definitions() { let started = std::time::Instant::now(); let root = workspace(); let allowed = allowed(); let mut used = vec![false; allowed.len()]; let mut hits = Vec::new(); for dir in DIRS { let dir = root.join(dir); let files = source_files(&dir); assert!(files.len() > 3, "{} holds {} source files — a moved folder belongs in DIRS", dir.display(), files.len()); for path in files { let source = std::fs::read_to_string(&path).unwrap(); let tokens = tokens(&source); let callers = callers(&tokens); let at = path.strip_prefix(&root).unwrap_or(&path).display().to_string(); for (token, caller) in tokens.iter().zip(&callers) { let Tok::Str(text) = token.tok else { continue }; if caller.is_some_and(|name| DEVELOPER_ONLY.contains(&name)) || !sentence_like(text) { continue; } let mut listed = false; for (index, (file, literal, _)) in allowed.iter().enumerate() { if *file == at && text.starts_with(literal.as_str()) { used[index] = true; listed = true; } } if !listed { hits.push(format!("{at}:{} \"{text}\"", token.line)); } } } } let took = started.elapsed(); assert!( hits.is_empty(), "{} sentence-like literals ({took:?}) — say each as a line, or allow-list it with its reason:\n{}", hits.len(), hits.join("\n") ); let stale: Vec = allowed .iter() .zip(&used) .filter(|(_, used)| !**used) .map(|((path, literal, _), _)| format!("{path} \"{literal}\"")) .collect(); assert!( stale.is_empty(), "sentence_literals_allowed.txt entries nothing matches any more — delete them and lower ALLOWED_CEILING:\n{}", stale.join("\n") ); assert!( allowed.len() <= ALLOWED_CEILING, "sentence_literals_allowed.txt holds {} entries and the ceiling is {ALLOWED_CEILING} — say the new sentence as a line; \ the ceiling rises only by an architect's ruling named in the commit", allowed.len() ); }