Cotton code
816 lines · 37.8 KB · RustRaw
//! The ONE read of what a table's definition is ([`resolve_table`]), which//! the generic verbs and the app's own list ([`table_definitions`]) both//! answer through. Definitions are records only (72nd amendment): no start//! and no creation writes one; a tool arrives by `import_tool`, and a//! database with none opens, lists and syncs.use std::cell::RefCell;use std::collections::BTreeMap;use cotton_core::definitions::{    builtin_table_definitions, DatabaseKind, TableDefinition,    ToolDefinition, BUILTIN_DEFINITIONS_HASH, BUILTIN_DEFINITIONS_STAMP,};use rusqlite::types::Value as SqlValue;use serde_json::Value;use crate::mcp::dispatch::Ctx;use crate::mcp::protocol::ToolFailure;/// The synced table the table definitions live in.pub const TABLE_DEFINITIONS: &str = "cotton_table_definitions";/// The synced table the tool definitions live in.pub const TOOL_DEFINITIONS: &str = "cotton_tool_definitions";/// The job the server's start step writes as.pub const SEED_JOB: &str = "definitions";/// The byline the start step's writes carry (`job:<name>`).pub const SEED_LABEL: &str = "job:definitions";/// The byline an upgrade's Feedback rows carry.pub const UPGRADE_LABEL: &str = "Definition upgrade";// ── the read ────────────────────────────────────────────────────────────────/// One synced `cotton_table_definitions` row. Required fields are read strictly;/// the definition text is parsed and validated by the resolver.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DefinitionRow {    pub id: String,    pub definition: String,    /// The row's `builtin` column — what the seed wrote it as.    pub builtin: bool,    /// A person edited this table's instructions.    pub instructions_edited: bool,    /// The definitions revision the row was written at.    pub builtin_hash: Option<String>,    pub builtin_stamp: Option<i64>,}/// A stored definition's text parsed, and shared: remembered by its row id/// and exact text, so the same text is parsed once a process. A preflight/// reads every definition the file holds to judge a package beside them, and/// a fresh copy installs its kit one tool at a time: each tool parsed every/// definition the tools before it wrote (copy-installer-store, 8 Nov 2026)./// A changed definition is a new text; `None` for a text that does not parse.pub fn parsed(id: &str, text: &str) -> Option<std::sync::Arc<TableDefinition>> {    type Memo = std::collections::HashMap<String, (String, std::sync::Arc<TableDefinition>)>;    static MEMO: std::sync::LazyLock<std::sync::Mutex<Memo>> = std::sync::LazyLock::new(Default::default);    if let Some((held, definition)) = MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(id) {        if held == text {            return Some(definition.clone());        }    }    let definition = std::sync::Arc::new(TableDefinition::from_json(text).ok()?);    MEMO.lock()        .unwrap_or_else(std::sync::PoisonError::into_inner)        .insert(id.to_owned(), (text.to_owned(), definition.clone()));    Some(definition)}/// A definition row this build could not read. The phone drains these after a/// call into its retained Debug failures, while the resolver keeps reading the/// rest of the file.#[derive(Debug, Clone, PartialEq, Eq)]pub struct DefinitionDiagnostic {    pub id: String,    pub revision: Option<i64>,    pub bundled_revision: i64,    pub cause: String,}thread_local! {    static DEFINITION_DIAGNOSTICS: RefCell<Vec<DefinitionDiagnostic>> = const { RefCell::new(Vec::new()) };}/// Take definition failures found on this thread since the previous drain.pub fn take_definition_diagnostics() -> Vec<DefinitionDiagnostic> {    DEFINITION_DIAGNOSTICS.with(|diagnostics| std::mem::take(&mut *diagnostics.borrow_mut()))}fn definition_unreadable(row: &DefinitionRow, cause: String) {    DEFINITION_DIAGNOSTICS.with(|diagnostics| {        let mut diagnostics = diagnostics.borrow_mut();        if diagnostics.len() < 128 {            diagnostics.push(DefinitionDiagnostic {                id: row.id.clone(),                revision: row.builtin_stamp,                bundled_revision: BUILTIN_DEFINITIONS_STAMP,                cause,            });        }    });}/// What table `id` is, given what this build ships at that id and the synced/// row at it — the ONE answer, which the generic verbs/// (`handlers::tables::definition`) and the app's list ([`table_definitions`])/// both take, so the list can never offer a table the verbs refuse.////// - **A built-in row at an id this build ships is the SHIPPED definition**:///   nothing a device wrote into it can widen what a read selects or a write///   reaches. The row contributes one thing, the instructions, and only when///   a person edited them (the same string `plan_seed` keeps across a///   reseed) — so only its id and instructions are read, never the format of///   the revision that wrote it; JSON that does not parse, or names another///   id, is still refused./// - **Any other row is VALIDATED**: JSON that does not parse, a definition///   that does not validate, or one naming another id is refused whole, never///   read around. A valid table a person defined stands — at a built-in's id///   too, which is the seed's `UserTableHoldsId`./// - **A row that says it is a built-in this build does not ship is a///   RETIRED built-in** (Stores' order, product and store, 11 Oct 2026): it is///   no definition at all — removed means removed — so the id is free for a///   package's own table, and nothing is refused over it./// - **A capability is gated by presence**: a table a person or a package///   defined that names an engine this build does not have is drawn///   data-only, never refused over what the build lacks./// - No row: no tool draws it — the typed refusal///   (`cotton_core::definitions::NO_TOOL_DRAWS_THIS_TABLE`), never the///   shipped file.pub fn resolve_table(    id: &str,    shipped: Option<&TableDefinition>,    row: Option<&DefinitionRow>,) -> Result<TableDefinition, String> {    // No row is no tool drawing it: never a fallback to the shipped file. The    // cause is the kind; a reader with the database at hand says it with    // [`no_tool_draws`].    let Some(row) = row.filter(|row| !retired_builtin(row, shipped)) else {        return Err(cotton_core::definitions::NO_TOOL_DRAWS_THIS_TABLE.to_string());    };    let unreadable =        |error: String| format!("the definition of table {id:?} cannot be read: {error}");    // A BUILT-IN IS DRAWN AS THIS BUILD SHIPS IT, and its row lends only the    // instructions a person edited — so only its id and instructions are read    // from it, never its format, as the seed reads one (`seed_definitions`).    // The row is in the shape of whichever revision the server seeded, and a    // device a revision behind or ahead cannot decode every key of it: when    // 0f76239c1 wrote `tool` without `tables`, a phone a build behind refused    // its whole Todos list over a key it then threw away.    if let (true, Some(shipped)) = (row.builtin, shipped) {        #[derive(serde::Deserialize)]        struct BuiltinContent {            id: String,            #[serde(default)]            instructions: Option<String>,        }        let content: BuiltinContent = serde_json::from_str(&row.definition)            .map_err(|error| unreadable(format!("definition JSON does not parse: {error}")))?;        if content.id != id {            return Err(unreadable(format!("it names itself {:?}", content.id)));        }        // The small content read above deliberately accepts a newer row's        // foreign keys. It must still reject a value that no definition can        // decode at all, so that the caller can retain its diagnostic — read        // over this build's shipped shape, so a row from before this build        // added a word (`viewer.words.fetching`, 16 Oct 2026) is not refused        // for the key it could not have had.        let mut over_shipped: Value = serde_json::from_str(&row.definition)            .map_err(|error| unreadable(format!("definition JSON does not parse: {error}")))?;        let shipped_value = serde_json::to_value(shipped).map_err(|error| unreadable(error.to_string()))?;        // A row an OLDER revision wrote lends nothing but its instructions and        // the edits a person made (`with_edits`, which keeps each edit that        // still reads and lets the rest go): every other look key is that        // revision's shape, thrown away here, so it is read as this build        // ships it — never refused. Money's accounts row as the schema-139        // builds wrote it (`"create": false`, a `parts` the next revision        // removed) refused the whole table on 294 over a key it then threw        // away (295 F row 69, walker294). Its id and its columns are still        // read: a row whose columns do not decode is broken, not older.        let newer_or_same = row.builtin_hash.as_deref() == Some(BUILTIN_DEFINITIONS_HASH)            || row.builtin_stamp.is_some_and(|stamp| stamp > BUILTIN_DEFINITIONS_STAMP);        let mut checked = over_shipped.clone();        if !newer_or_same {            if let (Some(checked), Some(shipped)) = (checked.as_object_mut(), shipped_value.as_object()) {                checked.retain(|key, _| key == "id" || key == "columns");                for (key, value) in shipped {                    checked.entry(key.clone()).or_insert_with(|| value.clone());                }            }        }        cotton_core::definitions::fill_missing_keys(&mut checked, &shipped_value);        cotton_core::definitions::fill_missing_keys(&mut over_shipped, &shipped_value);        TableDefinition::from_json(&checked.to_string())            .map_err(|error| unreadable(error.to_string()))?;        // Look resolution must read the same completed shape as validation,        // so an edited viewer keeps its words when a sibling word is added.        let carried = DefinitionRow { definition: over_shipped.to_string(), ..row.clone() };        let row = &carried;        let mut definition = shipped.clone();        // A newer build may already carry an equal overlay and retire its        // edit marker. Older devices still need that newer product's words        // until their own build carries it, just like its presentation keys.        if row.instructions_edited || row.builtin_stamp.is_some_and(|stamp| stamp > BUILTIN_DEFINITIONS_STAMP) {            definition.instructions = content.instructions;            definition                .validate()                .map_err(|error| unreadable(error.to_string()))?;        }        // A row from this build or a newer one can lend every look key, including keys this build        // preserves opaquely. `drawn_from_row` overlays those keys one at a time,        // so foreign keys and foreign columns are ignored instead of making        // the phone refuse the whole page.        if row.builtin_hash.as_deref() == Some(BUILTIN_DEFINITIONS_HASH) || row.builtin_stamp.is_some_and(|stamp| stamp > BUILTIN_DEFINITIONS_STAMP) {            if let Some(drawn) = drawn_from_row(&definition, &row.definition) {                return Ok(drawn);            }        }        // A shipping checkout may be ahead of the serving build. Explicit        // owner edits survive that boundary through the same validated merge        // the seed uses; reading must not silently drop them before seeding.        let raw: Value = serde_json::from_str(&row.definition).map_err(|error| unreadable(error.to_string()))?;        let edited = raw.get("edited").cloned().and_then(|value| serde_json::from_value::<Vec<String>>(value).ok()).unwrap_or_default();        if !edited.is_empty() {            definition = cotton_core::definitions::with_edits(&definition, &raw, &edited).0;        }        return Ok(definition);    }    let parsed = TableDefinition::from_json(&row.definition)        .map_err(|error| unreadable(error.to_string()))?;    parsed        .validate()        .map_err(|error| unreadable(error.to_string()))?;    if parsed.id != id {        return Err(unreadable(format!("it names itself {:?}", parsed.id)));    }    if parsed.engine.is_none() {        return Ok(parsed);    }    // A kit table this build carries: its engine's binding is code, and the    // edits a person made here (added or hidden columns, words) ride on it,    // as they do on a built-in's row.    if let Some(shipped) = shipped {        // The row's look keys (a view order, words) overlay the compiled        // definition one at a time, as a built-in's row of this build does.        if let Some(drawn) = drawn_from_row(shipped, &row.definition) {            return Ok(drawn);        }        let raw: Value = serde_json::from_str(&row.definition).map_err(|error| unreadable(error.to_string()))?;        let edited = raw.get("edited").cloned().and_then(|value| serde_json::from_value::<Vec<String>>(value).ok()).unwrap_or_default();        if edited.is_empty() {            return Ok(shipped.clone());        }        return Ok(cotton_core::definitions::with_edits(shipped, &raw, &edited).0);    }    // A package's row of a built-in table keeps the engine its schema is    // compiled with: the binding is code, never the row's claim.    if parsed.has_engine() {        return Ok(parsed);    }    let mut data_only = parsed;    data_only.builtin = false;    data_only.engine = None;    Ok(data_only)}/// A row that says it is a built-in at an id this build no longer ships — what/// a retired built-in leaves on every file seeded before it went. The seed only/// writes the ids it ships, so the row stays; it is read as no definition.pub fn retired_builtin(row: &DefinitionRow, shipped: Option<&TableDefinition>) -> bool {    row.builtin && shipped.is_none()}/// The refusal of a read over a table no tool in this database draws: typed/// [`cotton_core::definitions::NO_TOOL_DRAWS_THIS_TABLE`], said in the/// database's own `refusal` line.pub fn no_tool_draws(db: &cotton_store::driver::Driver, workspace_id: &str) -> ToolFailure {    ToolFailure::kinded(        cotton_core::definitions::NO_TOOL_DRAWS_THIS_TABLE,        cotton_core::definitions::no_tool_draws_this_table(&crate::presentation::line_rows(db, workspace_id)),    )}/// [`resolve_table`]'s answer, held to the open file: a built-in drawn from/// its stored row that names a column its store table in THIS file does not/// have — the file is behind the definition, or the row came from a newer/// Mac — is drawn as this build compiles it instead, with one log line naming/// the table and the column. The row is left exactly as it is, so it draws/// again once the file moves. Never a failed open or a blank screen over it:/// a read selecting that column would fail the whole list.pub fn resolve_table_on_file(    db: &cotton_store::driver::Driver,    id: &str,    shipped: Option<&TableDefinition>,    row: Option<&DefinitionRow>,) -> Result<TableDefinition, ToolFailure> {    let resolved = match resolve_table(id, shipped, row) {        Ok(resolved) => resolved,        Err(cause) => {            // No row is no tool drawing the table: the typed refusal, never            // the shipped file (72nd amendment, 21 Oct 2026).            let Some(row) = row else { return Err(ToolFailure::new(cause)) };            definition_unreadable(row, cause.clone());            // A broken stored row never blanks a built-in page: what the app            // carries is a complete, safe definition for the table.            if let Some(shipped) = shipped {                return Ok(shipped.clone());            }            return Err(ToolFailure::new(cause));        }    };    // Only a stored row can name what this build's file lacks; a definition    // drawn as compiled is the build's own, and nothing is left to fall back to.    let Some(compiled) = shipped.filter(|compiled| **compiled != resolved) else {        return Ok(resolved);    };    let Some(store) = cotton_core::definitions::builtin_store_table(id).filter(|_| resolved.has_engine()) else {        return Ok(resolved);    };    let file = file_columns(db, store)?;    let Some(missing) = column_the_file_lacks(&resolved, compiled, store, &file) else {        return Ok(resolved);    };    say_once(id, missing);    Ok(compiled.clone())}/// The first column `resolved` (a built-in kept in `store`) keeps in a column/// of `store` that `file` — that table's columns in the open file — lacks./// A person's own column is added to `store` by the package step when its/// definition lands (`package_shape::step_own`) and read only once there, and/// a column this build/// answers without a store column (computed, device-answered, a link list)/// needs nothing of the file; every other column must be there.pub fn column_the_file_lacks<'a>(    resolved: &'a TableDefinition,    compiled: &TableDefinition,    store: &str,    file: &std::collections::BTreeSet<String>,) -> Option<&'a str> {    let spec = cotton_store::schema::specs::columns_of(store).unwrap_or(&[]);    resolved        .columns        .iter()        .map(|column| column.key.as_str())        .find(|key| {            if cotton_core::definitions::owner::is_own_column(key) {                return false;            }            let answered_without_the_file =                compiled.column(key).is_some() && !spec.iter().any(|(name, _)| name == key);            !answered_without_the_file && !file.contains(*key)        })}/// The columns `table` has in the open file — empty when it has no such table.fn file_columns(    db: &cotton_store::driver::Driver,    table: &str,) -> Result<std::collections::BTreeSet<String>, ToolFailure> {    Ok(db        .all("SELECT name FROM pragma_table_info(?)", &[SqlValue::Text(table.to_string())])        .map_err(|error| ToolFailure::new(error.to_string()))?        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect())}/// One line per table and column for the life of the process: the list is/// read on every screen, and a line per read would bury the one that matters.fn say_once(table: &str, column: &str) {    static SAID: std::sync::Mutex<std::collections::BTreeSet<(String, String)>> =        std::sync::Mutex::new(std::collections::BTreeSet::new());    let first = SAID        .lock()        .map(|mut said| said.insert((table.to_string(), column.to_string())))        .unwrap_or(true);    if first {        tracing::warn!(            table,            column,            "definitions: the stored definition of {table} names column {column}, which this file does not have; drawing the built-in until the file moves"        );    }}/// Whether `resolved` draws differently from `shipped` in any of/// the writable definition keys.fn draws_differently(shipped: &TableDefinition, resolved: &TableDefinition) -> bool {    let (Ok(shipped), Ok(resolved)) = (serde_json::to_value(shipped), serde_json::to_value(resolved)) else {        return false;    };    shipped.as_object().into_iter().flat_map(|o| o.keys()).chain(resolved.as_object().into_iter().flat_map(|o| o.keys())).filter(|key| cotton_core::definitions::writable_definition_key(key)).any(|key| shipped.get(key) != resolved.get(key))}/// `shipped` with the writable definition keys taken from the stored row's JSON,/// when the row holds any of them and the result validates.fn drawn_from_row(shipped: &TableDefinition, row: &str) -> Option<TableDefinition> {    let row: Value = serde_json::from_str(row).ok()?;    let mut merged = serde_json::to_value(shipped).ok()?;    let mut changed = false;    let mut keys: Vec<&str> = merged.as_object()?.keys().chain(row.as_object()?.keys()).map(String::as_str).filter(|key| cotton_core::definitions::writable_definition_key(key) && *key != "instructions").collect();    keys.sort_unstable();    keys.dedup();    let keys: Vec<String> = keys.into_iter().map(str::to_string).collect();    for key in &keys {        // An act or a stack on the row is taken onto the shipped file, so a        // row naming a list or a filter this build does not offer draws only        // what it does (`owner::on_shipped`); a key that cannot is as shipped.        let Ok(from_row) = cotton_core::definitions::owner::on_shipped(            shipped,            key,            &row.get(key).cloned().unwrap_or(Value::Null),            cotton_core::definitions::owner::Against::Upgrade,        ) else {            continue;        };        let current = merged.get(key).cloned().unwrap_or(Value::Null);        if from_row != current {            match from_row {                Value::Null => {                    merged.as_object_mut()?.remove(key);                }                value => {                    merged.as_object_mut()?.insert(key.to_string(), value);                }            }            changed = true;        }    }    if !changed {        return None;    }    let drawn: TableDefinition = serde_json::from_value(merged).ok()?;    drawn.validate().ok()?;    Some(drawn)}/// The synced table-definition rows, one id or all of them.pub fn definition_rows(    ctx: &Ctx<'_>,    only: Option<&str>,) -> Result<Vec<DefinitionRow>, ToolFailure> {    definition_rows_from_driver(ctx.read.driver(), ctx.workspace_id, only)}/// [`definition_rows`] before any Ctx exists — a worker's read of the file.pub fn definition_rows_from_driver(    db: &cotton_store::driver::Driver,    workspace: &str,    only: Option<&str>,) -> Result<Vec<DefinitionRow>, ToolFailure> {    let mut sql = format!(        "SELECT id, definition, builtin, instructions_edited, builtin_hash, builtin_stamp FROM {TABLE_DEFINITIONS} \         WHERE workspace_id = ?"    );    let mut params = vec![SqlValue::Text(workspace.to_string())];    if let Some(id) = only {        sql.push_str(" AND id = ?");        params.push(SqlValue::Text(id.to_string()));    }    sql.push_str(" ORDER BY id");    db.all(&sql, &params)        .map_err(|error| ToolFailure::new(error.to_string()))?        .iter()        .map(|row| {            Ok(DefinitionRow {                id: required_text(row, "id")?.to_string(),                definition: required_text(row, "definition")?.to_string(),                builtin: required_flag(row, "builtin")?,                instructions_edited: required_flag(row, "instructions_edited")?,                builtin_hash: row.text("builtin_hash").map(str::to_owned),                builtin_stamp: row.int("builtin_stamp"),            })        })        .collect()}/// A definition refusal in the catalogue response.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pub struct Refused {    pub id: String,    pub reason: String,}/// The definition catalogue. A malformed non-built-in row is named in/// `refused`; every readable definition still answers.#[derive(Debug, Clone, PartialEq, serde::Serialize)]pub struct Definitions<T> {    pub definitions: Vec<T>,    pub refused: Vec<Refused>,    /// Built-ins drawn from their stored row rather than as this build ships    /// them (the writable definition keys) — the ids a device that keeps its own    /// copies of the built-ins takes from this answer instead.    #[serde(skip_serializing_if = "Vec::is_empty")]    pub drawn_from_rows: Vec<String>,    /// Built-ins whose stored row could not be read, each drawn as this build    /// ships it instead, with why — never a blank page, and said once in    /// Feedback by the catalogue (`definitions.catalogue`).    #[serde(skip_serializing_if = "Vec::is_empty")]    pub fell_back: Vec<Refused>,}/// Every table definition, as [`resolve_table`] answers each id: the shipped/// built-ins in the order the app ships them, each at its place even when a/// table a person defined holds the id, then every other synced row by id.pub fn table_definitions(ctx: &Ctx<'_>) -> Result<Definitions<TableDefinition>, ToolFailure> {    table_definitions_from_driver(ctx.read.driver(), ctx.workspace_id)}/// [`table_definitions`] before any Ctx exists — the capture sweep reads the/// tables it may file into while it builds its prompt.pub fn table_definitions_from_driver(    db: &cotton_store::driver::Driver,    workspace: &str,) -> Result<Definitions<TableDefinition>, ToolFailure> {    shared_table_definitions_from_driver(db, workspace).map(|definitions| (*definitions).clone())}/// Product definitions before database visibility is applied. Export keeps/// conditional links and views for the receiving database to resolve, and/// reads no database-kind or record state into a package or shipping commit.pub fn export_table_definitions_from_driver(    db: &cotton_store::driver::Driver,    workspace: &str,) -> Result<Definitions<TableDefinition>, ToolFailure> {    resolve_all(db, definition_rows_from_driver(db, workspace, None)?, None)}/// Borrow the existing validated catalogue within a composed read. A consumer/// which only reads definitions need not deep-copy every table and package.pub fn shared_table_definitions(ctx: &Ctx<'_>) -> Result<std::sync::Arc<Definitions<TableDefinition>>, ToolFailure> {    shared_table_definitions_from_driver(ctx.read.driver(), ctx.workspace_id)}pub fn shared_table_definitions_from_driver(    db: &cotton_store::driver::Driver,    workspace: &str,) -> Result<std::sync::Arc<Definitions<TableDefinition>>, ToolFailure> {    let rows = definition_rows_from_driver(db, workspace, None)?;    let kind = database_kind(db)?;    // A file in memory is keyed by its handle: every fold's derive pass asks    // for the catalogue twice, and resolving it afresh each time on a test's    // in-memory file cost the mail suites forty minutes (run 6347).    let file = db.file_key();    // `schema_version` moves with every DDL, so a file whose store tables    // gained or lost a column (what `resolve_table_on_file` reads) misses.    let schema = db        .get("PRAGMA schema_version", &[])        .map_err(|error| ToolFailure::new(error.to_string()))?        .and_then(|row| row.int("schema_version"))        .ok_or_else(|| ToolFailure::new("SQLite did not answer its schema version"))?;    let key = ResolvedKey { file, workspace: workspace.to_string(), schema, kind };    if cotton_core::flavor::single_database() { return resolve_all(db, rows, Some(kind)).map(std::sync::Arc::new); }    if let Some(hit) = resolved_cache_lookup(&key, &rows) {        for (row, cause) in &hit.diagnostics {            definition_unreadable(row, cause.clone());        }        return Ok(std::sync::Arc::clone(&hit.definitions));    }    let before = DEFINITION_DIAGNOSTICS.with(|diagnostics| diagnostics.borrow().len());    let definitions = std::sync::Arc::new(resolve_all(db, rows.clone(), Some(kind))?);    let diagnostics = DEFINITION_DIAGNOSTICS.with(|diagnostics| {        diagnostics.borrow()[before.min(diagnostics.borrow().len())..]            .iter()            .filter_map(|diagnostic| {                let row = rows.iter().find(|row| row.id == diagnostic.id)?;                Some((row.clone(), diagnostic.cause.clone()))            })            .collect()    });    resolved_cache_keep(key, std::sync::Arc::new(Resolved { rows, definitions: definitions.clone(), diagnostics }));    Ok(definitions)}/// Which file, database and shape a set of resolved definitions was read from.#[derive(Debug, Clone, PartialEq, Eq)]struct ResolvedKey {    file: String,    workspace: String,    schema: i64,    /// What kind of database the file is: a link or view standing in the    /// other kind is left out of what it resolves ([`DatabaseKind`]).    kind: DatabaseKind,}/// The kind of database `db` is, as a definition's `when` names it: a/// project's (shared) file, else the personal one — a file whose kind is not/// yet written is the personal database's, as adding a tool reads it.fn database_kind(db: &cotton_store::driver::Driver) -> Result<DatabaseKind, ToolFailure> {    match cotton_store::link_rule::file_kind(db) {        Ok(cotton_store::link_rule::FileKind::Shared) => Ok(DatabaseKind::Project),        Ok(_) => Ok(DatabaseKind::Personal),        Err(error) => Err(ToolFailure::new(format!("the file's kind could not be read: {error}"))),    }}/// One resolution of every table definition, and exactly the rows it read.struct Resolved {    rows: Vec<DefinitionRow>,    definitions: std::sync::Arc<Definitions<TableDefinition>>,    /// The unreadable rows this resolution named, said again on every hit so    /// a drain (`take_definition_diagnostics`) after a cached read still    /// reports them.    diagnostics: Vec<(DefinitionRow, String)>,}/// How many resolutions the process keeps: a device has a handful of/// databases open and a server a few more; the oldest goes first.const RESOLVED_KEPT: usize = 8;static RESOLVED: std::sync::Mutex<Vec<(ResolvedKey, std::sync::Arc<Resolved>)>> = std::sync::Mutex::new(Vec::new());fn resolved_cache_lookup(key: &ResolvedKey, rows: &[DefinitionRow]) -> Option<std::sync::Arc<Resolved>> {    let kept = RESOLVED.lock().ok()?;    kept.iter()        .find(|(at, resolved)| at == key && resolved.rows == rows)        .map(|(_, resolved)| std::sync::Arc::clone(resolved))}fn resolved_cache_keep(key: ResolvedKey, resolved: std::sync::Arc<Resolved>) {    let Ok(mut kept) = RESOLVED.lock() else { return };    kept.retain(|(at, _)| *at != key);    if kept.len() >= RESOLVED_KEPT {        kept.remove(0);    }    kept.push((key, resolved));}/// Resolve every table definition from `rows` against the open file.fn resolve_all(    db: &cotton_store::driver::Driver,    rows: Vec<DefinitionRow>,    kind: Option<DatabaseKind>,) -> Result<Definitions<TableDefinition>, ToolFailure> {    let shipped = builtin_table_definitions();    let rows: BTreeMap<String, DefinitionRow> = rows        .into_iter()        .filter(|row| {            let built = shipped.iter().find(|definition| definition.id == row.id);            !retired_builtin(row, built)        })        .map(|row| (row.id.clone(), row))        .collect();    // Only what a tool here draws: a shipped table with no row is no tool's.    let mut ids: Vec<&str> = shipped        .iter()        .map(|definition| definition.id.as_str())        .filter(|id| rows.contains_key(*id))        .collect();    ids.extend(        rows.keys()            .map(String::as_str)            .filter(|id| !shipped.iter().any(|definition| definition.id == *id)),    );    let mut out = Definitions {        definitions: Vec::new(),        refused: Vec::new(),        drawn_from_rows: Vec::new(),        fell_back: Vec::new(),    };    let workspace = if cotton_core::flavor::single_database() && kind.is_some() { db.get("SELECT workspace_id FROM _meta", &[]).ok().flatten().and_then(|row| row.text("workspace_id").map(str::to_string)).unwrap_or_default() } else { String::new() };    for id in ids {        if !workspace.is_empty() && crate::home_arrangement::require_table(db, &workspace, id).is_err() { continue; }        let built = shipped.iter().find(|definition| definition.id == id);        if let (Some(_), Some(row)) = (built, rows.get(id)) {            if let Err(cause) = resolve_table(id, built, Some(row)) {                out.fell_back.push(Refused { id: id.to_string(), reason: cause });            }        }        let mut resolved = match resolve_table_on_file(db, id, built, rows.get(id)) {            Ok(resolved) => resolved,            Err(error) => {                out.refused.push(Refused { id: id.to_string(), reason: error.to_string() });                continue;            }        };        if let Some(built) = built.filter(|_| rows.get(id).is_some_and(|row| row.builtin)) {            if draws_differently(built, &resolved) {                out.drawn_from_rows.push(id.to_string());            }        }        if let Some(kind) = kind {            resolved.for_database(kind);        }        out.definitions.push(resolved);    }    Ok(out)}/// What contributes a list to a record page of `table`: every table here with/// a link column pointing at it, as [`cotton_core::definitions::contributors`]/// finds them — built-ins in shipped order, then made tables by id.pub fn table_contributors(    ctx: &Ctx<'_>,    table: &str,) -> Result<Vec<cotton_core::definitions::contributors::Contributor>, ToolFailure> {    let tables = table_definitions(ctx)?.definitions;    if !tables.iter().any(|definition| definition.id == table) {        return Err(no_tool_draws(ctx.read.driver(), ctx.workspace_id));    }    Ok(cotton_core::definitions::contributors::contributors(&tables, table))}/// Every synced tool definition, validated the way a table definition is, by/// id. Nothing ships a tool yet, so a new file answers an empty list.pub fn tool_definitions(ctx: &Ctx<'_>) -> Result<Definitions<ToolDefinition>, ToolFailure> {    tool_definitions_from_driver(ctx.read.driver(), ctx.workspace_id)}/// The same per-row reader for session starts and packages, before any Ctx exists./// Every stored tool is read through the same typed validation, regardless of origin.pub fn tool_definitions_from_driver(    db: &cotton_store::driver::Driver,    workspace: &str,) -> Result<Definitions<ToolDefinition>, ToolFailure> {    let rows = db.all(        &format!("SELECT id, definition FROM {TOOL_DEFINITIONS} WHERE workspace_id = ? ORDER BY id"),        &[SqlValue::Text(workspace.into())],    ).map_err(|error| ToolFailure::new(error.to_string()))?;    let mut out = Definitions {        definitions: Vec::new(),        refused: Vec::new(),        drawn_from_rows: Vec::new(),        fell_back: Vec::new(),    };    for row in &rows {        let id = required_text(row, "id")?.to_string();        let unreadable =            |error: String| format!("the definition of tool {id:?} cannot be read: {error}");        let resolved = ToolDefinition::from_json(required_text(row, "definition")?)            .map_err(|error| unreadable(error.to_string()))            .and_then(|parsed| {                parsed                    .validate()                    .map_err(|error| unreadable(error.to_string()))?;                if parsed.views.iter().any(|view| view.visibility == "public") {                    cotton_core::definitions::tool_views::validate_public_reads(&parsed.views, &table_definitions_from_driver(db, workspace).map_err(|e| unreadable(e.to_string()))?.definitions).map_err(|e|unreadable(e.to_string()))?;                }                if parsed.id == id {                    Ok(parsed)                } else {                    Err(unreadable(format!("it names itself {:?}", parsed.id)))                }            });        out.definitions.push(resolved.map_err(ToolFailure::new)?);    }    Ok(out)}fn required_text<'a>(row: &'a cotton_store::driver::Row, key: &str) -> Result<&'a str, ToolFailure> {    row.text(key).ok_or_else(|| ToolFailure::new(format!("definition row requires text {key:?}")))}fn required_flag(row: &cotton_store::driver::Row, key: &str) -> Result<bool, ToolFailure> {    match row.get(key) {        Some(SqlValue::Integer(0)) => Ok(false),        Some(SqlValue::Integer(1)) => Ok(true),        _ => Err(ToolFailure::new(format!("definition row requires boolean {key:?}"))),    }}#[cfg(test)]mod tests {    use super::*;    use cotton_store::driver::Row;    // RULE: Missing and mistyped stored fields must fail rather than becoming empty text or false.    #[test]    fn definition_rows_require_text_and_integer_booleans() {        let absent = Row::default();        assert!(required_text(&absent, "id").is_err());        assert!(required_flag(&absent, "builtin").is_err());        for value in [            SqlValue::Null,            SqlValue::Text("1".into()),            SqlValue::Real(1.5),            SqlValue::Integer(2),        ] {            let row = Row::new(vec![("builtin".into(), value)]);            assert!(required_flag(&row, "builtin").is_err());        }        for (value, expected) in [(0, false), (1, true)] {            let row = Row::new(vec![("builtin".into(), SqlValue::Integer(value))]);            assert_eq!(required_flag(&row, "builtin").unwrap(), expected);        }    }    /// RULE: a column is the file's to hold unless it is a person's own (added by the package step, read once there) or one this build answers without a store column.    #[test]    fn what_a_definition_needs_of_the_file() {        let compiled = builtin_table_definitions().into_iter().find(|d| d.id == "todo").unwrap();        let store = cotton_core::definitions::builtin_store_table("todo").unwrap();        let spec = cotton_store::schema::specs::columns_of(store).unwrap();        let file: std::collections::BTreeSet<String> = spec.iter().map(|(name, _)| name.to_string()).collect();        assert_eq!(column_the_file_lacks(&compiled, &compiled, store, &file), None, "computed and device-answered columns need nothing of the file");        let with = |key: &str| {            let mut definition = compiled.clone();            definition.columns.push(serde_json::from_value(serde_json::json!({"key": key, "name": "Invented", "type": "text"})).unwrap());            definition        };        let newer = with("later_reading");        assert_eq!(column_the_file_lacks(&newer, &compiled, store, &file), Some("later_reading"));        let mut moved = file.clone();        moved.insert("later_reading".into());        assert_eq!(column_the_file_lacks(&newer, &compiled, store, &moved), None, "once the file moves it draws");        assert_eq!(column_the_file_lacks(&with("own_birth_city"), &compiled, store, &file), None, "a person's own column is the step's to add");        let stored = spec.iter().map(|(name, _)| *name).find(|name| compiled.column(name).is_some()).unwrap();        let behind: std::collections::BTreeSet<String> = file.iter().filter(|name| *name != stored).cloned().collect();        assert_eq!(column_the_file_lacks(&compiled, &compiled, store, &behind), Some(stored));    }}