Cotton code
721 lines · 29.4 KB · RustRaw
//! Summaries — one paragraph about a record, and the provenance of whoever//! wrote it (spec 2026-08-29-cotton-projects-first-app-design.md §D6). The//! port of `packages/core/src/engine/summaries.ts`.//!//! ONE declaration of where a summary lives and what "has arrived since" means,//! because three surfaces ask: the app's page, the server's MCP read, and the//! tests. Two answers to "is this summary stale" is two different numbers on//! one screen.//!//! Pure. `now` and the arrival instants come through the seam — never a wall//! clock here, or the memo this feeds is new every frame and the tests are a//! time bomb with a computable detonation date.use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use cotton_store::protocol::js::{is_js_whitespace, parse_date_ms};use crate::constants::SummaryKind;/// What a WRITER may send (§D6: "≤ 1,200 characters").////// The COLUMN's ceiling is 4,000 (`SUMMARY_MAX_STORED_CHARS`, store), and the/// gap is deliberate: schema v15 folds `how_we_met` into the person's summary,/// `how_we_met` never had a length CHECK, and a constraint that refuses prose/// the owner already wrote is a migration that fails on their own file. So the/// product's cap is enforced here, at the seam, where a refusal can explain/// itself.////// Counted in UTF-16 code units, because `String.prototype.length` is: 601/// emoji are 1,202 characters to this rule and 601 to a Rust `chars()` count,/// and the phone and the server must refuse the same paragraph.pub const SUMMARY_MAX_CHARS: usize = 1200;/// What a staleness cue counts, per kind. The WORDS are each surface's own.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum SummaryStalenessNoun {    Note,    Message,    Email,    Record,}impl SummaryStalenessNoun {    pub const fn as_str(self) -> &'static str {        match self {            SummaryStalenessNoun::Note => "note",            SummaryStalenessNoun::Message => "message",            SummaryStalenessNoun::Email => "email",            SummaryStalenessNoun::Record => "record",        }    }}impl std::fmt::Display for SummaryStalenessNoun {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// Where "who wrote it, and when" lives.////// DECLARED rather than assumed. All four tables spell it the same way today/// ([`SUMMARY_PROVENANCE`] is the one literal), but the prose column already/// differs on one kind — a project's is `description` — and a registry that/// can say where the paragraph lives while hard-coding its stamp is a registry/// that would silently be wrong the first time a fifth kind spelled either/// column differently.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct SummaryProvenance {    /// The column holding `'user'` or the assistant's label (R74).    pub by: &'static str,    /// The instant the prose was last written.    pub updated_at: &'static str,}/// What "has arrived since this was written" counts.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct SummarySince {    pub table: &'static str,    /// The column in `table` pointing back at the summarised record.    pub parent_column: &'static str,    /// The instant compared against `summary_updated_at`.    pub instant_column: &'static str,    pub noun: SummaryStalenessNoun,}/// Where one kind's summary lives, and what makes it stale.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct SummarySource {    /// The table the summary lives on.    pub table: &'static str,    /// The column holding the prose.    ///    /// A project's is `description` and stays so: a synced table's COLUMN name    /// is wire protocol exactly as its table name is (projects.v12.ts's    /// ruling), and a rename would strand in-flight ops from a phone    /// mid-upgrade. Everything a person or an assistant READS says "summary".    pub column: &'static str,    pub provenance: SummaryProvenance,    pub since: SummarySince,}/// The provenance pair, spelled once. Schema v15 gave all four tables the same/// two column names, so this is a literal every entry points at rather than/// four copies that could drift — while [`SummarySource::provenance`] keeps the/// fact declared per kind, which is what lets a fifth kind differ.pub const SUMMARY_PROVENANCE: SummaryProvenance = SummaryProvenance {    by: "summary_by",    updated_at: "summary_updated_at",};/// Where each kind's summary lives, and what makes it stale.////// The tables and columns are READ OFF THE DEFINITIONS ([`summary_home`]):/// the kind's own definition says where its summary is stored, and the/// arrivals' definition says which of its links points back at the record/// (lane T11, 22 Oct 2026: summaries stop hand-listing tables). What each/// kind counts, and what it calls them, stay declared here — that is the/// decision below, not a fact about storage. The exhaustive `match` is still/// the guard that a fifth kind fails the BUILD rather than the first request.////// Two choices worth stating, because the spec's examples do not name kinds://////   - A PERSON's cue counts NOTES, not chats. Their chats are reachable only///     through `cotton_msg_contacts.person_id` — a two-hop join for a cue —///     while the note stream is the page's own content and the material a///     summary is written from.///   - A PROJECT's counts new LINKS, not memories or sessions. A memory is the///     owner's own sentence, shown in full directly below the summary on the///     same page, so nothing it would tell you is hidden; a session is work///     that happened, not new material the summary should have described. New///     links are exactly what arrived that this summary did not see.////// And one that applies to all four: the instant is ARRIVAL — `created_at`,/// when the row landed in this database — never authorship. A chat and an email/// both carry `sent_at`, and counting that is the reading that silently says/// nothing after an import: bring a WhatsApp archive or an `ingest_emails`/// backfill into a conversation you have already summarised, and every one of/// those tens of thousands of rows was sent long before the summary was/// written, so the page reports no arrivals over a thread that just grew by/// 40,000 lines. The cue's question is "has material this summary never saw/// reached me since", and only `created_at` answers it.////// Deliberately absent: `document`. §D6 leaves documents with the pipeline's/// summary, whose author is the profile stage and whose stamp is the row's own/// `updated_at`; a cue would be measuring a file that never changes.pub fn summary_source(kind: SummaryKind) -> SummarySource {    static RESOLVED: std::sync::LazyLock<Vec<(SummaryKind, SummarySource)>> =        std::sync::LazyLock::new(|| {            SummaryKind::ALL                .iter()                .map(|kind| {                    let source = resolve_summary_source(*kind)                        .unwrap_or_else(|fault| panic!("summary {kind}: {fault:?}"));                    (*kind, source)                })                .collect()        });    RESOLVED        .iter()        .find(|(resolved, _)| *resolved == kind)        .map(|(_, source)| *source)        .expect("every summary kind resolves")}/// Where one kind's summary lives: read off the definitions, or the hand/// entry for a kind no shipped definition describes yet.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum SummaryHome {    /// The kind's built-in definition (its id is the kind), the definition    /// whose records count as arrivals, and what to call them.    Definition {        arrivals: &'static str,        noun: SummaryStalenessNoun,    },    Hand(SummarySource),}/// What each kind counts as having arrived since its summary, and where the/// kinds with no definition keep theirs.pub const fn summary_home(kind: SummaryKind) -> SummaryHome {    use SummaryStalenessNoun::{Email, Message, Note};    match kind {        // Hand: a person's notes are a retired table (TABLE DROP 1), so no        // definition says where they link back; the store still keeps them.        SummaryKind::Person => SummaryHome::Hand(SummarySource {            table: "cotton_people",            column: "summary",            provenance: SUMMARY_PROVENANCE,            since: SummarySince {                table: "cotton_person_notes",                parent_column: "person_id",                instant_column: "created_at",                noun: Note,            },        }),        SummaryKind::Thread => SummaryHome::Definition { arrivals: "message", noun: Message },        SummaryKind::EmailThread => SummaryHome::Definition { arrivals: "email", noun: Email },        // Hand: no built-in definition ships for projects — a project is a        // database's own row (`cotton_memory_projects`), and its links are        // the project engine's table, which no definition describes yet.        SummaryKind::Project => SummaryHome::Hand(SummarySource {            table: "cotton_memory_projects",            column: "description",            provenance: SUMMARY_PROVENANCE,            since: SummarySince {                table: "cotton_project_links",                parent_column: "project_id",                instant_column: "created_at",                noun: SummaryStalenessNoun::Record,            },        }),    }}/// Why a built-in's summary home does not resolve — a fault in the shipped/// definitions or the store's compiled shape, read only by the developer the/// panic in [`summary_source`] stops, so it is a typed fact and never words.#[derive(Debug, Clone, PartialEq, Eq)]pub enum SourceFault {    NoBuiltin { id: &'static str },    NoStorage { id: String },    NoProvenance { id: String, long_texts: usize },    NoLinkBack { id: String, parent: String },    LinksTwice { id: String, parent: String },}/// One kind's summary home, resolved.fn resolve_summary_source(kind: SummaryKind) -> Result<SummarySource, SourceFault> {    let (arrivals, noun) = match summary_home(kind) {        SummaryHome::Hand(source) => return Ok(source),        SummaryHome::Definition { arrivals, noun } => (arrivals, noun),    };    let definition = crate::definitions::builtin_table_definition(kind.as_str())        .ok_or(SourceFault::NoBuiltin { id: kind.as_str() })?;    let (table, column, provenance) = summary_column(definition)?;    let arrivals = crate::definitions::builtin_table_definition(arrivals)        .ok_or(SourceFault::NoBuiltin { id: arrivals })?;    let (since_table, parent_column) = link_back(arrivals, kind.as_str())?;    Ok(SummarySource {        table,        column,        provenance,        since: SummarySince {            table: since_table,            parent_column,            // ARRIVAL, never authorship (see above): the row's own landing            // instant, which every synced table stores.            instant_column: "created_at",            noun,        },    })}/// A built-in's storage, as the store compiles it: `'static`, so a resolved/// home borrows its names rather than copying them.fn stored_tables(id: &str) -> Result<&'static [cotton_store::schema::package_tables::PackageTable], SourceFault> {    cotton_store::schema::package_tables::compiled_shape(id)        .ok_or_else(|| SourceFault::NoStorage { id: id.to_string() })}/// The table and column a definition keeps its summary in: the long-text/// column that declares `provenance` (who wrote it and when), else its one/// stored long text — and the table that stores it.pub fn summary_column(    definition: &'static crate::definitions::TableDefinition,) -> Result<(&'static str, &'static str, SummaryProvenance), SourceFault> {    use crate::definitions::ColumnType;    let tables = stored_tables(&definition.id)?;    let stored_in = |key: &str| {        tables            .iter()            .find(|table| table.columns.iter().any(|column| column.name == key))    };    let long: Vec<&'static crate::definitions::Column> = definition        .columns        .iter()        .filter(|column| column.column_type == ColumnType::Longtext && stored_in(&column.key).is_some())        .collect();    let column = match long.iter().find(|column| column.provenance.is_some()) {        Some(column) => *column,        None => match long.as_slice() {            [only] => *only,            _ => {                return Err(SourceFault::NoProvenance { id: definition.id.clone(), long_texts: long.len() })            }        },    };    let table = stored_in(&column.key).expect("filtered to stored columns");    let provenance = match &column.provenance {        Some(declared) => SummaryProvenance {            by: declared.by.as_str(),            updated_at: declared.at.as_str(),        },        // The store's one spelling (schema v15) for a table whose definition        // does not declare the pair.        None => SUMMARY_PROVENANCE,    };    Ok((table.name.as_str(), column.key.as_str(), provenance))}/// The table and link column by which `arrivals`' records point back at a/// record of `parent`: its one stored link column whose `link_to` is `parent`.pub fn link_back(    arrivals: &'static crate::definitions::TableDefinition,    parent: &str,) -> Result<(&'static str, &'static str), SourceFault> {    use crate::definitions::ColumnType;    let tables = stored_tables(&arrivals.id)?;    let mut found = arrivals.columns.iter().filter_map(|column| {        if column.column_type != ColumnType::Link || column.link_to.as_deref() != Some(parent) {            return None;        }        let table = tables            .iter()            .find(|table| table.columns.iter().any(|stored| stored.name == column.key))?;        Some((table.name.as_str(), column.key.as_str()))    });    let first = found        .next()        .ok_or_else(|| SourceFault::NoLinkBack { id: arrivals.id.clone(), parent: parent.to_string() })?;    if found.next().is_some() {        return Err(SourceFault::LinksTwice { id: arrivals.id.clone(), parent: parent.to_string() });    }    Ok(first)}/// One record's summary as a reader receives it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ISummary {    pub kind: SummaryKind,    pub id: String,    pub text: Option<String>,    /// `'user'`, or the assistant's label exactly as the owner typed it.    pub by: Option<String>,    pub updated_at: Option<String>,}/// How much has arrived since the summary was written, and what to call it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SummaryStaleness {    pub count: i64,    pub noun: SummaryStalenessNoun,}/// A summary plus its cue.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SummaryRead {    pub summary: ISummary,    /// `None` when there is nothing to say — never `{ count: 0 }`.    pub staleness: Option<SummaryStaleness>,}/// `String.prototype.trim()` — the ECMAScript whitespace set, which includes/// U+FEFF and excludes U+0085. Rust's `str::trim` is the Unicode `White_Space`/// property, which is the other way round on both.fn js_trim(text: &str) -> &str {    text.trim_matches(is_js_whitespace)}/// `String.prototype.length` — UTF-16 code units.fn utf16_len(text: &str) -> usize {    text.encode_utf16().count()}/// Refuse before the write, with a sentence a model can act on — or `None`.////// The TypeScript's `undefined` never reaches here: R73's grammar is/// `undefined` keeps, a string sets, `null` clears, and "keeps" is decided by/// the caller before it asks. That is why the argument is `Option<&str>` and/// not `Option<Option<&str>>` — `None` is the CLEAR, which is never refused.pub fn summary_refusal(text: Option<&str>) -> Option<SummaryRefusal> {    let text = text?;    if js_trim(text).is_empty() {        return Some(SummaryRefusal::Blank);    }    let length = utf16_len(text);    if length > SUMMARY_MAX_CHARS {        return Some(SummaryRefusal::TooLong { length });    }    None}/// Why a summary write is refused, as a typed fact; said to the assistant in/// the database's `refusal` lines (`summary.blank`, `summary.too_long`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum SummaryRefusal {    Blank,    TooLong { length: usize },}impl SummaryRefusal {    /// The refusal in `rows`' words, the kit's for a line they have none of.    pub fn say(&self, rows: &[super::shell_lines::LineRow]) -> String {        let (path, length) = match self {            SummaryRefusal::Blank => ("summary.blank", String::new()),            SummaryRefusal::TooLong { length } => ("summary.too_long", length.to_string()),        };        let max = SUMMARY_MAX_CHARS.to_string();        super::shell_lines::resolve("refusal", path, rows, &[("max", &max), ("length", &length)]).unwrap_or_default()    }}/// The columns a summary write sets — the ONE encoding, shared by the app's/// service and the server's tool, so the two can never disagree about what/// clearing a summary does to its provenance.////// A CLEAR takes the provenance with it. "Written by Claude Code, 12 Aug" over/// an empty space is a claim about nothing, and leaving the stamp behind would/// make the next writer's cue count arrivals since a summary that is gone.////// Returns a [`Map`] rather than a struct because the KEY ORDER is observable:/// this becomes an op's patch, stored as text, and the workspace turns on/// serde_json's `preserve_order` so the insertion order here is the order the/// bytes carry. The prose column is first, then the byline, then the stamp —/// the TypeScript object's own order.pub fn summary_columns(    kind: SummaryKind,    text: Option<&str>,    by: &str,    now: &str,) -> Map<String, Value> {    let source = summary_source(kind);    let mut patch = Map::new();    match text {        None => {            patch.insert(source.column.to_string(), Value::Null);            patch.insert(source.provenance.by.to_string(), Value::Null);            patch.insert(source.provenance.updated_at.to_string(), Value::Null);        }        Some(text) => {            patch.insert(source.column.to_string(), Value::String(text.to_string()));            patch.insert(                source.provenance.by.to_string(),                Value::String(by.to_string()),            );            patch.insert(                source.provenance.updated_at.to_string(),                Value::String(now.to_string()),            );        }    }    patch}/// What the row says today — the three columns a summary write can touch.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct StoredSummary {    pub text: Option<String>,    pub by: Option<String>,    pub updated_at: Option<String>,}/// What a summary write should do, decided once.////// Check `refusal` FIRST: on a refusal `patch` is also `None`, so a caller that/// looks only at `patch` would read a refusal as "nothing to do" and silently/// accept prose the rules reject.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SummaryDecision {    /// The prose as it would be stored — `None` for a clear.    pub text: Option<String>,    /// Why this write is refused, in a sentence a model can act on. Else    /// `None`.    pub refusal: Option<SummaryRefusal>,    /// The columns to write, provenance pair included — or `None` when the row    /// already says exactly this, which is the R67 no-op.    pub patch: Option<Map<String, Value>>,}/// THE summary decision: refuse, do nothing, or write these columns.////// Pure, and that is the point. Two surfaces write a summary and neither can/// share the other's writer: the app goes through `summariesService`, which/// writes via core's process-wide store singleton, while every server write/// must become a sync op on THIS request's file. What they CAN share is the/// decision — and they must, because "one implementation of who wins" is not/// about the transport, it is about when a stamp moves. Two diffs would/// eventually disagree, and the disagreement is a person watching their/// summary's author change because somebody renamed the record.////// The three rules, in the order they apply://////   1. REFUSE blank prose (pass `None` to clear) and prose over the product's///      cap. Nothing is written, and `patch` stays `None`.///   2. A CLEAR is a no-op only when the row is ALREADY entirely clear —///      prose, author and instant all null. Text alone is not enough: a stamp///      standing over an empty string is exactly the state a clear exists to///      end, and `stored.by` / `stored.updated_at` are why they are fields.///   3. A SET is a no-op when the prose is IDENTICAL (R67). Compared raw, not///      trimmed: everything that survives rule 1 is non-blank prose or a clear,///      so the only asymmetry left is a legacy empty string in the column///      meeting an incoming clear — deliberately unequal, so that write goes///      through and takes the stranded provenance with it.////// The author and the instant are NOT part of the comparison. Re-sending the/// same paragraph under a new name is still the same paragraph, and re-stamping/// it would reset the staleness cue every time an edit sheet was opened and/// saved — which is the one promise a summary page makes ("N notes since this/// was written") broken by the act of looking.////// The TypeScript takes the kind and the prose as one `input` object; here they/// are two arguments, since Rust has no reason to build a struct to pass a pair.pub fn summary_patch_for(    stored: &StoredSummary,    kind: SummaryKind,    text: Option<&str>,    by: &str,    now: &str,) -> SummaryDecision {    if let Some(refusal) = summary_refusal(text) {        return SummaryDecision {            text: text.map(str::to_string),            refusal: Some(refusal),            patch: None,        };    }    let unchanged = match text {        None => stored.text.is_none() && stored.by.is_none() && stored.updated_at.is_none(),        Some(text) => stored.text.as_deref() == Some(text),    };    SummaryDecision {        text: text.map(str::to_string),        refusal: None,        patch: if unchanged {            None        } else {            Some(summary_columns(kind, text, by, now))        },    }}/// How much has arrived since the summary was written — the ONE predicate every/// cue reads (R60).////// `None`, not zero, in both the cases that mean "say nothing": no summary at/// all (there is nothing to be stale), and nothing newer than it (figure or/// silence). An unparseable arrival is stepped over rather than counted: a/// malformed timestamp is not evidence that something happened.////// Instants are PARSED, never compared lexically — an offset-bearing instant/// sorts wrong as a string (`2026-08-20T14:00+05:30` is 08:30Z, before a/// summary written at 09:00Z, though it sorts after it).////// The empty string is guarded alongside the missing stamp, because the/// TypeScript's `!summaryUpdatedAt` catches both and a `summary_updated_at`/// column really can hold one on a legacy row.pub fn staleness_of(    kind: SummaryKind,    summary_updated_at: Option<&str>,    arrivals: &[String],) -> Option<SummaryStaleness> {    let stamp = summary_updated_at.filter(|value| !value.is_empty())?;    let written = parse_date_ms(stamp)?;    let count = arrivals        .iter()        .filter(|arrival| parse_date_ms(arrival).is_some_and(|at| at > written))        .count();    staleness_from(kind, count as i64)}/// The cue for a count somebody else has already made — the tail of/// [`staleness_of`], exported so a caller who counted in SQL reaches the SAME/// "figure or silence" rule and the SAME noun.////// The server's MCP read uses it: a chat with a year-old summary can have tens/// of thousands of arrivals, and `SELECT count(*) … WHERE created_at > ?` beats/// carrying every instant into the process to be counted there. Two ways to/// COUNT, deliberately — one way to say what the count MEANS, which is the part/// a person sees.pub fn staleness_from(kind: SummaryKind, count: i64) -> Option<SummaryStaleness> {    (count > 0).then(|| SummaryStaleness {        count,        noun: summary_source(kind).since.noun,    })}/// The byline a summary the PERSON wrote carries. Everything else in that/// column is a label — an assistant's, or a worker's device id.////// Declared here because two very different readers turn on it: the app's/// provenance line ("written by you"), and the nightly summaries worker, whose/// whole restraint is this one comparison. A string literal spelled twice is a/// worker that one day overwrites somebody's own paragraph.pub const SUMMARY_AUTHOR_PERSON: &str = "user";/// Did the owner write this themselves? A missing byline is not theirs.pub fn summary_is_theirs(by: Option<&str>) -> bool {    by == Some(SUMMARY_AUTHOR_PERSON)}/// How much has to arrive before a summary is worth writing again, per kind.////// Declared HERE, beside [`summary_source`], and not in the worker that reads/// it: the staleness rule and the number that rule is measured against are one/// decision, and a threshold living next to the model call would be a second/// opinion about what "stale" means — the same split the source registry exists/// to prevent.////// The four numbers are not one number, because the nouns are not comparable./// Twenty chat messages can be one exchange about lunch; three emails are three/// matters. Ten notes about a person is a genuinely different person from the/// one the last paragraph described; fifteen new links is a project that has/// moved on. A single figure across all four would either rewrite every chat/// every night or never rewrite a mailbox at all.pub const fn summary_refresh_threshold(kind: SummaryKind) -> i64 {    match kind {        SummaryKind::Person => 10,        SummaryKind::Thread => 20,        SummaryKind::EmailThread => 3,        SummaryKind::Project => 15,    }}/// Why a summary wants writing: it has never been written, or it has aged.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum SummaryRefreshReason {    Empty,    Stale,}impl SummaryRefreshReason {    pub const fn as_str(self) -> &'static str {        match self {            SummaryRefreshReason::Empty => "empty",            SummaryRefreshReason::Stale => "stale",        }    }}impl std::fmt::Display for SummaryRefreshReason {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SummaryRefreshDecision {    pub due: bool,    /// `None` exactly when `due` is false — there is no "due for no reason".    pub reason: Option<SummaryRefreshReason>,    /// What was counted since the stamp; 0 when there was no stamp to count    /// from.    pub arrivals: i64,    pub threshold: i64,}/// Should something write this summary now? Pure, and the ONE answer.////// Three states, in the order they apply://////   1. NO PROSE — due, whatever has or has not arrived. An empty slot is the///      case the whole feature exists for, and there is nothing to be stale.///      Whitespace counts as empty: [`summary_refusal`] refuses to write it, so///      a column holding it is a legacy value, not a summary.///   2. PROSE WITH NO STAMP — never due. [`staleness_of`] answers `None` for///      exactly this row, so no screen shows a cue for it; a worker that///      rewrote it nightly would be acting on a measurement the product has///      decided cannot be made. Rare and legacy — [`summary_columns`] writes///      both or neither.///   3. PROSE WITH A STAMP — due once `arrivals` reaches the kind's threshold.////// `arrivals` is somebody else's count, deliberately: the caller has either the/// instants ([`staleness_of`]) or a `COUNT(*)` the database made. This decides/// what the number MEANS, exactly as [`staleness_from`] does for the cue — and/// note that in cases 1 and 2 the count the caller passed is REPLACED by 0 in/// the answer, because it was never measured against anything.pub fn summary_refresh_due(    kind: SummaryKind,    stored: &StoredSummary,    arrivals: i64,) -> SummaryRefreshDecision {    let threshold = summary_refresh_threshold(kind);    let has_prose = stored        .text        .as_deref()        .is_some_and(|text| !js_trim(text).is_empty());    if !has_prose {        return SummaryRefreshDecision {            due: true,            reason: Some(SummaryRefreshReason::Empty),            arrivals: 0,            threshold,        };    }    // The empty string is guarded with the missing stamp: `!stored.updatedAt`    // catches both over there, and both mean "nothing to measure from".    let has_stamp = stored        .updated_at        .as_deref()        .is_some_and(|stamp| !stamp.is_empty());    if !has_stamp {        return SummaryRefreshDecision {            due: false,            reason: None,            arrivals: 0,            threshold,        };    }    let due = arrivals >= threshold;    SummaryRefreshDecision {        due,        reason: due.then_some(SummaryRefreshReason::Stale),        arrivals,        threshold,    }}#[cfg(test)]#[path = "summaries_tests.rs"]mod tests;