Cotton code
448 lines · 15.4 KB · RustRaw
//! What history SHOWS, and what a restore puts back — one declaration per//! versioned kind. The port of `packages/core/src/engine/history/fields.ts`.//!//! The trigger snapshots the whole row, which is right: a column added next//! month lands in history for free. But a whole row is not a reading. Half of//! every snapshot is bookkeeping — ids, sync stamps, pipeline state — and a//! screen that drew all of it would bury the one sentence somebody changed//! under twenty rows nobody wrote. So the reading is declared, kind by kind,//! here.//!//! `restore` is the same list narrowed to what the kind's own service can//! honestly write back, or a written REASON it can write nothing. A reason,//! never a bare `false`: the screen says it out loud, and the next author//! reading this file learns why rather than guessing whether it was an//! oversight. (The primitives registry makes the same choice for the same//! reason.)//!//! A restore goes through the owning kind's service, never a row write, so it//! is an ordinary edit that happens to carry old words — it earns a version row//! of its own and it can itself be undone.//!//! The TypeScript's `Record<VersionRecordKind, HistoryKindSpec>` is a `const//! fn` with an exhaustive `match` here, so a kind added to the union without a//! declaration fails the BUILD. That is the gate the TypeScript needs a test//! for, and the failure it prevents is silent: a kind missing from the registry//! reads on screen as "this record has no history" while the trigger has been//! writing rows for it all along.use crate::constants::VersionRecordKind;use crate::rules::shell_lines::{self, LineRow};/// How one column is drawn, and whether it is worth a word-level diff.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum HistoryFieldForm {    /// A short line — shown whole, tinted as a whole when it changes.    Text,    /// Long text — diffed word by word, the changed spans tinted.    Prose,    /// An ISO instant.    Moment,    /// A calendar day (`YYYY-MM-DD`).    Day,    /// 0/1 or a boolean.    Flag,    Number,    /// A json column — an array or an object, shown as its stored text.    List,}impl HistoryFieldForm {    pub const fn as_str(self) -> &'static str {        match self {            HistoryFieldForm::Text => "text",            HistoryFieldForm::Prose => "prose",            HistoryFieldForm::Moment => "moment",            HistoryFieldForm::Day => "day",            HistoryFieldForm::Flag => "flag",            HistoryFieldForm::Number => "number",            HistoryFieldForm::List => "list",        }    }}impl std::fmt::Display for HistoryFieldForm {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// One column as history draws it: the reader's name for it and its form.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct HistoryField {    pub kind: VersionRecordKind,    pub column: &'static str,    /// The definition's name for the column; `None` says the line    /// `fields.<kind>.<column>` of set `history` ([`HistoryField::label`]).    pub named: Option<&'static str>,    pub form: HistoryFieldForm,}impl HistoryField {    /// The reader's name for the column, plain words, never the raw column:    /// the definition's name, or the `history` line in `lines`' words, the    /// kit's for a line they have none of.    #[must_use]    pub fn label(&self, lines: &[LineRow]) -> String {        self.named.map_or_else(            || {                let line = format!("fields.{}.{}", self.kind.as_str(), self.column);                shell_lines::resolve("history", &line, lines, &[]).unwrap_or_else(|| format!("history.{line}"))            },            str::to_string,        )    }}/// One column a kind's history shows, as declared here. A column the kind's/// built-in table definition names takes its label from the definition's/// `name` and its form from the definition's `type` (lane T7, 22 Oct 2026:/// history stops hand-listing what the definitions already say); only a/// column no definition names carries a hand label. A `date` column keeps a/// hand form, because the type does not say a day from an instant.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct FieldSpec {    pub column: &'static str,    /// A column no definition names: its label is the line    /// `fields.<kind>.<column>` of set `history`; `false` reads the    /// definition's name.    pub hand: bool,    /// The hand form; `None` reads it off the definition's column type.    pub form: Option<HistoryFieldForm>,}/// The columns a restore writes back, or the reason there are none.////// The TypeScript spells this `readonly string[] | string` and every reader/// asks `Array.isArray`. An enum says the same thing without the question: a/// refusal is a `Refusal`, not a string that happens not to be a list.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Restore {    /// Narrower than `fields` on purpose: history shows everything worth    /// reading, a restore writes only what the kind's service actually    /// accepts. A column a pipeline owns is shown and not restored — putting a    /// stale summary back would fight the worker that wrote it.    Columns(&'static [&'static str]),    /// The kind restores nothing; the sentence the screen says out loud is    /// the line `history.kind.<kind>` of set `refusal`    /// (`super::restorable::RestoreBlock::Kind`).    Refusal,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct HistoryKindSpec {    /// The table whose trigger writes this kind's rows.    pub table: &'static str,    pub fields: &'static [FieldSpec],    pub restore: Restore,}/// `f(column)` — a column no definition names, drawn as a short line; its/// label a `history` line.const fn f(column: &'static str) -> FieldSpec {    FieldSpec { column, hand: true, form: Some(HistoryFieldForm::Text) }}/// `ff(column, form)` — a column no definition names, in its form; its label/// a `history` line.const fn ff(column: &'static str, form: HistoryFieldForm) -> FieldSpec {    FieldSpec { column, hand: true, form: Some(form) }}/// `d(column)` — a column the kind's definition names: label and form both/// the definition's.const fn d(column: &'static str) -> FieldSpec {    FieldSpec { column, hand: false, form: None }}/// `dd(column, form)` — a definition's date column: its label the/// definition's, its form (a day or an instant) said here.const fn dd(column: &'static str, form: HistoryFieldForm) -> FieldSpec {    FieldSpec { column, hand: false, form: Some(form) }}use HistoryFieldForm::{Day, Flag, List, Moment, Number, Prose};const TODO: HistoryKindSpec = HistoryKindSpec {    table: "cotton_todos",    fields: &[        d("title"),        d("notes"),        d("status"),        dd("due_at", Moment),        dd("snoozed_until", Moment),        d("priority"),        dd("completed_at", Moment),    ],    // `status` and its paired stamps belong to `toggleTodo` / `dropTodo`, which    // date themselves from now — putting a completion back would date it wrong.    restore: Restore::Columns(&["title", "notes", "due_at", "priority"]),};const TODO_RECURRENCE: HistoryKindSpec = HistoryKindSpec {    table: "cotton_todo_recurrences",    fields: &[        f("title"),        ff("notes", Prose),        d("rrule"),        dd("dtstart", Moment),        d("paused"),        ff("priority", Number),    ],    restore: Restore::Refusal,};const EVENT: HistoryKindSpec = HistoryKindSpec {    table: "cotton_events",    fields: &[        d("title"),        d("notes"),        dd("starts_at", Moment),        dd("ends_at", Moment),        d("all_day"),        d("location"),        d("rrule"),        d("my_response"),    ],    restore: Restore::Columns(&[        "title",        "notes",        "starts_at",        "ends_at",        "all_day",        "location",        "rrule",    ]),};const NOTE: HistoryKindSpec = HistoryKindSpec {    table: "cotton_notes",    fields: &[        d("title"),        d("body"),        d("pinned"),        dd("archived_at", Moment),    ],    restore: Restore::Columns(&["title", "body"]),};const JOURNAL: HistoryKindSpec = HistoryKindSpec {    table: "cotton_notes",    fields: &[        f("title"),        ff("body", Prose),        ff("journal_date", Day),    ],    restore: Restore::Columns(&["title", "body"]),};const PERSON: HistoryKindSpec = HistoryKindSpec {    table: "cotton_people",    fields: &[        d("full_name"),        d("org"),        d("role_title"),        d("city"),        // `phones`/`emails` are no columns since v90: a handle is its own        // `cotton_person_handles` row, so a person's versions carry neither.        d("timezone"),        d("summary"),        d("birth_month"),        d("birth_day"),        d("birth_year"),    ],    // A summary has ONE writer (`summariesService.setSummary`, which carries    // its own provenance), and a birthday is written as one value through    // `birthdayColumns` rather than three loose numbers — so history shows    // both and restores neither.    restore: Restore::Columns(&[        "full_name",        "org",        "role_title",        "city",        "timezone",    ]),};const DOCUMENT: HistoryKindSpec = HistoryKindSpec {    table: "cotton_documents",    fields: &[        f("title"),        d("doc_type"),        d("issuer"),        dd("document_date", Day),        dd("period_start", Day),        dd("period_end", Day),        d("summary"),        f("status"),        // The one redaction in the schema: the snapshot carries the FACT that a        // password was set and never the password, so the document's own row        // stays the single place that secret lives.        ff("has_password", Flag),    ],    restore: Restore::Columns(&["title", "doc_type", "issuer", "document_date"]),};const MEMORY: HistoryKindSpec = HistoryKindSpec {    table: "cotton_memories",    fields: &[        ff("title", Prose),        f("status"),        f("visibility"),        f("machine"),        f("source"),    ],    // Only the sentence: a memory IS its sentence, and its status, its place    // in the owner's order and its review clock are acts of their own. Its    // projects and its pin left the row at v34 for the link table, which is    // not versioned — an arrangement is not an edit.    restore: Restore::Columns(&["title"]),};/// A money row's own facts stay restorable; its statement evidence does not/// become a second editable copy of the row.const TRANSACTION: HistoryKindSpec = HistoryKindSpec {    table: "cotton_money_transactions",    fields: &[        ff("occurred_on", Day),        f("description"),        f("counterparty_person_id"),        f("status"),        f("certainty"),        f("amount_known"),        f("repeat"),        f("between_us"),        f("moves_money"),        ff("tag", Prose),        ff("notes", Prose),        ff("due_date", Day),        ff("for_period", Day),        f("source"),    ],    restore: Restore::Columns(&[        "occurred_on",        "description",        "counterparty_person_id",        "notes",        "due_date",        "for_period",        "tag",        "between_us",        "moves_money",    ]),};const MESSAGE: HistoryKindSpec = HistoryKindSpec {    table: "cotton_msg_messages",    fields: &[        ff("body", Prose),        d("send_state"),        d("send_error"),        dd("sent_at", Moment),        ff("meta", List),    ],    // Rewinding an outbox state could send again or invent delivery evidence.    restore: Restore::Refusal,};// gen-kind: history-specs/// `HISTORY_KINDS[kind]` — total over the union by construction.pub const fn history_kind(kind: VersionRecordKind) -> &'static HistoryKindSpec {    match kind {        VersionRecordKind::Todo => &TODO,        VersionRecordKind::Event => &EVENT,        VersionRecordKind::Note => &NOTE,        VersionRecordKind::Journal => &JOURNAL,        VersionRecordKind::Person => &PERSON,        VersionRecordKind::TodoRecurrence => &TODO_RECURRENCE,        VersionRecordKind::Document => &DOCUMENT,        VersionRecordKind::Memory => &MEMORY,        VersionRecordKind::Transaction => &TRANSACTION,        VersionRecordKind::Message => &MESSAGE,        // gen-kind: history-kind    }}/// Every column history draws for a kind, in the order it draws them.pub fn history_columns(kind: VersionRecordKind) -> Vec<&'static str> {    history_kind(kind)        .fields        .iter()        .map(|field| field.column)        .collect()}/// The built-in table definition a kind's history reads its names from: the/// one whose id is the kind's.fn definition(kind: VersionRecordKind) -> Option<&'static crate::definitions::TableDefinition> {    crate::definitions::builtin_table_definitions()        .iter()        .find(|definition| definition.id == kind.as_str())}/// How a column of a definition's type is drawn in history.fn form_of(column_type: &crate::definitions::ColumnType) -> HistoryFieldForm {    use crate::definitions::ColumnType;    match column_type {        ColumnType::Longtext => HistoryFieldForm::Prose,        ColumnType::Bool => HistoryFieldForm::Flag,        ColumnType::Number | ColumnType::Amount => HistoryFieldForm::Number,        ColumnType::Date => HistoryFieldForm::Moment,        _ => HistoryFieldForm::Text,    }}/// One declared column, read: the definition's name and type where the/// declaration leaves them to it.fn resolve(kind: VersionRecordKind, spec: &FieldSpec) -> HistoryField {    let column = (!spec.hand || spec.form.is_none())        .then(|| definition(kind))        .flatten()        .and_then(|definition| definition.columns.iter().find(|column| column.key == spec.column));    let named = (!spec.hand).then(|| {        column            .and_then(|column| column.name.as_deref())            .unwrap_or_else(|| panic!("{kind}.{} has no hand label and no definition names it", spec.column))    });    let form = spec        .form        .or_else(|| column.map(|column| form_of(&column.column_type)))        .unwrap_or_else(|| panic!("{kind}.{} has no hand form and no definition types it", spec.column));    HistoryField { kind, column: spec.column, named, form }}/// Every column a kind's history shows, each with its label and form.pub fn history_fields(kind: VersionRecordKind) -> Vec<HistoryField> {    history_kind(kind).fields.iter().map(|spec| resolve(kind, spec)).collect()}pub const fn history_restore_columns(kind: VersionRecordKind) -> &'static [&'static str] {    match history_kind(kind).restore {        Restore::Columns(columns) => columns,        Restore::Refusal => &[],    }}pub const fn can_restore_kind(kind: VersionRecordKind) -> bool {    matches!(history_kind(kind).restore, Restore::Columns(_))}/// Why a kind cannot restore, in the words the screen says out loud.pub const fn restore_refusal(kind: VersionRecordKind) -> Option<super::restorable::RestoreBlock> {    match history_kind(kind).restore {        Restore::Refusal => Some(super::restorable::RestoreBlock::Kind(kind)),        Restore::Columns(_) => None,    }}pub fn history_field(kind: VersionRecordKind, column: &str) -> Option<HistoryField> {    history_kind(kind)        .fields        .iter()        .find(|field| field.column == column)        .map(|spec| resolve(kind, spec))}#[cfg(test)]#[path = "fields_tests.rs"]mod tests;