Cotton code
1135 lines · 50.2 KB · RustRaw
//! A package's shape is data: the tables a tool owns come from its definition,//! and a file holds AT LEAST the shape of every definition it holds.//!//! Phase 2 of tools as packages (architect's brief, 12 Oct 2026). A built-in//! package's tables are part of the flat DDL and move with the core//! (`shape_move`); a package a person brought — imported, or defined by//! conversation — has its tables made from its `cotton_table_definitions` row,//! by [`step`], whenever that row is new or higher://!//! - a table the file lacks is created, with its indexes, search index and//!   the search index's triggers;//! - a column the file lacks is added by `ADD COLUMN` — nullable or with a//!   constant default, so every row already there stays as it was;//! - a column the file holds and the shape does not is KEPT: an older revision//!   arriving after a newer one never takes a column away (the file is ahead);//! - a column whose type, key, nullability or default differs is REFUSED, as//!   is a revision that drops or renames one ([`check_add_only`]). A column//!   that is no longer wanted is marked retired in the definition and stays.//!//! The fold learns a package table's columns from the FILE ([`spec_on`]), so a//! receipt naming a column or a table this file does not hold yet is parked//! `newer-shape` rather than refused, and folded again after the next step.use std::collections::{BTreeMap, BTreeSet};use std::sync::Mutex;use rusqlite::types::Value as SqlValue;use super::decl::{Codec, TableSpec};use super::package_tables::{    from_definition, generate, statement_table, validate_ownership, PackageColumn, PackageTable,};use crate::driver::Driver;use crate::error::{Result, StoreError};fn refuse(message: impl Into<String>) -> StoreError {    StoreError::refused(message.into())}/// One package-owned table a file's definitions declare, with the codec each/// of its columns is written and read by.#[derive(Debug, Clone, PartialEq)]pub struct DeclaredTable {    /// The `cotton_table_definitions` row it comes from.    pub definition: String,    pub table: PackageTable,    pub codecs: BTreeMap<String, Codec>,}/// The codec a declared column is stored by: what its definition type says,/// and for a metadata column, what the record shape says (`*_at` instants).fn codec_for(name: &str, sql_type: &str, kind: Option<&str>) -> Codec {    match kind {        Some("number" | "bytes") => Codec::Real,        Some("amount") => Codec::MoneyMinor,        Some("bool") => Codec::Bool,        Some("list") => Codec::Json,        Some(_) => Codec::Text,        None if matches!(name, "created_at" | "updated_at" | "deleted_at") => Codec::Timestamp,        None => match sql_type {            "INTEGER" => Codec::Int,            "REAL" | "NUMERIC" => Codec::Real,            _ => Codec::Text,        },    }}/// The tables a definition owns, from its JSON: its authored `tables` section/// when it carries one, else the storage its columns derive/// ([`from_definition`]). `None` for a compiled engine binding, whose storage/// the flat DDL owns.pub fn declared(definition: &serde_json::Value) -> Result<Option<Vec<DeclaredTable>>> {    if super::package_tables::has_engine(definition) {        return Ok(None);    }    if !definition["engine"].is_null() {        return Err(refuse("definition names no engine binding this build carries"));    }    let id = definition["id"].as_str().ok_or_else(|| refuse("definition needs id"))?;    let authored = definition["tables"].as_array().filter(|tables| !tables.is_empty());    let tables: Vec<PackageTable> = match authored {        Some(tables) => serde_json::from_value(serde_json::Value::Array(tables.clone()))            .map_err(|error| refuse(format!("definition {id}: {error}")))?,        None => from_definition(definition)?,    };    // Imported shapes are declarative data: no SQL fragment passes.    generate(&tables, false)?;    // A column holding several values (`multiple`) is kept as one JSON list,    // whatever its type.    let kinds: BTreeMap<&str, &str> = definition["columns"]        .as_array()        .into_iter()        .chain(definition["retired"].as_array())        .flatten()        .filter_map(|column| Some((column["key"].as_str()?, if column["multiple"] == true { "list" } else { column["type"].as_str()? })))        .collect();    Ok(Some(        tables            .into_iter()            .map(|table| DeclaredTable {                definition: id.to_owned(),                codecs: table                    .columns                    .iter()                    .map(|c| {                        let kind = if authored.is_some() { None } else { kinds.get(c.name.as_str()).copied() };                        (c.name.clone(), codec_for(&c.name, &c.sql_type, kind))                    })                    .collect(),                table,            })            .collect(),    ))}/// The made tables Cotton's own code writes, which no definition row/// declares: every file holds them, as it holds a definition's. The data/// automations' notifications (`cotton_tools` reads its definition here).pub const CODE_MADE: &[&str] = &[    r#"{"id":"automation_notification","name":"Notification","plural":"Notifications","picture":null,"builtin":false,"engine":null,"columns":[{"key":"text","name":"Text","type":"text","required":true}],"title":"text","date":null,"project":null,"order":null,"slip":{"title":"text","subtitle":null,"trailing":null,"photo":null,"toggle":null},"tile":{"face":"slip-list"},"page":[{"heading":null,"columns":["text"]}],"instructions":"Notifications from data automations."}"#,];/// The declared tables, and the definitions refused with why.type Declared = (Vec<DeclaredTable>, Vec<(String, String)>);/// A column a person added: its key, SQL type and codec.type OwnColumn = (String, String, Codec);/// Every package-owned table this file's definitions declare, and the/// definitions whose storage could not be derived, with why.pub fn file_packages(db: &Driver) -> Result<(Vec<DeclaredTable>, Vec<(String, String)>)> {    packages_of(db, None)}/// [`file_packages`] of the definitions `only` names, or of every one (and/// the code-made tables) when `None`.fn packages_of(db: &Driver, only: Option<&BTreeSet<String>>) -> Result<Declared> {    let rows = definition_texts(db, only)?;    let (mut tables, mut refused) = (if only.is_none() { code_made()? } else { Vec::new() }, Vec::new());    for (id, text) in rows {        match declared_text(&text) {            Ok(Some(declared)) => tables.extend(declared),            Ok(None) => {}            Err(why) => refused.push((id, why)),        }    }    Ok((tables, refused))}/// The definition rows' texts by id: those `only` names, or every one.pub fn definition_texts(db: &Driver, only: Option<&BTreeSet<String>>) -> Result<Vec<(String, String)>> {    let rows = match only {        None => db.all("SELECT id, definition FROM cotton_table_definitions ORDER BY id", &[])?,        Some(only) if only.is_empty() => Vec::new(),        Some(only) => db.all(            &format!(                "SELECT id, definition FROM cotton_table_definitions WHERE id IN ({}) ORDER BY id",                vec!["?"; only.len()].join(", ")            ),            &only.iter().map(|id| SqlValue::Text(id.clone())).collect::<Vec<_>>(),        )?,    };    Ok(rows        .iter()        .map(|row| (row.text("id").unwrap_or_default().to_owned(), row.text("definition").unwrap_or_default().to_owned()))        .collect())}/// The tables [`CODE_MADE`] declares: compiled in, so read once a process.fn code_made() -> Result<Vec<DeclaredTable>> {    static TABLES: std::sync::LazyLock<std::result::Result<Vec<DeclaredTable>, String>> = std::sync::LazyLock::new(|| {        let mut tables = Vec::new();        for made in CODE_MADE {            let definition: serde_json::Value = serde_json::from_str(made).map_err(|error| error.to_string())?;            if let Some(declared) = declared(&definition).map_err(|error| error.to_string())? {                tables.extend(declared);            }        }        Ok(tables)    });    TABLES.clone().map_err(refuse)}/// [`declared`] of one definition row as the file holds it, or why its/// storage cannot be derived — remembered by the row's exact text.////// [`file_packages`] reads every definition the file holds, and a file is/// stepped after every batch that brings a definition and asked for its/// package specs after every schema change: importing the kit parsed and/// generated each of its definitions some forty times over, a quarter of a/// kit import (6 Nov 2026: 44 reads, 11 of its 41 s in a debug build), on/// the phone's first open as in every test. The answer is a function of the/// text alone (the compiled built-ins and the generator), so the same text/// is answered from memory; a changed definition is a new text.fn declared_text(text: &str) -> std::result::Result<Option<Vec<DeclaredTable>>, String> {    (*declared_text_shared(text)).clone()}type DeclaredAnswer = std::result::Result<Option<Vec<DeclaredTable>>, String>;/// [`declared_text`] as the memory holds it, shared rather than copied: a/// reader looking for one table clones that table alone.fn declared_text_shared(text: &str) -> std::sync::Arc<DeclaredAnswer> {    type Memo = BTreeMap<String, std::sync::Arc<DeclaredAnswer>>;    static MEMO: std::sync::LazyLock<Mutex<Memo>> = std::sync::LazyLock::new(|| Mutex::new(BTreeMap::new()));    // Bounded: a long-lived process that sees definitions edited many times    // starts again rather than keeping every text it was ever handed.    const KEPT: usize = 2048;    if let Some(known) = MEMO.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).get(text) {        return known.clone();    }    let answer = std::sync::Arc::new(        serde_json::from_str::<serde_json::Value>(text)            .map_err(|error| refuse(error.to_string()))            .and_then(|definition| declared(&definition))            .map_err(|error| error.to_string()),    );    let mut memo = MEMO.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    if memo.len() >= KEPT {        memo.clear();    }    memo.insert(text.to_owned(), answer.clone());    answer}/// The declaration of `table` that [`file_packages`] would answer — the last/// one, the code-made tables first and then the definitions by id — cloning/// that one alone instead of every declaration the file holds. A definition/// whose storage cannot be derived declares nothing, as there.fn last_declaration_of(db: &Driver, table: &str) -> Result<Option<DeclaredTable>> {    static MADE: std::sync::LazyLock<std::result::Result<Vec<DeclaredTable>, String>> = std::sync::LazyLock::new(|| code_made().map_err(|error| error.to_string()));    let made = MADE.as_ref().map_err(|error| refuse(error.clone()))?;    let mut found = made.iter().rev().find(|declared| declared.table.name == table).cloned();    for (_, text) in definition_texts(db, None)? {        if let Ok(Some(declared)) = declared_text_shared(&text).as_ref() {            if let Some(last) = declared.iter().rev().find(|declared| declared.table.name == table) {                found = Some(last.clone());            }        }    }    Ok(found)}/// What [`step`] did, in schema words.#[derive(Debug, Clone, Default, PartialEq)]pub struct StepReport {    /// `table <name>`, `index <name>`, `search index <name>`, `trigger <name>`.    pub created: Vec<String>,    /// `<table>.<column>` added in place.    pub added: Vec<String>,    /// Indexes, triggers and search indexes made again under the shape.    pub replaced: Vec<String>,    /// `<table>.<column>` the file holds and the shape does not: kept.    pub ahead: Vec<String>,}impl StepReport {    /// Did the step change this file's shape?    pub fn changed(&self) -> bool {        !(self.created.is_empty() && self.added.is_empty() && self.replaced.is_empty())    }}struct FileColumn {    name: String,    sql_type: String,    not_null: bool,    default: Option<String>,    primary_key: bool,}fn file_columns(db: &Driver, table: &str) -> Result<Vec<FileColumn>> {    Ok(db        .all(            "SELECT name, type, \"notnull\" AS nn, dflt_value, pk FROM pragma_table_info(?) ORDER BY cid",            &[SqlValue::Text(table.to_owned())],        )?        .iter()        .map(|row| FileColumn {            name: row.text("name").unwrap_or_default().to_owned(),            sql_type: row.text("type").unwrap_or_default().to_ascii_uppercase(),            not_null: row.int("nn") == Some(1),            default: row.text("dflt_value").map(str::to_owned),            primary_key: row.int("pk").unwrap_or(0) > 0,        })        .collect())}/// How a column the file holds differs from the shape's, if it does.fn differs(had: &FileColumn, wanted: &PackageColumn) -> Option<String> {    if had.sql_type != wanted.sql_type {        return Some(format!("its type is {} here and {} in the package", had.sql_type, wanted.sql_type));    }    if had.primary_key != wanted.primary_key {        return Some("its key changed".into());    }    if had.default != wanted.default {        return Some("its default changed".into());    }    if had.not_null != !wanted.nullable {        return Some("whether it may be empty changed".into());    }    None}fn add_column_sql(column: &PackageColumn) -> Result<String> {    if column.primary_key {        return Err(refuse(format!("column {} is a key and cannot be added in place", column.name)));    }    if !column.nullable && column.default.is_none() {        return Err(refuse(format!("column {} is new, may not be empty and has no default", column.name)));    }    // The same words `generate` writes, read back off a one-column table.    let one = generate(        &[PackageTable {            name: "one".into(),            columns: vec![column.clone()],            constraints: Vec::new(),            prefix: None,            suffix: None,            indexes: Vec::new(),            full_text: Vec::new(),            triggers: Vec::new(),        }],        false,    )?;    let sql = &one[0];    let open = sql.find('(').ok_or_else(|| refuse("generated table has no columns"))?;    Ok(sql[open + 1..sql.len() - 1].to_owned())}/// The name of the object a generated statement makes.fn made(sql: &str) -> Option<(&'static str, String)> {    // Only the first four words name it; a table's whole statement is never split.    let words: Vec<&str> = sql.split_whitespace().take(4).collect();    let (kind, at) = match (words.get(1).copied(), words.get(2).copied()) {        (Some("VIRTUAL"), _) => ("search index", 3),        (Some("UNIQUE"), _) => ("index", 3),        (Some("INDEX"), _) => ("index", 2),        (Some("TRIGGER"), _) => ("trigger", 2),        (Some("TABLE"), _) => ("table", 2),        _ => return None,    };    Some((kind, words.get(at)?.trim_matches('"').to_owned()))}/// Make this file hold AT LEAST `tables`, in place and add-only, as one/// transaction (see the module). Refuses a column that differs, a table a/// core object or another package holds, and any SQL fragment.pub fn step(db: &Driver, tables: &[PackageTable]) -> Result<StepReport> {    let generated = generate(tables, false)?;    let mine: BTreeSet<&str> = tables.iter().map(|t| t.name.as_str()).collect();    db.transaction(|db| {        let occupied: BTreeSet<String> = db            .all("SELECT name, tbl_name FROM sqlite_master", &[])?            .iter()            .filter(|row| !mine.contains(row.text("tbl_name").unwrap_or_default()))            .filter(|row| {                // A search index's own shadow tables carry its name, not ours.                let name = row.text("name").unwrap_or_default();                !tables.iter().any(|t| {                    t.full_text.iter().any(|f| match f {                        super::package_tables::PackageFullText::Declared { name: index, .. } => {                            name == index || name.starts_with(&format!("{index}_"))                        }                        _ => false,                    })                })            })            .filter_map(|row| row.text("name").map(str::to_owned))            .collect();        validate_ownership(tables, &occupied)?;        let mut report = StepReport::default();        let mut widened = BTreeSet::new();        let mut ahead_tables = BTreeSet::new();        for table in tables {            let had = file_columns(db, &table.name)?;            if had.is_empty() {                let create = generated                    .iter()                    .find(|sql| made(sql).is_some_and(|(kind, name)| kind == "table" && name == table.name))                    .ok_or_else(|| refuse("package omitted its table"))?;                db.exec(create)?;                report.created.push(format!("table {}", table.name));                continue;            }            for wanted in &table.columns {                match had.iter().find(|c| c.name == wanted.name) {                    Some(column) => {                        if let Some(why) = differs(column, wanted) {                            return Err(refuse(format!(                                "package shape for {}.{} is not add-only: {why}; a column only gains, and one no longer wanted is marked retired",                                table.name, wanted.name                            )));                        }                    }                    None => {                        db.exec(&format!("ALTER TABLE \"{}\" ADD COLUMN {}", table.name, add_column_sql(wanted)?))?;                        report.added.push(format!("{}.{}", table.name, wanted.name));                        widened.insert(table.name.clone());                    }                }            }            for column in had.iter().filter(|c| !table.columns.iter().any(|w| w.name == c.name)) {                report.ahead.push(format!("{}.{}", table.name, column.name));                ahead_tables.insert(table.name.clone());            }        }        // The rest — indexes, search indexes, their triggers — per table. A        // file AHEAD of the shape keeps its own (they may index its newer        // columns); otherwise a differing one is made again, and a search        // index made over rows already here is filled from them.        for table in tables {            let rest: Vec<(&'static str, String, &String)> = generated                .iter()                .filter(|sql| statement_table(sql).as_deref() == Some(table.name.as_str()) || sql.contains(&format!("ON \"{}\"", table.name)))                .filter_map(|sql| made(sql).map(|(kind, name)| (kind, name, sql)))                .filter(|(kind, _, _)| *kind != "table")                .collect();            let stale: Vec<&(&'static str, String, &String)> = rest                .iter()                .filter(|(_, name, sql)| {                    db.get("SELECT sql FROM sqlite_master WHERE name = ?", &[SqlValue::Text(name.clone())])                        .ok()                        .flatten()                        .and_then(|row| row.text("sql").map(str::to_owned))                        .is_some_and(|had| had != **sql)                })                .collect();            if !stale.is_empty() && ahead_tables.contains(&table.name) && !widened.contains(&table.name) {                continue;            }            // Triggers first: they name the search index they write.            let mut order = stale.clone();            order.sort_by_key(|(kind, _, _)| match *kind {                "trigger" => 0,                "search index" => 1,                _ => 2,            });            for (kind, name, _) in &order {                let what = if *kind == "search index" { "TABLE" } else if *kind == "trigger" { "TRIGGER" } else { "INDEX" };                db.exec(&format!("DROP {what} \"{name}\""))?;            }            let mut fill = Vec::new();            for (kind, name, sql) in &rest {                let exists = db                    .get("SELECT 1 AS one FROM sqlite_master WHERE name = ?", &[SqlValue::Text(name.clone())])?                    .is_some();                if exists {                    continue;                }                db.exec(sql)?;                if stale.iter().any(|(_, n, _)| n == name) {                    report.replaced.push(format!("{kind} {name}"));                } else {                    report.created.push(format!("{kind} {name}"));                }                if *kind == "search index" {                    fill.push(name.clone());                }            }            for index in fill {                db.exec(&format!("INSERT INTO \"{index}\" (\"{index}\") VALUES ('rebuild')"))?;            }        }        // A table or a column more: what the file refused is due again.        if !report.created.is_empty() || !report.added.is_empty() {            crate::rejected::shape_changed(db)?;        }        // MAIL PREDICATE phase 2 (schema 157): a kit's mail cut table is mirrored into `_mail_cuts`, which the mail        // predicate reads on every copy; the triggers keep it so and the copy's rows are taken now.        for (table, kind) in cotton_rules::mail::predicate::cuts::KINDS {            if mine.contains(table) {                for statement in cotton_rules::mail::predicate::cuts::mirror(table, kind) {                    db.exec(&statement)?;                }            }        }        Ok(report)    })}/// [`step`] for every package this file's definitions declare: the launch/// path and the path after a definition arrives. A definition whose storage/// cannot be derived, or whose shape is refused, is answered in the second/// list and changes nothing; the others still step.pub fn step_file(db: &Driver) -> Result<(StepReport, Vec<(String, String)>)> {    step_declared(db, None)}/// [`step_file`] for the definitions `only` names and nothing else: what a/// fold that wrote those definitions steps ([`after_definitions`]).pub fn step_definitions(db: &Driver, only: &BTreeSet<String>) -> Result<(StepReport, Vec<(String, String)>)> {    step_declared(db, Some(only))}fn step_declared(db: &Driver, only: Option<&BTreeSet<String>>) -> Result<(StepReport, Vec<(String, String)>)> {    let _span = crate::spans::span("package_shape::step");    let (declared, mut refused) = packages_of(db, only)?;    let mut by_definition: BTreeMap<&str, Vec<PackageTable>> = BTreeMap::new();    for table in &declared {        by_definition.entry(&table.definition).or_default().push(table.table.clone());    }    let mut report = StepReport::default();    for (definition, tables) in by_definition {        match step(db, &tables) {            Ok(one) => {                report.created.extend(one.created);                report.added.extend(one.added);                report.replaced.extend(one.replaced);                report.ahead.extend(one.ahead);            }            Err(error) => refused.push((definition.to_owned(), error.to_string())),        }    }    let (own, own_refused) = step_own_of(db, only)?;    report.added.extend(own.added);    refused.extend(own_refused);    Ok((report, refused))}/// GUARD 3's rule between two revisions of one package: every table and/// every column of `previous` is in `next`, of the same type and key, no/// narrower and with the same default. A column no longer wanted is marked/// retired in the definition, never dropped; a rename is a new column.pub fn check_add_only(previous: &[PackageTable], next: &[PackageTable]) -> Result<()> {    for old in previous {        let Some(new) = next.iter().find(|t| t.name == old.name) else {            return Err(refuse(format!(                "a package revision may only add: it drops the table {}",                old.name            )));        };        for column in &old.columns {            let Some(wanted) = new.columns.iter().find(|c| c.name == column.name) else {                return Err(refuse(format!(                    "a package revision may only add: it drops or renames {}.{}; mark the column retired instead",                    old.name, column.name                )));            };            let had = FileColumn {                name: column.name.clone(),                sql_type: column.sql_type.clone(),                not_null: !column.nullable,                default: column.default.clone(),                primary_key: column.primary_key,            };            if let Some(why) = differs(&had, wanted) {                return Err(refuse(format!(                    "a package revision may only add: {}.{} narrows or changes — {why}",                    old.name, column.name                )));            }        }    }    Ok(())}// ---------------------------------------------------------------------------// What the fold and the minter know of a package table./// One spec per distinct shape, for the life of the process: a `TableSpec`/// is `'static` everywhere the fold and the minter hold one, and a package's/// shapes are few and only grow, so each is made once and kept.static INTERNED: Mutex<Vec<&'static TableSpec>> = Mutex::new(Vec::new());fn intern(name: &str, pk: &str, columns: Vec<(String, Codec)>) -> &'static TableSpec {    let mut interned = INTERNED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    if let Some(spec) = interned.iter().find(|spec| {        spec.name == name            && spec.pk == pk            && spec.columns.len() == columns.len()            && spec.columns.iter().zip(&columns).all(|((a, x), (b, y))| a == b && x == y)    }) {        return spec;    }    let leaked_columns: &'static [(&'static str, Codec)] = Box::leak(        columns            .iter()            .map(|(column, codec)| (&*Box::leak(column.clone().into_boxed_str()), *codec))            .collect::<Vec<_>>()            .into_boxed_slice(),    );    let spec: &'static TableSpec = Box::leak(Box::new(TableSpec {        name: Box::leak(name.to_owned().into_boxed_str()),        pk: Box::leak(pk.to_owned().into_boxed_str()),        columns: leaked_columns,        natural_key: &[],        fts_into: None,    }));    interned.push(spec);    spec}/// A shipped table's spec with the columns a person added to it on this/// file (`own_<key>`), after the build's own; its key, natural key and search/// index stay the build's.fn intern_with_own(base: &'static TableSpec, own: &[(String, Codec)]) -> &'static TableSpec {    let mut interned = INTERNED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    let wanted = base.columns.len() + own.len();    if let Some(spec) = interned.iter().find(|spec| {        spec.name == base.name            && spec.columns.len() == wanted            && spec.columns[..base.columns.len()] == *base.columns            && spec.columns[base.columns.len()..].iter().zip(own).all(|((a, x), (b, y))| a == b && x == y)    }) {        return spec;    }    let columns: Vec<(&'static str, Codec)> = base        .columns        .iter()        .copied()        .chain(own.iter().map(|(column, codec)| (&*Box::leak(column.clone().into_boxed_str()), *codec)))        .collect();    let spec: &'static TableSpec = Box::leak(Box::new(TableSpec { columns: Box::leak(columns.into_boxed_slice()), ..*base }));    interned.push(spec);    spec}/// The bookkeeping columns every synced row carries and no receipt names.fn bookkeeping(column: &str) -> bool {    column.starts_with('_')}/// The package tables of this file as the fold and the minter see them: each/// declared table the file HOLDS, with the columns the file holds — so a/// receipt naming a column a newer revision brings is not this file's yet.fn package_specs(db: &Driver) -> Result<BTreeMap<String, &'static TableSpec>> {    let (declared, _) = file_packages(db)?;    let mut specs = BTreeMap::new();    for table in declared {        let held = file_columns(db, &table.table.name)?;        if held.is_empty() {            continue;        }        let Some(pk) = held.iter().find(|c| c.primary_key) else { continue };        let columns = held            .iter()            .filter(|c| !bookkeeping(&c.name))            .map(|c| {                let codec = table.codecs.get(&c.name).copied().unwrap_or_else(|| codec_for(&c.name, &c.sql_type, None));                (c.name.clone(), codec)            })            .collect();        specs.insert(table.table.name.clone(), intern(&table.table.name, &pk.name, columns));    }    // A shipped table's columns added in place: a person's (`own_<key>`) the    // file holds, and those this copy keeps for the object's definition    // ([`add_served`]).    let mut added: BTreeMap<String, Vec<(String, Codec)>> = BTreeMap::new();    for (table, own) in own_columns(db)? {        let held: BTreeSet<String> = file_columns(db, &table)?.into_iter().map(|c| c.name).collect();        added.entry(table).or_default().extend(own.into_iter().filter(|(name, _, _)| held.contains(name)).map(|(name, _, codec)| (name, codec)));    }    for (table, served) in served_columns(db)? {        let columns = added.entry(table).or_default();        for (name, codec) in served {            if !columns.iter().any(|(held, _)| *held == name) {                columns.push((name, codec));            }        }    }    for (table, columns) in added {        let Some(base) = super::specs::spec_for(&table) else { continue };        if !columns.is_empty() {            specs.insert(table, intern_with_own(base, &columns));        }    }    Ok(specs)}/// [`package_specs`]' answer for `table` alone, read as that reads it.fn package_spec_of(db: &Driver, table: &str) -> Result<Option<&'static TableSpec>> {    if let Some(base) = super::specs::spec_for(table) {        let mut columns: Vec<(String, Codec)> = Vec::new();        // Only the definition rows whose store is this table can add to it.        let rows: BTreeSet<String> = BUILTIN_STORES.iter().filter(|(_, store)| *store == table).map(|(id, _)| (*id).to_owned()).collect();        if let Some(own) = own_columns_of(db, Some(&rows))?.remove(table) {            let held: BTreeSet<String> = file_columns(db, table)?.into_iter().map(|c| c.name).collect();            columns.extend(own.into_iter().filter(|(name, _, _)| held.contains(name)).map(|(name, _, codec)| (name, codec)));        }        for (name, codec) in served_columns(db)?.remove(table).unwrap_or_default() {            if !columns.iter().any(|(held, _)| *held == name) {                columns.push((name, codec));            }        }        return Ok((!columns.is_empty()).then(|| intern_with_own(base, &columns)));    }    // The last declaration wins, as it does in the whole map.    let Some(declared) = last_declaration_of(db, table)? else {        return Ok(None);    };    let held = file_columns(db, table)?;    let Some(pk) = held.iter().find(|c| c.primary_key) else { return Ok(None) };    let columns = held        .iter()        .filter(|c| !bookkeeping(&c.name))        .map(|c| (c.name.clone(), declared.codecs.get(&c.name).copied().unwrap_or_else(|| codec_for(&c.name, &c.sql_type, None))))        .collect();    Ok(Some(intern(table, &pk.name, columns)))}// ---------------------------------------------------------------------------// The columns a copy keeps because the object's definition names them./// How a copy declares a column it added to a shipped table because the/// object's definition of that table names it and the build's table lacks it/// (owner, 27 Oct 2026: the copy does not drop a column it does not have —/// the running balance the object's money engine writes on every/// transaction). The column's name is the object's key, so the declaration/// carries the mark: every reader of the file's statement/// ([`without_added`]) tells it from the build's own columns by it, as a/// person's added column is told by its `own_` name, and a move carries it/// with its values.pub const SERVED_MARK: &str = "CONSTRAINT served NULL";/// One column a served definition names that the build's table lacks: kept/// under the object's key, nullable, by its type's codec.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ServedColumn {    pub name: String,    pub sql_type: &'static str,    pub codec: Codec,}/// The column the object's `column_name` of type `kind` is kept as (`multiple`: a/// column of several values, kept as one JSON list) — the same SQL types a/// person's added column takes ([`own_columns`]). A key no column may carry,/// or a type this build does not know, is refused by name: a column is never/// guessed.pub fn served_column(column_name: &str, kind: &str, multiple: bool) -> Result<ServedColumn> {    let named = !column_name.is_empty()        && !column_name.starts_with('_')        && column_name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');    if !named {        return Err(refuse(format!("the object's column {column_name:?} is no name a column of this copy may carry")));    }    let sql_type = match kind {        _ if multiple => "TEXT",        "number" | "bytes" => "REAL",        "amount" | "bool" => "INTEGER",        "text" | "longtext" | "account_number" | "date" | "time" | "choice" | "link" | "photo" | "file" | "url" | "place" => "TEXT",        _ => return Err(refuse(format!("the object's column {column_name} is of type {kind:?}, which this build keeps no way"))),    };    let codec = codec_for(column_name, sql_type, Some(if multiple { "list" } else { kind }));    Ok(ServedColumn { name: column_name.to_owned(), sql_type, codec })}/// Make `table` — a table this build compiles — hold every column of/// `columns`, in place and add-only, as one transaction: a column already/// here of the same type is left as it is, one of another type is refused/// by name and nothing of the call stays, and one of the build's own columns/// is never added again. Returns `<table>.<column>` for each column added.pub fn add_served(db: &Driver, table: &str, columns: &[ServedColumn]) -> Result<Vec<String>> {    let spec = super::specs::spec_for(table).ok_or_else(|| refuse(format!("{table} is no table this build keeps")))?;    db.transaction(|db| {        let held = file_columns(db, table)?;        if held.is_empty() {            return Err(refuse(format!("this file holds no table {table}")));        }        let mut added = Vec::new();        for column in columns {            if spec.columns.iter().any(|(name, _)| *name == column.name) {                return Err(refuse(format!("{table}.{} is the build's own column, not one the object's definition adds", column.name)));            }            match held.iter().find(|had| had.name == column.name) {                Some(had) if had.sql_type.eq_ignore_ascii_case(column.sql_type) => {}                Some(had) => {                    return Err(refuse(format!(                        "{table}.{} is {} here and {} in the object's definition; a column only adds",                        column.name, had.sql_type, column.sql_type                    )))                }                None => {                    db.exec(&format!("ALTER TABLE \"{table}\" ADD COLUMN \"{}\" {} {SERVED_MARK}", column.name, column.sql_type))?;                    added.push(format!("{table}.{}", column.name));                }            }        }        // A column more: what the file refused is due again.        if !added.is_empty() {            crate::rejected::shape_changed(db)?;        }        Ok(added)    })}/// The columns this file's shipped tables carry for the object's/// definitions ([`add_served`]), by table: `(column, codec)` in the order/// the file added them, the codec its SQL type's.fn served_columns(db: &Driver) -> Result<BTreeMap<String, Vec<(String, Codec)>>> {    let mut out = BTreeMap::new();    let rows = db.all(        "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND instr(sql, ?) > 0",        &[SqlValue::Text(SERVED_MARK.to_owned())],    )?;    for row in rows {        let (Some(table), Some(sql)) = (row.text("name"), row.text("sql")) else { continue };        if super::specs::spec_for(table).is_none() {            continue;        }        let columns: Vec<(String, Codec)> = without_added(sql)            .1            .iter()            .filter(|declared| declared.ends_with(SERVED_MARK))            .filter_map(|declared| {                let name = added_name(declared)?;                let sql_type = declared[name.len() + 2..].split_whitespace().next().unwrap_or_default().to_ascii_uppercase();                Some((name, codec_for("", &sql_type, None)))            })            .collect();        out.insert(table.to_owned(), columns);    }    Ok(out)}/// The columns `table` carries in this file for the object's definition/// ([`add_served`]), in the order the file added them: what a reader of the/// table draws beside the build's own columns.pub fn served_on(db: &Driver, table: &str) -> Result<Vec<String>> {    Ok(served_columns(db)?.remove(table).unwrap_or_default().into_iter().map(|(name, _)| name).collect())}/// The name of one column declaration [`without_added`] took out/// (`"own_met_at" TEXT`, `"balance_after_minor" INTEGER CONSTRAINT served NULL`).pub fn added_name(declared: &str) -> Option<String> {    let rest = declared.strip_prefix('"')?;    Some(rest[..rest.find('"')?].to_owned())}/// Each shipped table's store table — the table its records are rows of,/// which a person's added columns join. Generated from/// `cotton_core::definitions::builtin_store_table` (cotton-tools'/// `own_columns_home`, whose ignored `print_builtin_stores` prints it) and/// held equal to it there: the store cannot read cotton-core.pub const BUILTIN_STORES: &[(&str, &str)] = &[    ("ai_calls", "cotton_ai_calls"),    ("alarm", "cotton_alarms"),    ("arrival", "cotton_arrivals"),    ("album", "cotton_media_albums"),    ("assistant", "cotton_mcp_tokens"),    ("call", "cotton_call_log"),    ("comment", "cotton_comments"),    ("connection", "cotton_connections"),    ("decision", "cotton_decisions"),    ("device", "cotton_devices"),    ("document", "cotton_documents"),    ("email", "cotton_emails"),    ("email_sender", "cotton_blocked_senders"),    ("email_thread", "cotton_email_threads"),    ("event", "cotton_events"),    ("evidence", "cotton_money_evidence"),    ("feedback", "cotton_feedback"),    ("goal", "cotton_goals"),    ("issue", "cotton_repo_issues"),    ("journal", "cotton_notes"),    ("location", "cotton_locations"),    ("meeting", "cotton_meetings"),    ("memory", "cotton_memories"),    ("message", "cotton_msg_messages"),    ("money_account", "cotton_money_accounts"),    ("mood", "cotton_moods"),    ("news_edition", "cotton_news_editions"),    ("note", "cotton_notes"),    ("outage", "cotton_outages"),    ("page", "cotton_pages"),    ("person", "cotton_people"),    ("person_handle", "cotton_person_handles"),    ("person_language", "cotton_person_languages"),    ("person_note", "cotton_person_notes"),    ("photo", "cotton_photos"),    ("post", "cotton_posts"),    ("project", "cotton_memory_projects"),    ("prompt", "cotton_prompts"),    ("pull", "cotton_repo_pulls"),    ("release", "cotton_repo_releases"),    ("repo_comment", "cotton_repo_comments"),    ("repository", "cotton_repos"),    ("run", "cotton_repo_runs"),    ("secret", "cotton_secrets"),    ("session", "cotton_sessions"),    ("session_message", "cotton_session_messages"),    ("statement", "cotton_money_statements"),    ("statement_line", "cotton_money_statement_lines"),    ("story", "cotton_stories"),    ("thought", "cotton_inbox_items"),    ("thread", "cotton_msg_threads"),    ("todo", "cotton_todos"),    ("todo_recurrence", "cotton_todo_recurrences"),    ("toolkit", "cotton_toolkits"),    ("transaction", "cotton_money_transactions"),    ("video", "cotton_videos"),];/// What every column a person adds to a shipped table is keyed under, and no/// shipped column ever is (`cotton_core::definitions::owner`).pub const OWN_PREFIX: &str = "own_";/// The columns a person added to shipped tables on this file, by the shipped/// table's store table: `(column, SQL type, codec)` in the definition's/// order. They are real columns of that table (architect, 13 Oct 2026), added/// by the same add-only step as a made table's ([`step_own`]), on the table/// [`BUILTIN_STORES`] names.pub fn own_columns(db: &Driver) -> Result<BTreeMap<String, Vec<(String, String, Codec)>>> {    own_columns_of(db, None)}fn own_columns_of(db: &Driver, only: Option<&BTreeSet<String>>) -> Result<BTreeMap<String, Vec<OwnColumn>>> {    let mut out: BTreeMap<String, Vec<OwnColumn>> = BTreeMap::new();    for (id, text) in definition_texts(db, only)? {        if let Some((store, own)) = own_of(&id, &text) {            out.entry(store.to_owned()).or_default().extend(own);        }    }    Ok(out)}/// The store a shipped table's definition row `id` names and the columns a/// person added to it, from the row's text; `None` for any other row.fn own_of(id: &str, text: &str) -> Option<(&'static str, Vec<OwnColumn>)> {    let store = BUILTIN_STORES.iter().find(|(table, _)| *table == id).map(|(_, store)| *store)?;    let definition = serde_json::from_str::<serde_json::Value>(text).ok()?;    if definition["id"].as_str() != Some(id) || !super::package_tables::has_engine(&definition) {        return None;    }    let mut own = Vec::new();    for column in definition["columns"].as_array().into_iter().flatten() {        let (Some(key), Some(kind)) = (column["key"].as_str(), column["type"].as_str()) else { continue };        let named = key.strip_prefix(OWN_PREFIX).is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'));        if !named {            continue;        }        let sql_type = match kind {            "number" | "bytes" => "REAL",            "amount" | "bool" => "INTEGER",            _ => "TEXT",        };        own.push((key.to_owned(), sql_type.to_owned(), codec_for(key, sql_type, Some(kind))));    }    Some((store, own))}/// Add every column a person added to a shipped table that the file does not/// hold yet, in place — add-only, as a made table's step: a column already/// there of another type is refused, never changed.pub fn step_own(db: &Driver) -> Result<(StepReport, Vec<(String, String)>)> {    step_own_of(db, None)}fn step_own_of(db: &Driver, only: Option<&BTreeSet<String>>) -> Result<(StepReport, Vec<(String, String)>)> {    let mut report = StepReport::default();    let mut refused = Vec::new();    for (table, own) in own_columns_of(db, only)? {        let held = file_columns(db, &table)?;        if held.is_empty() {            continue;        }        for (name, sql_type, _) in own {            match held.iter().find(|c| c.name == name) {                Some(had) if had.sql_type.eq_ignore_ascii_case(&sql_type) => {}                Some(had) => refused.push((table.clone(), format!("{table}.{name} is {} here and {sql_type} in the definition; a column only adds", had.sql_type))),                None => {                    db.exec(&format!("ALTER TABLE \"{table}\" ADD COLUMN \"{name}\" {sql_type}"))?;                    report.added.push(format!("{table}.{name}"));                }            }        }    }    Ok((report, refused))}/// A table statement as this build wrote it: the file's statement without/// the columns added in place — a person's (`, "own_<key>" TYPE`) and those/// a copy keeps for the object's definition (`, "<key>" TYPE CONSTRAINT/// served NULL`, [`SERVED_MARK`]), which `ALTER TABLE … ADD COLUMN` spliced/// in — and those columns' declarations. The start-up move and every check/// that the file is this build's shape compare the first, and carry the/// second.pub fn without_added(sql: &str) -> (String, Vec<String>) {    let mut kept = sql.to_owned();    let mut own = Vec::new();    // A served column first: its declaration runs to its mark, and its key    // may itself begin `own_`.    while let Some(mark) = kept.find(SERVED_MARK) {        let end = mark + SERVED_MARK.len();        let Some(start) = kept[..mark].rfind(", \"") else { break };        own.push(kept[start + 2..end].to_owned());        kept.replace_range(start..end, "");    }    let marker = format!(", \"{OWN_PREFIX}");    while let Some(at) = kept.find(&marker) {        let rest = &kept[at + 2..];        let end = rest.find([',', ')']).map_or(rest.len(), |end| end);        own.push(rest[..end].trim().to_owned());        kept.replace_range(at..at + 2 + end, "");    }    (kept, own)}/// The tables definitions are kept in: their shape is the build's alone.const DEFINITIONS_STORES: [&str; 3] = ["cotton_table_definitions", "cotton_tool_definitions", "cotton_board_definitions"];/// The spec of `table` in THIS file: the compiled one for a core or built-in/// table, else the package table this file's definitions declare and the file/// holds, with the columns it holds. `None` for a table this file does not/// know — which may be a package table whose definition has not arrived.pub fn spec_on(db: &Driver, table: &str) -> Result<Option<&'static TableSpec>> {    let compiled = super::specs::spec_for(table);    // The definitions tables are the build's whole: no definition adds a    // column to them. And every write to `cotton_table_definitions` moves    // [`specs_stamp`], so asking the package specs for each receipt of a    // batch of table definitions derived every package again per receipt —    // a fresh copy's 125 kit tables took half a minute to fold (28 Oct 2026).    if DEFINITIONS_STORES.contains(&table) {        return Ok(compiled);    }    let stamp = specs_stamp(db)?;    // A miss reads the one table asked, never every package table: a fresh    // copy's install moves the stamp with every tool, and reading every    // table's columns again for the one the fold asked was O(all tables)    // per tool (copy-installer-store, 8 Nov 2026).    let found = match db.package_specs_cached(&stamp, table) {        Some(found) => found,        None => {            let found = package_spec_of(db, table)?;            db.keep_package_spec(stamp, table, found);            found        }    };    // A shipped table is the build's, with the columns a person added to it.    Ok(found.or(compiled))}/// The package tables this file holds, by name: what the exchange hands over/// beside the compiled tables (`changes::known_tables_clause`).pub fn held_tables(db: &Driver) -> Result<Vec<String>> {    let stamp = specs_stamp(db)?;    if let Some(names) = db.package_names_cached(&stamp) {        return Ok(names.into_iter().filter(|name| super::specs::spec_for(name).is_none()).collect());    }    let specs = package_specs(db)?;    let names = specs.keys().filter(|name| super::specs::spec_for(name).is_none()).cloned().collect();    db.keep_package_specs(stamp, specs);    Ok(names)}/// What the package specs of this file were read at: the schema, and the/// definitions' count and latest writes (a shipped table's row names the/// columns a person added to it).fn specs_stamp(db: &Driver) -> Result<String> {    db.batch_fact("specs_stamp", || read_specs_stamp(db))}fn read_specs_stamp(db: &Driver) -> Result<String> {    Ok(db        .get(            "SELECT (SELECT schema_version FROM pragma_schema_version) AS s, count(*) AS n, \             max(_hlc) AS h, max(updated_at) AS u FROM cotton_table_definitions",            &[],        )?        .map(|row| {            format!(                "{}|{}|{}|{}",                row.int("s").unwrap_or(0),                row.int("n").unwrap_or(0),                row.text("h").unwrap_or_default(),                row.text("u").unwrap_or_default()            )        })        .unwrap_or_default())}/// Could `table` be a package table this file has not been given yet? A/// receipt for one waits (`newer-shape`) rather than being refused: its/// definition is on its way. Core and built-in names are not; nor is a/// local or a search-index name.pub fn may_arrive(table: &str) -> bool {    super::specs::spec_for(table).is_none()        && table.starts_with("cotton_")        && table.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')}/// The reason a receipt waits for a package shape this file does not hold.pub fn waits_for_shape(table: &str, column: Option<&str>) -> String {    match column {        Some(column) => format!(            "{}{table}.{column} comes with a package revision this file has not taken yet",            crate::rejected::NEWER_SHAPE        ),        None => format!(            "{}{table} comes with a package this file has not taken yet",            crate::rejected::NEWER_SHAPE        ),    }}/// After a fold that wrote definitions: step this file to the packages of/// the definitions whose STORAGE the fold changed — their declared tables or/// the columns a person added — and nothing else; when that changed its/// shape, fold the receipts that were waiting for it. `before` is each/// written definition's text as the fold found it (`None`: it was new), read/// by [`definition_texts`] ahead of the fold.////// A fold that changes one table's storage steps that table; one that/// changes a definition's looks, words or views alone steps none. Stepping/// every declared table on every definition fold was O(all tables) per/// tool a fresh copy installs (copy-installer-store, 8 Nov 2026). The launch/// path still steps the whole file ([`step_file`]).pub fn after_definitions(    db: &Driver,    now: &str,    before: &BTreeMap<String, Option<String>>,) -> Result<(StepReport, Vec<(String, String)>)> {    let written: BTreeSet<String> = before.keys().cloned().collect();    let after: BTreeMap<String, String> = definition_texts(db, Some(&written))?.into_iter().collect();    let storage = |id: &str, text: Option<&str>| text.map(|text| (declared_text(text), own_of(id, text)));    let changed: BTreeSet<String> = written        .into_iter()        .filter(|id| storage(id, before[id].as_deref()) != storage(id, after.get(id).map(String::as_str)))        .collect();    if changed.is_empty() {        return Ok((StepReport::default(), Vec::new()));    }    let (report, refused) = step_definitions(db, &changed)?;    if report.changed() && crate::rejected::keeps_newer_shape(db)? {        crate::rejected::fold_newer_shape(db, now)?;    }    Ok((report, refused))}#[cfg(test)]#[path = "package_shape_tests.rs"]mod tests;