//! 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};usecrate::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.pubconst 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")]pubenumSummaryStalenessNoun {Note,Message,Email,Record,}implSummaryStalenessNoun {pubconstfn as_str(self) -> &'static str {matchself {SummaryStalenessNoun::Note => "note",SummaryStalenessNoun::Message => "message",SummaryStalenessNoun::Email => "email",SummaryStalenessNoun::Record => "record", } }}impl std::fmt::DisplayforSummaryStalenessNoun {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)]pubstructSummaryProvenance {/// 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)]pubstructSummarySince {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)]pubstructSummarySource {/// 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.pubconst 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.pubfn 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)]pubenumSummaryHome {/// 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.pubconstfn summary_home(kind: SummaryKind) -> SummaryHome {useSummaryStalenessNoun::{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)]pubenumSourceFault {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) => returnOk(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.pubfn summary_column( definition: &'staticcrate::definitions::TableDefinition,) -> Result<(&'static str, &'static str, SummaryProvenance), SourceFault> {usecrate::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<&'staticcrate::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, _ => {returnErr(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`.pubfn link_back( arrivals: &'staticcrate::definitions::TableDefinition, parent: &str,) -> Result<(&'static str, &'static str), SourceFault> {usecrate::definitions::ColumnType;let tables = stored_tables(&arrivals.id)?;letmut found = arrivals.columns.iter().filter_map(|column| {if column.column_type != ColumnType::Link || column.link_to.as_deref() != Some(parent) {returnNone; }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() {returnErr(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")]pubstruct 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")]pubstructSummaryStaleness {pub count: i64,pub noun: SummaryStalenessNoun,}/// A summary plus its cue.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructSummaryRead {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.pubfn summary_refusal(text: Option<&str>) -> Option<SummaryRefusal> {let text = text?;if js_trim(text).is_empty() {returnSome(SummaryRefusal::Blank); }let length = utf16_len(text);if length > SUMMARY_MAX_CHARS {returnSome(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)]pubenumSummaryRefusal {Blank,TooLong { length: usize },}implSummaryRefusal {/// The refusal in `rows`' words, the kit's for a line they have none of.pubfn say(&self, rows: &[super::shell_lines::LineRow]) -> String {let (path, length) = matchself {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.pubfn summary_columns( kind: SummaryKind, text: Option<&str>, by: &str, now: &str,) -> Map<String, Value> {let source = summary_source(kind);letmut 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")]pubstructStoredSummary {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)]pubstructSummaryDecision {/// 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.pubfn summary_patch_for( stored: &StoredSummary, kind: SummaryKind, text: Option<&str>, by: &str, now: &str,) -> SummaryDecision {ifletSome(refusal) = summary_refusal(text) {returnSummaryDecision { 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.pubfn 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.pubfn 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.pubconst SUMMARY_AUTHOR_PERSON: &str = "user";/// Did the owner write this themselves? A missing byline is not theirs.pubfn 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.pubconstfn 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")]pubenumSummaryRefreshReason {Empty,Stale,}implSummaryRefreshReason {pubconstfn as_str(self) -> &'static str {matchself {SummaryRefreshReason::Empty => "empty",SummaryRefreshReason::Stale => "stale", } }}impl std::fmt::DisplayforSummaryRefreshReason {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")]pubstructSummaryRefreshDecision {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.pubfn 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 {returnSummaryRefreshDecision { 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 {returnSummaryRefreshDecision { 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;