Cotton code
684 lines · 39.1 KB · RustRaw
//! The record page over synthetic rows: every built-in table's page, made by//! the one function with no branch for any kind. Every value is invented.use serde_json::{json, Map, Value};use super::*;use crate::definitions::{builtin_table_definition, builtin_table_definitions, TableDefinition};/// A synthetic record's id; an answer that shows one has shown an internal.const ID_MARK: &str = "id-";/// RULE: Shared-media status words come from the definition's labels; pending and unavailable have a line, while an available video has none and no engine token leaks.#[test]fn shared_media_status_reads_definition_words_only_while_media_is_missing() {    let mut definition = builtin_table_definition("message").unwrap().clone();    let column = definition.columns.iter_mut().find(|column| column.key == "shared_status").unwrap();    column.labels = Some(serde_json::from_value(json!({"pending":"Invented waiting words","unavailable":"Invented unavailable words"})).unwrap());    let column = definition.column("shared_status").unwrap();    for status in ["pending", "unavailable"] {        assert_eq!(super::fact_words(&definition, column, &json!(status), &Map::new(), None, None, crate::records::page::Words::shipped()).as_ref(), column.labels.as_ref().unwrap().get(status));    }    assert_eq!(super::fact_words(&definition, column, &json!("available"), &Map::new(), None, None, crate::records::page::Words::shipped()), None);}/// RULE: A formatted scalar uses the definition's word map before a slip or card sees it; recurrence rules and provider ids must never leak through the core's resolved lines.#[test]fn formatted_text_reads_the_definitions_words() {    let mut definition = builtin_table_definition("event").unwrap().clone();    let column = definition.columns.iter_mut().find(|column| column.key == "rrule").unwrap();    column.labels = Some(serde_json::from_value(json!({"monthly":"Every month", "weekdays":"Every weekday", "custom":"Custom repeat"})).unwrap());    let column = definition.column("rrule").unwrap();    let data = Map::new();    for (raw, expected) in [("FREQ=MONTHLY", "Every month"), ("FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR", "Every weekday"), ("FREQ=MONTHLY;BYDAY=2TU", "Custom repeat")] {        assert_eq!(super::fact_words(&definition, column, &json!(raw), &data, None, None, crate::records::page::Words::shipped()).as_deref(), Some(expected));    }    assert_eq!(super::fact_words(&definition, column, &json!("  "), &data, None, None, crate::records::page::Words::shipped()), None);    let mut column = column.clone();    column.format = Some(crate::definitions::ColumnFormat::AppName);    column.labels = Some(serde_json::from_value(json!({"facetime_video":"FaceTime video"})).unwrap());    assert_eq!(super::fact_words(&definition, &column, &json!("facetime_video"), &data, None, None, crate::records::page::Words::shipped()).as_deref(), Some("FaceTime video"));    assert_eq!(super::fact_words(&definition, &column, &json!("com.unknown.internal"), &data, None, None, crate::records::page::Words::shipped()), None);}/// RULE: Count units may read a row's kind names, but a missing or secret source never becomes display text; counts stay numeric and engines never compose their sentences.#[test]fn count_units_read_safe_typed_kind_names() {    let mut definition = builtin_table_definition("todo").unwrap().clone();    definition.columns.extend([        serde_json::from_value(json!({"key":"count_one", "type":"text", "hidden":true})).unwrap(),        serde_json::from_value(json!({"key":"count_other", "type":"text", "hidden":true})).unwrap(),    ]);    definition.columns.iter_mut().find(|column| column.key == "priority").unwrap().units =        Some(serde_json::from_value(json!({"one":"{count_one}", "other":"{count_other}", "zero":"0 {count_other}"})).unwrap());    let data = json!({"count_one":"marble", "count_other":"marbles"}).as_object().unwrap().clone();    let column = definition.column("priority").unwrap();    for (number, words) in [(0, "0 marbles"), (1, "1 marble"), (3, "3 marbles")] {        assert_eq!(super::fact_words(&definition, column, &json!(number), &data, None, None, crate::records::page::Words::shipped()).as_deref(), Some(words));    }    assert_eq!(super::fact_words(&definition, column, &json!(3), &Map::new(), None, None, crate::records::page::Words::shipped()), None);    definition.validate().expect("declared text sources are safe units");    definition.columns.iter_mut().find(|column| column.key == "count_other").unwrap().secret = Some(true);    assert!(definition.validate().is_err(), "a unit cannot expose a secret column");    assert_eq!(super::fact_words(&definition, definition.column("priority").unwrap(), &json!(3), &data, None, None, crate::records::page::Words::shipped()), None);}/// A value of each column's own type, never a key or an id but a link's.fn synthetic(definition: &TableDefinition) -> Map<String, Value> {    let mut data = Map::new();    for column in &definition.columns {        let one = match column.column_type {            ColumnType::Place => json!("Harbour"),            ColumnType::Text => json!("Harbour lane"),            ColumnType::AccountNumber => json!("12345678901234"),            ColumnType::Longtext => json!("A few lines about it.\nAnd one more."),            ColumnType::Date => json!("2026-10-07"),            ColumnType::Time => json!("09:30"),            ColumnType::Number => json!(3),            ColumnType::Bytes => json!(3_000),            ColumnType::Amount => json!(150_000),            ColumnType::Choice => column                .choices                .as_ref()                .and_then(|choices| choices.first())                .map_or(json!("open"), |first| json!(first)),            ColumnType::Link => json!(format!("{ID_MARK}{}-linked", column.key)),            ColumnType::Photo | ColumnType::File => json!("objects/print.jpg"),            ColumnType::Bool => json!(true),            ColumnType::Url => json!("https://example.org/harbour"),        };        let value = match column.multiple == Some(true) {            true => Value::Array(vec![one]),            false => one,        };        data.insert(column.key.clone(), value);    }    if definition.id == "project" {        data.insert("slug".into(), json!("harbour-lane"));    }    data}/// The built-ins, read as the generic verbs answer them: each record made/// up from its definition, every list twelve long with two rows read.struct Synthetic {    every_record_the_same: bool,    implicit_parts: bool,    /// How many commits `read.repoCommits` answers.    commits: usize,    /// Each read asked, with its arguments.    reads: Vec<(String, Map<String, Value>)>,}impl Synthetic {    fn new(every_record_the_same: bool) -> Self {        Self { every_record_the_same, implicit_parts: false, commits: 12, reads: Vec::new() }    }}impl PageSource for Synthetic {    fn line_rows(&mut self) -> Vec<crate::rules::shell_lines::LineRow> { Vec::new() }    fn definition(&mut self, table: &str) -> Option<TableDefinition> {        builtin_table_definition(table).cloned().map(|mut definition| {            if self.implicit_parts {                // The same facts are drawn through the legacy page, so the                // automatic head can actually select them without explicit parts.                let facts = definition.resolved_parts().head.facts;                definition.parts = None;                definition.page.push(serde_json::from_value(json!({ "columns": facts })).unwrap());            }            definition        })    }    fn record(&mut self, table: &str, _id: &str) -> Result<Map<String, Value>, String> {        let definition = self.definition(table).ok_or("no table")?;        Ok(synthetic(&definition))    }    fn records(&mut self, table: &str, ids: &[String]) -> Result<Vec<(String, Map<String, Value>)>, String> {        let definition = self.definition(table).ok_or("no table")?;        Ok(ids.iter().map(|id| (id.clone(), synthetic(&definition))).collect())    }    fn list(        &mut self,        table: &str,        filter: &Map<String, Value>,        limit: usize,    ) -> Result<(u64, Vec<(String, Map<String, Value>)>), String> {        let definition = self.definition(table).ok_or("no table")?;        let count = if filter.is_empty() || self.every_record_the_same { 12 } else { 5 };        let rows = (0..limit.min(2))            .map(|row| {                let id = format!("{ID_MARK}{table}-{row}");                let data = synthetic(&definition);                (id, data)            })            .collect();        Ok((count, rows))    }    fn active_project_slugs(&mut self) -> Vec<String> {        vec!["slug-a".into(), "slug-b".into()]    }    fn read(&mut self, name: &str, args: &Map<String, Value>) -> Result<Value, String> {        self.reads.push((name.to_string(), args.clone()));        Ok(json!({ "commits": commits(self.commits) }))    }}/// `count` commits as `read.repoCommits` answers them, newest first: each a/// forty-letter hash and a message of a title line and a body.fn commits(count: usize) -> Vec<Value> {    (0..count)        .rev()        .map(|n| json!({ "sha": format!("{n:04x}{}", "c0ffee".repeat(6)), "message": format!("Mend the gate, part {n}\n\nThe hinge had rusted."), "authorName": "Rhea Finch", "authoredAt": "2026-10-07T00:00:00Z" }))        .collect()}/// Every string the page shows.fn shown(page: &RecordPage) -> Vec<String> {    let mut words = vec![page.head.title.clone(), page.head.facts.clone()];    words.extend(page.head.state.iter().map(|state| state.label.clone()));    words.extend(page.links.iter().map(|link| link.title.clone()));    for list in &page.lists {        words.push(list.heading.clone());        for row in &list.rows {            words.push(row.title.clone());            words.extend(row.line.clone());            words.extend(row.act.iter().map(|act| act.label.clone()));        }    }    let acts = page.acts.main.iter().chain(&page.acts.more).chain(&page.acts.away);    words.extend(acts.map(|act| act.label.clone()));    words}/// RULE: Every built-in table answers records.page on a synthetic row through the one function with no branch for any kind, naming only its own commands and showing no id.#[test]fn every_builtin_answers_its_page_on_a_synthetic_row() {    for definition in builtin_table_definitions() {        let id = format!("{ID_MARK}{}", definition.id);        let page = record_page(&mut Synthetic::new(false), &definition.id, &id)            .unwrap_or_else(|error| panic!("{}: {error}", definition.id));        let parts = definition.resolved_parts();        assert_eq!(page.shape, parts.shape, "{}", definition.id);        assert!(!page.head.title.trim().is_empty(), "{}: a page always has a title", definition.id);        for said in shown(&page) {            assert!(!said.contains(ID_MARK), "{}: the page shows an id: {said:?}", definition.id);        }        let acts = page.acts.main.iter().chain(&page.acts.more).chain(&page.acts.away);        for act in acts {            assert!(definition.command(&act.id).is_some(), "{}: {} is not its command", definition.id, act.id);        }        for list in &page.lists {            assert!(list.rows.len() <= LIST_ROWS && list.count >= list.rows.len() as u64, "{}", definition.id);            let opens = match &list.all {                PageListAll::Table { filter, .. } => filter.values().next(),                PageListAll::Read { args, .. } => args.values().next(),            };            // A list matched by value opens on this record's parent value.            let matched = parts.lists.iter().find(|of| of.table == list.table).and_then(|of| of.matching.as_ref());            let wanted = matched.map_or_else(|| json!(id), |by| synthetic(&definition)[&by.parent].clone());            assert_eq!(opens, Some(&wanted), "{}: All opens this record's list", definition.id);        }        for link in &page.links {            assert!(builtin_table_definition(&link.table).is_some(), "{}: a chip opens a table", definition.id);        }    }}#[test]fn a_secret_shows_its_last_four_letters_and_a_date_reads_as_a_day() {    let definition: TableDefinition = serde_json::from_value(json!({        "id": "vault_key", "name": "Key", "plural": "Keys", "picture": null, "builtin": false, "engine": null,        "columns": [            { "key": "name", "type": "text" },            { "key": "token", "type": "text", "secret": true },            { "key": "since", "type": "date" },            { "key": "birthday", "type": "date", "yearly": true }        ],        "title": "name", "date": null, "project": null, "order": null,        "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null },        "tile": { "face": "slip-list" }, "page": [], "instructions": "A key."    }))    .unwrap();    let data = Map::new();    let said = |key: &str, value: Value| fact_words(&definition, definition.column(key).unwrap(), &value, &data, None, None, crate::records::page::Words::shipped());    assert_eq!(said("token", json!("sk-live-9a8bc017")).as_deref(), Some("•••• c017"));    assert_eq!(said("since", json!("2026-10-07T09:30:00.000Z")).as_deref(), Some("7 Oct 2026"));    assert_eq!(said("birthday", json!("--03-21")).as_deref(), Some("21 Mar"));}/// RULE: a page says one database's own words: the Words bundle read from its/// `lines` rows reaches every fact, so a reworded month or currency symbol/// is said on the page, never the kit's (architect, 22 Oct 2026).#[test]fn a_page_fact_says_the_databases_own_date_and_money_words() {    let definition: TableDefinition = serde_json::from_value(json!({        "id": "fee", "name": "Fee", "plural": "Fees", "picture": null, "builtin": false, "engine": null,        "columns": [            { "key": "name", "type": "text" },            { "key": "since", "type": "date" },            { "key": "fee", "type": "amount", "currency": "currency" },            { "key": "currency", "type": "text" },            { "key": "took", "type": "number", "format": "duration" }        ],        "title": "name", "date": null, "project": null, "order": null,        "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null },        "tile": { "face": "slip-list" }, "page": [], "instructions": "A fee."    }))    .unwrap();    let rows = vec![        crate::rules::shell_lines::LineRow { set: "dates".into(), line: "months.oct".into(), words: "Okt".into() },        crate::rules::shell_lines::LineRow { set: "money".into(), line: "symbols.INR".into(), words: "Rs".into() },        crate::rules::shell_lines::LineRow { set: "dates".into(), line: "duration.minutes.other".into(), words: "{n} minutes".into() },    ];    let words = crate::records::page::Words::of_rows(&rows);    let data = json!({ "currency": "INR" }).as_object().unwrap().clone();    let said = |key: &str, value: Value, words| fact_words(&definition, definition.column(key).unwrap(), &value, &data, None, None, words);    assert_eq!(said("since", json!("2026-10-07"), &words).as_deref(), Some("7 Okt 2026"));    assert_eq!(said("since", json!("2026-10-07"), crate::records::page::Words::shipped()).as_deref(), Some("7 Oct 2026"));    let fee = said("fee", json!(150_000), &words).unwrap();    assert!(fee.contains("Rs") && !fee.contains('₹'), "{fee}");    assert_eq!(said("took", json!(300), &words).as_deref(), Some("5 minutes"), "a column's own duration reading");    let timed = json!({ "currency": "INR", "took": 300 }).as_object().unwrap().clone();    let faced = column_words(&definition, &timed, None, None, &words);    assert_eq!(faced["took"], json!("5 minutes"), "a face's duration reading");}/// RULE: A timed date is said in the reader's own zone with its clock time, twelve-hour as every surface says it ("8 Oct 2026, 4:30 pm"); a reading of local midnight is the day alone (a day is enough), and its day is the reader's, never the UTC one.#[test]fn a_timed_date_keeps_its_time_in_the_readers_zone() {    let mut todos = builtin_table_definition("todo").unwrap().clone();    let due = todos.columns.iter_mut().find(|column| column.key == "due_at").unwrap();    due.fact = Some(true); due.reading = Some("{date}".into());    let data = Map::new();    let due = todos.column("due_at").unwrap();    let said = |value: &str, zone| fact_words(&todos, due, &json!(value), &data, zone, None, crate::records::page::Words::shipped());    assert_eq!(said("2026-10-08T14:30:00.000Z", Some("Europe/Berlin")).as_deref(), Some("8 Oct 2026, 4:30 pm"));    assert_eq!(said("2026-10-07T22:00:00.000Z", Some("Europe/Berlin")).as_deref(), Some("8 Oct 2026"), "midnight there: the day alone, the reader's day");    assert_eq!(said("2026-10-08", Some("Europe/Berlin")).as_deref(), Some("8 Oct 2026"), "a plain day stays a day");    assert_eq!(said("2026-10-08T14:30:00.000Z", None).as_deref(), Some("8 Oct 2026"), "no zone known: the day alone, never a UTC clock");}/// RULE: The facts line never repeats a field that has a card: it says only what has none (when it was made, by whom, a count), so every fact has one place and one form on a page (architect, 13 Oct 2026).#[test]fn no_fact_on_the_facts_line_names_a_column_that_has_a_card() {    // A head fact the definition names that is also a card is left to the    // card: the person's organisation and city are cards, so the line says    // the role alone.    let mut people = builtin_table_definition("person").unwrap().clone();    for key in ["role_title", "org", "city"] {        let column = people.columns.iter_mut().find(|column| column.key == key).unwrap();        column.fact = Some(true); column.reading = Some("{value}".into());    }    let Value::Object(row) = json!({ "full_name": "Ada Fenwick", "role_title": "Harbourmaster", "org": "Port Wren", "city": "Wexley" }) else { unreachable!() };    let page = record_page(&mut One { definition: people, data: row }, "person", "id-one").unwrap();    assert_eq!(page.head.facts, "Harbourmaster");    // A todo's due date is its card, and never the facts line's.    let todos = builtin_table_definition("todo").unwrap().clone();    let Value::Object(row) = json!({ "title": "Call back", "status": "open", "due_at": "2026-10-08T14:30:00.000Z" }) else { unreachable!() };    let page = record_page(&mut One { definition: todos, data: row }, "todo", "id-one").unwrap();    assert!(!page.head.facts.contains("8 Oct"), "{:?}", page.head.facts);}#[test]fn a_cap_is_assigned_over_the_set_of_slugs_not_their_order() {    let one = assign_caps(&["harbour".into(), "orchard".into(), "lane".into()]);    let two = assign_caps(&["lane".into(), "harbour".into(), "orchard".into()]);    assert_eq!(one, two);    let caps: std::collections::BTreeSet<_> = one.values().collect();    assert_eq!(caps.len(), 3, "three projects take three enamels");    assert_eq!(paper_of(None), "cream");    assert_eq!(paper_of(Some("navy")), "blue");}/// One record of one definition, alone in its table.struct One {    definition: TableDefinition,    data: Map<String, Value>,}impl PageSource for One {    fn line_rows(&mut self) -> Vec<crate::rules::shell_lines::LineRow> { Vec::new() }    fn definition(&mut self, table: &str) -> Option<TableDefinition> {        (table == self.definition.id).then(|| self.definition.clone())    }    fn record(&mut self, _table: &str, _id: &str) -> Result<Map<String, Value>, String> {        Ok(self.data.clone())    }    fn records(&mut self, _table: &str, _ids: &[String]) -> Result<Vec<(String, Map<String, Value>)>, String> {        Ok(Vec::new())    }    fn list(&mut self, _table: &str, _filter: &Map<String, Value>, _limit: usize) -> Result<(u64, Vec<(String, Map<String, Value>)>), String> {        Ok((1, Vec::new()))    }    fn active_project_slugs(&mut self) -> Vec<String> {        Vec::new()    }    fn read(&mut self, name: &str, _args: &Map<String, Value>) -> Result<Value, String> {        Err(format!("no read.{name} here"))    }}/// RULE: A date column formatted ago is said against the reader's now ("2 min ago", "yesterday") inside its units' template ("read {n}"), a day once it is past 30 days or with no now; a unit naming {n} is the whole phrase, its one said without the number.#[test]fn an_ago_date_is_said_against_now_and_a_unit_can_be_a_phrase() {    let definition: TableDefinition = serde_json::from_value(json!({        "id": "feed", "name": "Feed", "plural": "Feeds", "picture": null, "builtin": false, "engine": null,        "columns": [            { "key": "name", "type": "text" },            { "key": "last_read_at", "type": "date", "format": "ago", "units": { "one": "read {n}", "other": "read {n}" } },            { "key": "seen_at", "type": "date", "format": "ago" },            { "key": "done_before", "type": "number", "units": { "one": "done once before", "other": "done {n} times before", "zero": "" } },            { "key": "words", "type": "number", "units": { "one": "word", "other": "words" } }        ],        "title": "name", "date": null, "project": null, "order": null,        "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null },        "tile": { "face": "slip-list" }, "page": [], "instructions": "A feed."    }))    .unwrap();    definition.validate().expect("units on an ago date are its template");    let data = Map::new();    let now = chrono::DateTime::parse_from_rfc3339("2026-10-07T12:00:00Z").unwrap().with_timezone(&chrono::Utc);    let said = |key: &str, value: Value, now| fact_words(&definition, definition.column(key).unwrap(), &value, &data, None, now, crate::records::page::Words::shipped());    assert_eq!(said("last_read_at", json!("2026-10-07T11:58:00.000Z"), Some(now)).as_deref(), Some("read 2 min ago"));    assert_eq!(said("last_read_at", json!("2026-10-07T11:59:40.000Z"), Some(now)).as_deref(), Some("read just now"));    assert_eq!(said("seen_at", json!("2026-10-07T09:00:00.000Z"), Some(now)).as_deref(), Some("3 h ago"));    assert_eq!(said("seen_at", json!("2026-10-06T08:00:00.000Z"), Some(now)).as_deref(), Some("yesterday"));    assert_eq!(said("seen_at", json!("2026-10-03T12:00:00.000Z"), Some(now)).as_deref(), Some("4 days ago"));    assert_eq!(said("seen_at", json!("2026-08-01T12:00:00.000Z"), Some(now)).as_deref(), Some("1 Aug 2026"));    assert_eq!(said("seen_at", json!("2026-10-07T11:58:00.000Z"), None).as_deref(), Some("7 Oct 2026"), "no now, a day");    assert_eq!(said("done_before", json!(3), None).as_deref(), Some("done 3 times before"));    assert_eq!(said("done_before", json!(1), None).as_deref(), Some("done once before"));    assert_eq!(said("done_before", json!(0), None), None);    assert_eq!(said("words", json!(240), None).as_deref(), Some("240 words"));}/// RULE: A countdown is counted from the reader's now to the instant the/// column holds, never from the moment the reading was taken — the Quotas/// list said "resets in 2h 24m" on a reading taken yesterday, a window that/// had long since reset (295 rough row 44, walker294) — and once the instant/// has passed it says the definition's `units.zero` ("has reset"), never a/// negative or a stale countdown. The words around it are the definition's.#[test]fn a_countdown_runs_from_now_to_its_instant_and_says_the_definitions_word_once_passed() {    let definition: TableDefinition = serde_json::from_value(json!({        "id": "allowance", "name": "Allowance", "plural": "Allowances", "picture": null, "builtin": false, "engine": null,        "columns": [            { "key": "name", "type": "text" },            { "key": "checked_at", "type": "date", "format": "ago" },            { "key": "resets_at", "type": "date", "format": "countdown", "units": { "one": "resets in {n}", "other": "resets in {n}", "zero": "has reset" } }        ],        "title": "name", "date": null, "project": null, "order": null,        "slip": { "title": "name", "subtitle": "resets_at", "trailing": null, "photo": null, "toggle": null, "caption": { "columns": ["checked_at"] } },        "tile": { "face": "slip-list" }, "page": [], "instructions": "Synthetic allowances."    }))    .unwrap();    definition.validate().expect("units on a countdown date are its template and its passed word");    let now = chrono::DateTime::parse_from_rfc3339("2026-10-17T12:00:00Z").unwrap().with_timezone(&chrono::Utc);    let at = |offset_minutes: i64| (now + chrono::Duration::minutes(offset_minutes)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);    let slip = |checked: i64, resets: i64| {        let data = serde_json::from_value(json!({ "name": "synthetic@example.test", "checked_at": at(checked), "resets_at": at(resets) })).unwrap();        resolve_slip_lines(&definition, &data, Some("UTC"), Some(now), true, crate::records::page::Words::shipped())    };    // A reading taken a day ago whose 2 h 24 min window ended since: no    // countdown into the future from the reading time.    let yesterday = slip(-24 * 60, -24 * 60 + 144);    assert_eq!(yesterday.subtitle.as_deref(), Some("has reset"));    assert_eq!(yesterday.caption.as_deref(), Some("yesterday"));    // A week read three days ago that reset 2 d 23 h after it: over too.    assert_eq!(slip(-3 * 1440, -3 * 1440 + 2 * 1440 + 23 * 60).subtitle.as_deref(), Some("has reset"));    // A fresh reading counts down from now.    assert_eq!(slip(-1, 144).subtitle.as_deref(), Some("resets in 2 h 24 min"));    // An old reading whose instant is still ahead counts from now, not from it.    assert_eq!(slip(-24 * 60, 2 * 1440 + 23 * 60).subtitle.as_deref(), Some("resets in 2 d 23 h"));    assert_eq!(countdown_words(&at(0), now, DateWords::shipped()), None, "the instant itself has passed");    assert_eq!(countdown_words(&at(1), now, DateWords::shipped()).as_deref(), Some("1 min"));    // No reader's now: the instant itself, never a countdown.    let column = definition.column("resets_at").unwrap();    let said = fact_words(&definition, column, &json!(at(144)), &Map::new(), Some("UTC"), None, crate::records::page::Words::shipped()).unwrap();    assert!(!said.contains("resets in"), "{said}");}/// Connections and the repositories on their hosts, read as records.list/// narrows them: a row is listed when every `where` column equals its value.struct Hosts {    reaches: &'static str,    /// (id, host, held)    repositories: Vec<(String, &'static str, bool)>,    asked: Vec<Map<String, Value>>,}impl PageSource for Hosts {    fn line_rows(&mut self) -> Vec<crate::rules::shell_lines::LineRow> { Vec::new() }    fn definition(&mut self, table: &str) -> Option<TableDefinition> {        builtin_table_definition(table).cloned()    }    fn record(&mut self, _table: &str, _id: &str) -> Result<Map<String, Value>, String> {        let data = json!({ "kind": "Code host", "name": "Forge", "reaches": self.reaches, "state": "Reading" });        Ok(data.as_object().unwrap().clone())    }    fn records(&mut self, _table: &str, _ids: &[String]) -> Result<Vec<(String, Map<String, Value>)>, String> {        Ok(Vec::new())    }    fn list(&mut self, table: &str, filter: &Map<String, Value>, limit: usize) -> Result<(u64, Vec<(String, Map<String, Value>)>), String> {        if table != "repository" {            return Ok((0, Vec::new()));        }        self.asked.push(filter.clone());        let found: Vec<(String, Map<String, Value>)> = self            .repositories            .iter()            .map(|(id, host, held)| (id.clone(), json!({ "name": id, "host": host, "held": held }).as_object().unwrap().clone()))            .filter(|(_, data)| filter.iter().all(|(column, value)| data.get(column) == Some(value)))            .collect();        Ok((found.len() as u64, found.into_iter().take(limit).collect()))    }    fn active_project_slugs(&mut self) -> Vec<String> {        Vec::new()    }    fn read(&mut self, name: &str, _args: &Map<String, Value>) -> Result<Value, String> {        Err(format!("no read.{name} here"))    }}fn scalar_reading_fixture() -> TableDefinition {    serde_json::from_value(json!({        "id":"reading_probe", "name":"Probe", "plural":"Probes", "builtin":false,        "columns":[            {"key":"name", "type":"text"},            {"key":"quantity", "type":"number", "name":"fixture units", "fact":true, "reading":"{value} probe units"},            {"key":"seen_at", "type":"date", "format":"ago", "fact":true, "reading":"measured {value}"}        ],        "title":"name", "date":null, "project":null, "order":null,        "slip":{"title":"name", "subtitle":"quantity", "with_names":true, "caption":{"columns":["seen_at"]}},        "tile":{"face":"slip-list"}, "page":[], "instructions":"Synthetic reading inputs."    })).unwrap()}/// RULE: Fact templates preserve whole-number units and refuse missing, invalid or unread values; a synthetic definition keeps this logic independent of shipped copy.#[test]fn fact_templates_refuse_missing_or_invalid_scalars() {    let table = scalar_reading_fixture();    table.validate().unwrap();    let data = Map::new();    let read = |key: &str, value: Value| read_fact(&table, table.column(key).unwrap(), &value, &data, None, None, crate::records::page::Words::shipped());    assert_eq!(read("quantity", json!(16.0)).as_deref(), Some("16 probe units"));    assert!(read("seen_at", json!("2026-08-20T08:30:00Z")).is_some());    assert!(read("seen_at", json!("bad timestamp")).is_none());    assert!(read("quantity", Value::Null).is_none());    let mut column = table.column("quantity").unwrap().clone();    column.reading = None;    assert!(read_fact(&table, &column, &json!(16), &data, None, None, crate::records::page::Words::shipped()).is_none());}/// RULE: A slip obeys its declared date format, column names and visibility; synthetic inputs prove rewording and hiding need no engine change without pinning a shipped slip.#[test]fn slip_readings_follow_types_names_and_visibility() {    let mut table = scalar_reading_fixture();    let data = serde_json::from_value(json!({"quantity":16,"seen_at":"2026-10-14T00:00:00Z"})).unwrap();    let now = chrono::DateTime::parse_from_rfc3339("2026-10-14T00:03:00Z").unwrap().with_timezone(&chrono::Utc);    let line = resolve_slip_lines(&table, &data, Some("UTC"), Some(now), true, crate::records::page::Words::shipped());    assert_eq!(line.subtitle.as_deref(), Some("16 fixture units"));    assert_eq!(line.caption.as_deref(), Some("3 min ago"));    table.columns.iter_mut().find(|column| column.key == "quantity").unwrap().name = Some("available samples".into());    assert_eq!(resolve_slip_lines(&table, &data, None, Some(now), true, crate::records::page::Words::shipped()).subtitle.as_deref(), Some("16 available samples"));    table.columns.iter_mut().find(|column| column.key == "quantity").unwrap().hidden = Some(true);    assert!(resolve_slip_lines(&table, &data, None, Some(now), true, crate::records::page::Words::shipped()).subtitle.is_none());    let absent = resolve_slip_lines(&table, &Map::new(), None, Some(now), true, crate::records::page::Words::shipped());    assert!(absent.subtitle.is_none() && absent.caption.is_none());}/// RULE: When the definition borrows a body's first line as the head, the resolved page keeps that line whole and reads the body after it; an explicit title leaves the body intact.#[test]fn a_derived_page_title_and_body_share_no_line() {    let long = "The whole opening line 🧵 ".repeat(12).trim().to_string();    let definition = builtin_table_definition("note").unwrap().clone();    for (title, body, head, rest) in [        (None, "Asha wrote this on her phone.\nmore", "Asha wrote this on her phone.", Some("more")),        (None, "Asha wrote this on her phone.", "Asha wrote this on her phone.", None),        (None, long.as_str(), long.as_str(), None),        (None, "Élodie wrote this.\r\nmore", "Élodie wrote this.", Some("more")),        (Some("Own title"), "Asha wrote this on her phone.\nmore", "Own title", Some("Asha wrote this on her phone.\nmore")),        (Some("  "), "\n# **Opening** words\n\n- Keep this formatting", "Opening words", Some("\n- Keep this formatting")),    ] {        let data = json!({"title":title,"body":body}).as_object().unwrap().clone();        let original = data.clone();        let mut source = One { definition: definition.clone(), data };        let page = record_page(&mut source, "note", "synthetic-note").unwrap();        assert_eq!(page.head.title, head);        assert_eq!(page.body.as_ref().map(|body| body.text.as_str()), rest);        assert_eq!(source.data, original, "presentation must never rewrite the stored body");    }}/// RULE: A list reads text through the core as plain words before clipping; a Markdown link or code span never reaches a slip, and the source record is left intact.#[test]fn list_text_columns_resolve_as_plain_previews() {    let definition = builtin_table_definition("thread").unwrap();    assert!(subtitle_reads(definition));    let text = "May I run `npm install`? See [the plan](https://example.com/plan).";    let data = json!({"last_message_preview":text}).as_object().unwrap().clone();    let lines = resolve_slip_lines(definition, &data, None, None, true, crate::records::page::Words::shipped());    assert_eq!(lines.subtitle.as_deref(), Some("May I run npm install? See the plan."));    assert_eq!(data["last_message_preview"], text);    let note = builtin_table_definition("note").unwrap();    let data = json!({"body":"Opening line\nThe **remaining** words"}).as_object().unwrap().clone();    assert_eq!(resolve_slip_lines(note, &data, None, None, true, crate::records::page::Words::shipped()).subtitle.as_deref(), Some("The remaining words"));}/// RULE: Placeholder hints never become column labels or resolved values; changing a visual hint cannot change the core's reading of an absent, blank or written field.#[test]fn placeholder_hints_do_not_change_labels_or_resolved_values() {    for definition in crate::definitions::builtin_table_definitions() {        for column in &definition.columns {            let mut hinted = column.clone();            hinted.placeholder = Some("visual hint, never field data".into());            assert_eq!(hinted.label(), column.label(), "{}.{}", definition.id, column.key);            for value in [Value::Null, json!(""), json!("Written words")] {                let data = Map::from_iter([(column.key.clone(), value.clone())]);                assert_eq!(                    super::fact_words(definition, &hinted, &value, &data, None, None, crate::records::page::Words::shipped()),                    super::fact_words(definition, column, &value, &data, None, None, crate::records::page::Words::shipped()),                    "{}.{}", definition.id, column.key,                );            }        }    }}/// The synthetic built-ins, with `document` as one package or another/// leaves it: drawn narrowed without `people` (`Some(false)`), or drawn by/// no tool at all, its reads answering the no-tool line (`None`).struct Undrawn {    inner: Synthetic,    narrowed: Option<bool>,}impl PageSource for Undrawn {    fn line_rows(&mut self) -> Vec<crate::rules::shell_lines::LineRow> { Vec::new() }    fn definition(&mut self, table: &str) -> Option<TableDefinition> {        if table != "document" {            return self.inner.definition(table);        }        self.narrowed?;        let mut document = crate::kit::table("document").expect("Documents ships the document table");        document.columns.retain(|column| column.key != "people");        Some(document)    }    fn record(&mut self, table: &str, id: &str) -> Result<Map<String, Value>, String> {        self.inner.record(table, id)    }    fn records(&mut self, table: &str, ids: &[String]) -> Result<Vec<(String, Map<String, Value>)>, String> {        self.inner.records(table, ids)    }    fn list(&mut self, table: &str, filter: &Map<String, Value>, limit: usize) -> Result<(u64, Vec<(String, Map<String, Value>)>), String> {        if table != "document" {            return self.inner.list(table, filter, limit);        }        match self.narrowed {            Some(_) => Err("Artifacts have no column \"people\"".into()),            None => unreachable!("a table no tool draws has no definition, so its list is never asked"),        }    }    fn active_project_slugs(&mut self) -> Vec<String> {        self.inner.active_project_slugs()    }    fn read(&mut self, name: &str, args: &Map<String, Value>) -> Result<Value, String> {        self.inner.read(name, args)    }}/// RULE: A record page's list over another table is skipped quietly, never a refusal, when that table's/// definition lacks the list's relation column or no tool draws the table: People's Documents list in a/// household without Documents, or with a package that narrowed document, must leave the person page/// standing (architect, 21 Oct 2026: "Artifacts have no column people" broke every fresh household).#[test]fn a_list_over_an_undrawn_or_narrowed_table_is_skipped_and_the_page_stands() {    for narrowed in [Some(false), None] {        let mut source = Undrawn { inner: Synthetic::new(false), narrowed };        let page = record_page(&mut source, "person", "id-person").unwrap_or_else(|error| panic!("{narrowed:?}: {error}"));        assert!(page.lists.iter().all(|list| list.table.as_deref() != Some("document")), "{narrowed:?}");        assert!(page.lists.iter().any(|list| list.table.as_deref() == Some("todo")), "the other lists stay");    }}/// RULE: a key reads as a sentence the way the app's plain words split it.#[test]fn a_key_reads_as_a_sentence() {    use crate::definitions::key_as_words;    assert_eq!(key_as_words("role_title"), "Role title");    assert_eq!(key_as_words("inProgress"), "In progress");    assert_eq!(key_as_words("HTTP_status"), "HTTP status");    assert_eq!(key_as_words("DONE"), "Done");    assert_eq!(key_as_words("on-the.way now"), "On the way now");    assert_eq!(key_as_words("__"), "");}/// RULE: a `format: words` column reads as its sentence in @column_words, and an unlabelled repeat rule reads through fact_words.#[test]fn a_words_column_and_a_repeat_rule_read_in_column_words() {    let mut definition = crate::definitions::builtin_table_definition("todo").unwrap().clone();    let mut words_column = definition.columns[0].clone();    words_column.key = "invented_state".into();    words_column.column_type = crate::definitions::ColumnType::Text;    words_column.format = Some(crate::definitions::ColumnFormat::Words);    words_column.labels = None;    words_column.zone = None;    words_column.secret = None;    let mut rule = words_column.clone();    rule.key = "invented_rule".into();    rule.format = Some(crate::definitions::ColumnFormat::RepeatRule);    definition.columns = vec![words_column, rule.clone()];    let data: serde_json::Map<String, serde_json::Value> =        [("invented_state".to_string(), serde_json::json!("inProgress")), ("invented_rule".to_string(), serde_json::json!("FREQ=WEEKLY"))].into_iter().collect();    let words = Words::shipped();    let said = column_words(&definition, &data, Some("Asia/Kolkata"), None, words);    assert_eq!(said["invented_state"], serde_json::json!("In progress"));    let preset = words.dates.repeat(Some("FREQ=WEEKLY"));    assert!(preset.is_some());    assert_eq!(said["invented_rule"], serde_json::json!(preset));    assert_eq!(fact_words(&definition, &rule, &data["invented_rule"], &data, None, None, words), preset, "the RepeatRule arm runs");    assert!(reads_column_words(&definition));}