//! The day surface's reads — the queries no single tool answers. //! //! 4e's screens are the day and the person: todos, the calendar, alarms, //! notes, the journal, thoughts, people, places and goals. Most of them are //! already a tool's list and are declared in [`crate::phone::reads::READS`] as //! [`ReadSource::Tool`](crate::phone::reads::ReadSource::Tool). What is HERE is //! the remainder — a screen whose question no tool asks, either because the //! tool answers a different question (the assistant's index rather than the //! person's list) or because the screen joins two tables the catalogue keeps //! apart. //! //! Every function here is ported from the service the SwiftUI phone deletes, //! clause for clause, and the clause comments say which clause is load bearing //! and why. A clause quietly dropped in a port is a screen that shows somebody //! rows they had put away. //! //! One rule runs through all of them: **an empty answer and a failed read are //! different facts**, so a query that cannot run returns `Err` and never an //! empty list. Three of these screens draw a different surface for each, and //! `/journal/[date]` will DESTROY a day's words if a failed read is read as "no //! page exists" — it would resolve to a new page, and the editor's first //! keystroke would reconcile onto the existing row and replace the body with //! that one character. use std::collections::HashMap; use cotton_core::rules::asked_of_you::INVITE_SQL; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use crate::shell::file::ReadFile; /// The workspace id as a bound parameter — every read here is scoped to the one /// file this phone holds. fn workspace(replica: &ReadFile<'_>) -> SqlValue { SqlValue::Text(replica.workspace_id.to_string()) } /// A required id argument, refused by name rather than defaulted. fn id_arg(args: &Map, what: &str) -> Result { args.get("id") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_string) .ok_or_else(|| format!("`id` is the {what} to read")) } // ── /alarms ───────────────────────────────────────────────────────────────── /// The two keys the *Projects…* sheet needs, for ANY record kind: the whole /// project roster, and this record's memberships. /// /// ONE function rather than a clause per detail screen, because the sheet is /// kind-agnostic (`Record/ProjectsSheet.swift`) and the shapes it decodes are /// `ProjectRef` and `ProjectLink` wherever it opens. `read.person` answers the /// same two keys with the same two shapes and was the only screen that had /// them, which is why the sheet was live on one page out of five. /// /// ARCHIVED PROJECTS ARE INCLUDED, and that is `read.person`'s reason, kept: the /// chips draw only the active ones (the device filters), but the sheet has to /// be able to UNLINK from a project that has since been retired, and filtering /// here would make that membership impossible to remove. /// `cotton_memory_projects` retires by `status`; it has no `archived_at`. pub(super) fn record_projects( replica: &ReadFile<'_>, kind: &str, id: &str, ) -> Result<(Vec, Vec), String> { record_projects_in(replica.driver, replica.workspace_id, kind, id) } /// [`record_projects`] over a bare driver — for a COMPOSED read, which holds a /// tool context rather than a replica (`read.record`'s note half). pub(crate) fn record_projects_in( db: &cotton_store::driver::Driver, workspace_id: &str, kind: &str, id: &str, ) -> Result<(Vec, Vec), String> { let projects = db .all( "SELECT id, slug, name, status, created_at FROM cotton_memory_projects WHERE workspace_id = ? ORDER BY created_at ASC", &[SqlValue::Text(workspace_id.to_string())], ) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "id": row.text("id"), "slug": row.text("slug"), "name": row.text("name"), "status": row.text("status"), "createdAt": row.text("created_at"), }) }) .collect(); let links = db .all( "SELECT id, project_id, record_kind, record_id, note, created_at FROM cotton_project_links WHERE record_kind = ? AND record_id = ? ORDER BY created_at ASC", &[ SqlValue::Text(kind.to_string()), SqlValue::Text(id.to_string()), ], ) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "id": row.text("id"), "projectId": row.text("project_id"), "recordKind": row.text("record_kind"), "recordId": row.text("record_id"), // The note is MEMBERSHIP state and the sheet commits an edit to // it on blur, so it has to arrive: a sheet that opened empty // turned every edit into a fresh write over what was there. // NULL, never "" — an empty string is a note somebody typed and // cleared, which is a different fact from never having written // one, and the column is nullable to say so. "note": row.text("note"), "createdAt": row.text("created_at"), }) }) .collect(); Ok((projects, links)) } /// A JSON text column that holds a LIST, read as one — or `[]`. /// /// THE one reading of `phones`, `emails` and their kin, in this file and in /// `person.rs`. Both columns are `NOT NULL DEFAULT '[]'`, and every consumer on /// the Swift side is a non-optional `[String]`: a column that parses to an /// object, to a number or to nothing at all must therefore arrive as an empty /// list, never as that value and never as `null`, or the boundary throws and a /// whole page goes dark for one malformed row. Three different readings of /// these two columns landed in one PR — one filtered, one did not, one answered /// a bare `null` — which is why there is now one function and it is used /// everywhere. pub(super) fn json_list(raw: Option<&str>) -> Value { raw.and_then(|raw| serde_json::from_str::(raw).ok()) .filter(Value::is_array) .unwrap_or_else(|| json!([])) } /// The ISO weekdays an alarm repeats on. /// /// The column is JSON text (`'[]'` by default). A column that will not parse /// reads as a ONE-SHOT rather than as an error: the whole screen must not go /// dark for one malformed row, and an alarm with no days IS a one-shot — the /// row still shows, at its time, with its label. This is the same reading /// `alarms.rs::days_of` takes on the tool side, deliberately. /// /// The ELEMENTS are held to the same rule as the list. `Alarm.repeatDays` is /// `[Int]` on the Swift side and decodes non-optionally, so `["mon"]` — a list /// that parses, holding something that is not a weekday — would throw exactly /// where an unparseable list does not. A stray entry is dropped and the rest of /// the row still draws, which is what the paragraph above promises. fn repeat_days(raw: Option<&str>) -> Vec { let Some(raw) = raw else { return Vec::new() }; serde_json::from_str::(raw) .ok() .and_then(|value| value.as_array().cloned()) .unwrap_or_default() .into_iter() .filter(Value::is_i64) .collect() } /// `/alarms` — every alarm the owner has set, in clock order. /// /// `alarmsService.listAlarms`, and the two clauses that are not obvious: /// /// * **disabled rows are included.** The screen draws them greyed with their /// switch off — an alarm somebody turned off is still an alarm they own, and /// filtering them here would delete it from their eyes. /// * **the order is `hour, minute`, not `created_at`.** The list is a clock /// face; a person looks down it for a time, never for what they added last. /// /// The id is ALSO the AlarmKit alarm id: the reconciler diffs the operating /// system's alarms against these directly. That is why the read answers the /// stored id rather than an index. pub fn alarms(replica: &ReadFile<'_>, _args: &Map) -> Result { let rows = replica .driver .all( "SELECT id, label, hour, minute, repeat_days, enabled, sound, created_at, updated_at FROM cotton_alarms WHERE workspace_id = ? AND trashed_at IS NULL ORDER BY hour ASC, minute ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())?; let alarms: Vec = rows .iter() .map(|row| { json!({ "id": row.text("id"), // `NOT NULL DEFAULT ''`, and "" is what "the owner named // nothing" looks like — the screen decides what that reads as, // never this layer. "label": row.text("label").unwrap_or_default(), // No `unwrap_or` on these two, unlike the three around them: // both columns are `INTEGER NOT NULL` with a CHECK, so there is // no absent case to defend against and inventing a midnight // would be worse than the read failing. Said here because the // bare reads otherwise look like an oversight beside three // deliberate defences. "hour": row.int("hour"), "minute": row.int("minute"), "repeatDays": repeat_days(row.text("repeat_days")), "enabled": row.int("enabled").unwrap_or(0) != 0, // A v23 op carried no `sound`, and a row folded from one takes // the column's own default. Reading a missing value as silent // would quiet every alarm that arrived from an older device. "sound": row.int("sound").is_none_or(|value| value != 0), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), }) }) .collect(); Ok(json!({ "alarms": alarms })) } // ── /journal ──────────────────────────────────────────────────────────────── /// `/journal` — the person's own journal pages, newest day first. /// /// `notesService.listJournal`, and every clause matters: /// /// * `kind = 'journal'` — a note is the same table and a different screen; /// * `project_id IS NULL` — **load bearing**: an assistant's project entry is a /// row of exactly this kind in exactly this workspace, and including one /// would light the streak, dot the calendar and head Recent with a page /// that is not in the person's journal; /// * `archived_at IS NULL` — a put-away page belongs to the bin's screen; /// * `ORDER BY journal_date IS NULL, journal_date DESC` — the journal's order /// is the order of the DAYS it describes, never the order they were edited /// in, and a page with no day sorts last rather than first. /// /// The body travels WHOLE. The first line the list shows is derived on the /// device after `stripMarkdown`, and the same body feeds the editor, so /// pre-computing a title here would be a second answer to what a page is /// called. /// /// The streak stays on the device too: `journalDayState` is a function of these /// day keys and the PHONE's local midnight, and a server-computed one has /// already shipped a visible disagreement once — one surface saying "Write /// today's page" one swipe from a Home row reading "Today's page written". pub fn journal(replica: &ReadFile<'_>, args: &Map) -> Result { // SCOPED (the Mac's project filter, `phone/scope.rs`), the journal is the // chosen projects' pages instead of the person's own: `project_id IS NULL` // is exactly what would leave a scope nothing to show. The column is the // authoritative one for a journal page (`mirrored_project_column`), so the // clause reads it rather than the link row it mirrors into. // The seam only hands ids it resolved from at least one slug. let mut params = vec![workspace(replica)]; let owner_clause = match crate::phone::scope::handed_project_ids(args) { None => "project_id IS NULL".to_string(), Some(ids) => { let clause = format!("project_id IN ({})", vec!["?"; ids.len()].join(",")); params.extend(ids.into_iter().map(SqlValue::Text)); clause } }; let rows = replica .driver .all( &format!( "SELECT id, kind, journal_date, body FROM cotton_notes WHERE workspace_id = ? AND kind = 'journal' AND {owner_clause} AND archived_at IS NULL ORDER BY journal_date IS NULL, journal_date DESC" ), ¶ms, ) .map_err(|error| error.to_string())?; // WHAT "WRITTEN" MEANS IS ANSWERED HERE, NOT ON THE PHONE. // `cotton_core::rules::journal` owns the predicate and the streak — 4i // deleted the Swift copy for the reason the memory entry states, after two // implementations disagreed about whether one day had been written // ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]). So // each row carries `written`, and the screen's caption reads the state // below rather than re-deriving either. let engine_pages: Vec = rows .iter() .map(|row| cotton_core::rules::journal::JournalPage { kind: row.text("kind").unwrap_or_default().to_string(), body: row.text("body").map(str::to_string), journal_date: row.text("journal_date").map(str::to_string), }) .collect(); let pages: Vec = rows .iter() .zip(engine_pages.iter()) .map(|(row, page)| { json!({ "id": row.text("id"), // The kind travels even though this query pins it: the page // shape is the same one `read.home` answers. "kind": row.text("kind"), "journalDate": row.text("journal_date"), "body": row.text("body").unwrap_or_default(), "written": cotton_core::rules::journal::is_written_journal_page(page), }) }) .collect(); // The zone is the workspace's, the same one the calendar expands in: a // streak counted in two zones is two different runs. let zone = expansion_zone(replica, args)?; let now_ms = args .get("nowMs") .and_then(Value::as_i64) .ok_or_else(|| "`nowMs` is this device's clock — the streak is counted from it".to_string())?; let state = cotton_core::rules::journal::journal_day_state(&engine_pages, now_ms, &zone) .map_err(|error| error.to_string())?; Ok(json!({ "pages": pages, "writtenToday": state.written_today, "streak": state.streak, })) } // ── the calendar ──────────────────────────────────────────────────────────── /// The workspace's own zone, else the device's, and never a UTC floor. /// /// `services/workspaceZone.ts::expansionZone`. The order is the duplication /// guard rather than a preference: an occurrence's identity is its INSTANT, so /// two producers reading one rule in two zones draw two different days. The /// recorded zone is the value every producer can agree on; the device's is the /// momentary fallback for a workspace that has never recorded one, and the /// foreground materializer writes it down on its first pass. /// /// A read may fall back; a WRITER may not, which is why the tool half refuses /// instead. Drawing something in the device's zone is honest — "we were not /// told" still has a day to show — and minting rows at instants no other /// producer computes is not. /// /// A RECORDED ZONE THIS RUNTIME CANNOT RESOLVE IS TREATED AS NO ZONE, which is /// `workspaceZone()`'s own clause: *"A zone this runtime cannot format is worse /// than no zone: it would throw inside the expansion instead of answering."* /// Without it an unparseable stored name reaches `expand_calendar` and its /// error becomes the day screen's error surface, where the TypeScript drew the /// day. fn expansion_zone(replica: &ReadFile<'_>, args: &Map) -> Result { let recorded = replica .driver .get( "SELECT timezone FROM cotton_news_settings WHERE workspace_id = ?", &[workspace(replica)], ) .map_err(|error| error.to_string())? .and_then(|row| row.text("timezone").map(str::to_string)) .filter(|zone| !zone.trim().is_empty()) .filter(|zone| cotton_core::transforms::zoned_clock::zone_offset_ms(0, zone).is_ok()); if let Some(recorded) = recorded { return Ok(recorded); } args.get("timezone") .and_then(Value::as_str) .map(str::trim) .filter(|zone| !zone.is_empty()) .map(str::to_string) .ok_or_else(|| { "`timezone` is the zone this device is standing in — this database has recorded none" .to_string() }) } /// The phone's zone owns the displayed clock, independently of the zone /// used to expand a recurring series into stable occurrence identities. fn day_reading_zone(args: &Map) -> Result { let zone = args.get("timezone") .and_then(Value::as_str) .map(str::trim) .filter(|zone| !zone.is_empty()) .ok_or_else(|| "`timezone` is the zone this device is standing in".to_string())?; cotton_core::transforms::zoned_clock::zoned_parts(0, zone).map_err(|error| error.to_string())?; Ok(zone.to_string()) } /// The name of the calendar `event` names, where this file holds it — a word /// about the event, never what it belongs to: an event is the database's, and /// the object keeps no calendars (27 Oct 2026). fn calendar_name(replica: &ReadFile<'_>, event: &cotton_store::driver::Row) -> Result, String> { let Some(calendar) = event.text("collection_id") else { return Ok(None); }; Ok(replica .driver .get( "SELECT name FROM cotton_collections WHERE id = ? AND workspace_id = ?", &[SqlValue::Text(calendar.to_string()), workspace(replica)], ) .map_err(|error| error.to_string())? .and_then(|row| row.text("name").map(str::to_string)) .filter(|name| !name.trim().is_empty())) } /// The columns the day and month surfaces draw an event with. const EVENT_COLUMNS: &str = "id, title, starts_at, ends_at, all_day, location, notes, rrule, \ exdates, series_id, original_starts_at, trashed_at, gcal_id, gcal_etag, sync_state, \ my_response, organizer_is_self, collection_id, created_at, updated_at"; /// Every row that COULD produce an occurrence in the window. /// /// `eventsService.listEvents`' own predicate, and each half of it is load /// bearing: /// /// * `starts_at <= to` — an occurrence only ever moves forward from its /// master's start, so a row starting after the window cannot occur inside it; /// * `OR original_starts_at <= to` — an exception MOVED out of the window must /// still arrive, because its claim on the instant it left is what stops the /// master re-drawing the occurrence it gave up; /// * **no `trashed_at IS NULL`, and no lower bound.** Filtering the bin here /// would drop a trashed master while leaving its exceptions, which the /// expansion would then read as orphans and draw as ordinary events. The /// expansion is the one place that knows a trashed row draws nothing. And a /// series anchored years ago still anchors the rule. /// /// Every event of this database: an event is the database's, never reached /// through a calendar — the object keeps none, and a copy read through one /// drew none of the events it held (27 Oct 2026). fn event_candidates( replica: &ReadFile<'_>, to: &str, ) -> Result, String> { replica .driver .all( &format!( "SELECT {EVENT_COLUMNS} FROM cotton_events WHERE (starts_at <= ? OR original_starts_at <= ?) ORDER BY starts_at ASC" ), &[ SqlValue::Text(to.to_string()), SqlValue::Text(to.to_string()), ], ) .map_err(|error| error.to_string()) } /// One candidate row as the expansion reads it. fn series_row(row: &cotton_store::driver::Row) -> cotton_core::rules::series::SeriesRow { cotton_core::rules::series::SeriesRow { id: row.text("id").unwrap_or_default().to_string(), starts_at: row.text("starts_at").unwrap_or_default().to_string(), ends_at: row.text("ends_at").map(str::to_string), rrule: row.text("rrule").map(str::to_string), // The column is JSON text. A list that will not parse reads as NO // exdates rather than as an error — the calendar still draws, and the // occurrence a broken list would have removed is the one the person // then sees and can cancel again. exdates: row .text("exdates") .and_then(|raw| serde_json::from_str::>(raw).ok()), series_id: row.text("series_id").map(str::to_string), original_starts_at: row.text("original_starts_at").map(str::to_string), trashed_at: row.text("trashed_at").map(str::to_string), } } /// One event as every calendar surface renders it — `toIEvent`'s camel case. fn event_out(row: &cotton_store::driver::Row) -> Value { json!({ "id": row.text("id"), "title": row.text("title"), "startsAt": row.text("starts_at"), "endsAt": row.text("ends_at"), "allDay": row.int("all_day").unwrap_or(0) != 0, "location": row.text("location"), "notes": row.text("notes"), "rrule": row.text("rrule"), "seriesId": row.text("series_id"), "originalStartsAt": row.text("original_starts_at"), "trashedAt": row.text("trashed_at"), "gcalId": row.text("gcal_id"), "syncState": row.text("sync_state"), "myResponse": row.text("my_response"), "organizerIsSelf": row.int("organizer_is_self").unwrap_or(0) != 0, "collectionId": row.text("collection_id"), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), }) } /// The window this read was asked for, as the engine takes it. fn window(args: &Map) -> Result<(String, String), String> { let read = |key: &str| -> Result { args.get(key) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string) .ok_or_else(|| { format!("`{key}` is an ISO instant — the window is the DEVICE's local day, and this core has no clock to compute one from") }) }; Ok((read("from")?, read("to")?)) } /// Every event's projects, keyed by the event row's id, in ONE query over the /// links rather than one per occurrence — a month grid draws dozens at once. /// /// The order is the notes' and the todos' (`created_at, id`), so "first" /// means one thing on every surface: an event's paper is its FIRST project's /// cap colour, the todo board's rule. Archived projects come back too; the /// phone folds colours over the ACTIVE roster and an unknown slug is cream. fn event_projects(replica: &ReadFile<'_>) -> Result>, String> { let mut by_event: HashMap> = HashMap::new(); for row in replica .driver .all( "SELECT l.record_id, p.id, p.slug, p.name FROM cotton_project_links l JOIN cotton_memory_projects p ON p.id = l.project_id WHERE l.workspace_id = ? AND l.record_kind = 'event' ORDER BY p.created_at ASC, p.id ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())? { let Some(event_id) = row.text("record_id") else { continue; }; by_event.entry(event_id.to_string()).or_default().push(json!({ "id": row.text("id"), "slug": row.text("slug"), "name": row.text("name"), })); } Ok(by_event) } /// Expand the candidates and hand back one JSON occurrence per drawn instant. /// /// The decision is `cotton_core::rules::series::expand_calendar`'s and nothing /// here expands a rule a second way — which exdates apply, that an exception's /// `original_starts_at` claims its instant even when the exception is trashed, /// that a trashed master takes its whole series with it, and that an exception /// whose master is outside the window draws as an ordinary event. fn expanded( replica: &ReadFile<'_>, rows: &[cotton_store::driver::Row], from: &str, to: &str, zone: &str, ) -> Result, String> { let projects = event_projects(replica)?; let series: Vec = rows.iter().map(series_row).collect(); let range = cotton_core::transforms::rrule::DateRange { from: cotton_store::protocol::js::parse_date_ms(from) .ok_or_else(|| format!("`from` is not an instant: {from}"))?, to: cotton_store::protocol::js::parse_date_ms(to) .ok_or_else(|| format!("`to` is not an instant: {to}"))?, }; let drawn = cotton_core::rules::series::expand_calendar(&series, range, zone) .map_err(|error| error.to_string())?; Ok(drawn .into_iter() .filter_map(|slot| { // The row an occurrence is DRAWN from — the exception where there is // one, which is why the title and the sync marks come from here // rather than from the master. let row = rows.iter().find(|row| row.text("id") == Some(&slot.event_id))?; // The projects an occurrence wears: its own row's links, else its // series master's. An exception is filed where its master was — // a moved Tuesday is still that series' Tuesday — so a row with no // links of its own inherits rather than reading as unfiled. let filed = projects .get(&slot.event_id) .or_else(|| slot.series_id.as_ref().and_then(|id| projects.get(id))) .cloned() .unwrap_or_default(); Some(json!({ "eventId": slot.event_id, "seriesId": slot.series_id, "occurrenceAt": slot.occurrence_at, "startsAt": slot.starts_at, "endsAt": slot.ends_at, "isException": slot.is_exception, "event": event_out(row), "projects": filed, })) }) .collect()) } /// The todos a calendar surface draws, and only those. /// /// `todosService.listTodos` is the whole workspace pool of open and done /// todos, filtered to the day on the client — a missed occurrence is neither. The window is pushed down /// here instead — the same answer, without shipping every todo a person has to /// draw one day of them — and the `due_at IS NULL` half of its ORDER BY goes /// with it, since a todo with no date is on no day. /// /// THE COMPARISON IS ISO STRING ORDER, where the app compared local DATE KEYS, /// and the two agree only because every instant this file stores ends `Z`: /// a fixed-width UTC ISO-8601 string sorts lexicographically exactly as the /// instant does. That is the store's own invariant (every `*_at` column is /// written by `iso_of_ms`), and it is written down here because a stored offset /// like `+05:30` would break the ordering silently rather than loudly. /// /// A todo is on the day it is next due, as its list reads it (`upcoming`): /// a snooze landing in the window brings it onto the day at the snooze's /// instant, and a snooze past the window takes it off the day whatever its /// due date says — the day's list is that day's, never a coming one's /// (290 walk: tomorrow's todos stood in Me's Today). fn day_todos(replica: &ReadFile<'_>, from: &str, to: &str) -> Result, String> { let rows = replica .driver .all( "SELECT id, title, status, at AS due_at FROM ( SELECT id, title, status, created_at, CASE WHEN snoozed_until >= ?2 THEN snoozed_until ELSE due_at END AS at FROM cotton_todos WHERE workspace_id = ?1 AND trashed_at IS NULL AND status IN ('open', 'done')) WHERE at IS NOT NULL AND at >= ?2 AND at <= ?3 ORDER BY at ASC, created_at ASC", &[ workspace(replica), SqlValue::Text(from.to_string()), SqlValue::Text(to.to_string()), ], ) .map_err(|error| error.to_string())?; Ok(rows .iter() .map(|row| { json!({ "id": row.text("id"), "title": row.text("title"), "status": row.text("status"), "dueAt": row.text("due_at"), }) }) .collect()) } /// `/calendar` — one day: its occurrences, the todos due on it, and the /// invitations still waiting for an answer. /// /// THE WINDOW IS THE DEVICE'S. `dayWindow(dateKey)` is built with local /// `setHours`, so the phone computes the two instants and passes them; this /// core must not invent either. Recurrence expansion keeps the workspace's /// canonical zone so occurrence identities remain stable; the displayed lines /// use the phone's zone, just like every other date column. /// /// THE INVITE STRIP'S OWN `from` IS THE CALLER'S, AND IT SHOULD BE *NOW*. /// "Needs your reply" is a constant question that does not page with the day, /// so it is not the viewed day's window start. Asked as of *now*, an /// invitation that STARTED EARLIER TODAY is already past and is not shown; a /// caller passing today's local midnight instead widens the strip by up to a /// day. This core has no clock and cannot correct it here; the contract is /// stated so the call site can be read against it, and the omitted-argument /// fallback is the window's own `from`, never an invented instant. pub fn day(replica: &ReadFile<'_>, args: &Map) -> Result { let (from, to) = window(args)?; let reader_zone = day_reading_zone(args)?; let zone = expansion_zone(replica, args)?; let rows = event_candidates(replica, &to)?; let mut occurrences = expanded(replica, &rows, &from, &to, &zone)?; let mut todos = day_todos(replica, &from, &to)?; day_lines(replica, &mut occurrences, &mut todos, &from, &reader_zone)?; // Blank is ABSENT, like every other string argument in this file: an empty // string makes `starts_at >= ''` match every row, which is the widest // possible answer to the narrowest possible input. let invites_from = args .get("invitesFrom") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .unwrap_or(from.as_str()); let invites = replica .driver .all( &format!( "SELECT {EVENT_COLUMNS} FROM cotton_events WHERE {INVITE_SQL} AND starts_at >= ? AND trashed_at IS NULL ORDER BY starts_at ASC" ), &[SqlValue::Text(invites_from.to_string())], ) .map_err(|error| error.to_string())?; Ok(json!({ "occurrences": occurrences, // An invitation is answered ONCE for the whole series — `my_response` // is a column on the row — so the strip is rows, never occurrences. // The bin is filtered HERE rather than after the read: nothing expands // these, so there is no expansion to hide a trashed row from, and the // app's client-side `drawableEvents` was a stopgap its own comment // says belongs in the query. "invites": invites.iter().map(event_out).collect::>(), "todos": todos, "timezone": reader_zone, })) } /// Each row's line on the day and the instant it sorts at. A row at an hour /// says its clock time in the zone ("2:30 pm", the app's one clock spelling); /// a row naming its day and no hour — an all-day event, a todo due on a date /// — says its date column's `untimed` words from the definition ("all day", /// "due today"), or nothing when the definition has none, and sorts at the /// day's start so it leads the day. The rows of several databases are joined /// unsorted (`databases::join`), so the screen orders them by `sortAt` /// (walker pass 3, 16 Oct 2026: Me's Today wrote "2:30 PM" out of order and /// a timeless todo at midnight). fn day_lines( replica: &ReadFile<'_>, occurrences: &mut [Value], todos: &mut [Value], from: &str, zone: &str, ) -> Result<(), String> { let definitions = cotton_tools::definitions::table_definitions_from_driver(replica.driver, replica.workspace_id) .map_err(|failure| failure.to_string())? .definitions; let untimed = |table: &str, column: &str| { definitions .iter() .find(|definition| definition.id == table) .and_then(|definition| definition.column(column)) .and_then(|column| column.untimed.clone()) }; let (all_day, due_today) = (untimed("event", "starts_at"), untimed("todo", "due_at")); let lines = cotton_tools::presentation::line_rows(replica.driver, replica.workspace_id); let dates = cotton_core::records::page::DateWords::of_rows(&lines); let undrawn = cotton_core::definitions::no_tool_draws_this_table(&lines); // A row over a table no tool draws (an event with Calendar not installed) // says the typed refusal as its line, never nothing: it opens no page. let drawn = |table: &str| definitions.iter().any(|definition| definition.id == table); let refuse = |row: &mut Value| { if let Some(object) = row.as_object_mut() { object.insert("line".into(), Value::from(undrawn.as_str())); } }; let line = |at: &str, timeless: Option, words: &Option| -> Result<(Option, String), String> { let at_ms = cotton_store::protocol::js::parse_date_ms(at).ok_or_else(|| format!("not an instant: {at}"))?; let timeless = match timeless { Some(timeless) => timeless, None => !has_clock_time(at_ms, zone).map_err(|error| error.to_string())?, }; if timeless { return Ok((words.clone(), from.to_string())); } let parts = cotton_core::transforms::zoned_clock::zoned_parts(at_ms, zone).map_err(|error| error.to_string())?; Ok((Some(dates.clock(parts.hour, parts.minute)), at.to_string())) }; let stamp = |row: &mut Value, at: Option, timeless: Option, words: &Option| -> Result<(), String> { let Some(at) = at else { return Ok(()) }; let (said, sort_at) = line(&at, timeless, words)?; if let Some(object) = row.as_object_mut() { object.insert("line".into(), said.map_or(Value::Null, Value::from)); object.insert("sortAt".into(), Value::from(sort_at)); } Ok(()) }; for occurrence in occurrences.iter_mut() { let at = occurrence.get("startsAt").and_then(Value::as_str).map(str::to_string); let timeless = occurrence.pointer("/event/allDay").and_then(Value::as_bool).unwrap_or(false); stamp(occurrence, at, Some(timeless), &all_day)?; if !drawn("event") { refuse(occurrence); } } for todo in todos.iter_mut() { let at = todo.get("dueAt").and_then(Value::as_str).map(str::to_string); stamp(todo, at, None, &due_today)?; if !drawn("todo") { refuse(todo); } } Ok(()) } /// `/calendar/month` — the grid's window, bucketed by the phone. /// /// THE SAME OCCURRENCES THE DAY ANSWERS, whole. The grid itself draws only a /// dot per day, but under it the SELECTED day's events are drawn as rows that /// open the event — so each carries its id, its occurrence instant, where it is /// and its projects, and picking another day is a redraw rather than a second /// read. A spanning occurrence appears once, on the day it starts: the grid /// says "something begins here", not "this day is covered". pub fn month(replica: &ReadFile<'_>, args: &Map) -> Result { let (from, to) = window(args)?; let reader_zone = day_reading_zone(args)?; let zone = expansion_zone(replica, args)?; let rows = event_candidates(replica, &to)?; // The selected day's rows say what the day's own say. let mut occurrences = expanded(replica, &rows, &from, &to, &zone)?; let mut todos = day_todos(replica, &from, &to)?; day_lines(replica, &mut occurrences, &mut todos, &from, &reader_zone)?; Ok(json!({ "occurrences": occurrences, "todos": todos, "timezone": reader_zone, })) } /// `/calendar/event/[id]` and `/calendar/event/edit` — one event, its guests, /// and the people a guest might be. /// /// An event that is not there answers `null` rather than refusing: a screen /// reached from a stale link draws "This event isn't here any more", and an /// error would make it draw a crash. **A trashed event answers its row**, with /// `trashedAt` set — the screen decides, exactly as the app's does, and folding /// the decision in here would take the deleted-and-still-syncing state off the /// screen that has to explain it. /// /// UNSCOPED, where `read.todo` and `read.location` in this same file carry /// `workspace_id = ?`, and the difference is the table rather than the rule: /// `cotton_events` has no workspace column — an event is the database's own, /// never reached through a calendar — so the primary key is the whole /// address here, exactly as `selectById` was in the app. The other two carry the clause because their /// tables have it and the narrower read is free. pub fn event(replica: &ReadFile<'_>, args: &Map) -> Result { let id = id_arg(args, "event")?; let row = replica .driver .get( &format!("SELECT {EVENT_COLUMNS} FROM cotton_events WHERE id = ?"), &[SqlValue::Text(id.clone())], ) .map_err(|error| error.to_string())?; let Some(row) = row else { // EVERY key the found branch emits, `calendarName` included. Swift's // synthesized `Decodable` calls `decode` — not `decodeIfPresent` — for // a NON-optional stored property, so an absent key throws whatever // default the property declares; `calendarName` is optional today and // would survive, but the rule this holds is the key SET, not the luck // of one field's optionality. `day_tests.rs` asserts it. return Ok(json!({ "event": Value::Null, "attendees": [], "people": [], "calendarName": Value::Null, "projects": [], "projectLinks": [], })); }; let attendees = replica .driver .all( "SELECT id, email, phone, display_name, response FROM cotton_event_attendees WHERE event_id = ? ORDER BY created_at ASC", &[SqlValue::Text(id.clone())], ) .map_err(|error| error.to_string())?; // The whole address book, as the app reads it: an attendee is matched to a // person by email here, and the edit screen's autocomplete offers the same // list. One read rather than a lookup per guest. let people = replica .driver .all( &format!( "SELECT id, full_name, {}, org FROM cotton_people WHERE workspace_id = ? AND archived_at IS NULL ORDER BY full_name ASC", cotton_core::rules::people::handles::phones_and_emails_sql("cotton_people.id") ), &[workspace(replica)], ) .map_err(|error| error.to_string())?; let calendar = calendar_name(replica, &row)?; let (projects, project_links) = record_projects(replica, "event", &id)?; Ok(json!({ "event": event_out(&row), "attendees": attendees .iter() .map(|row| json!({ "id": row.text("id"), "email": row.text("email"), "phone": row.text("phone"), "displayName": row.text("display_name"), "response": row.text("response"), })) .collect::>(), "people": people .iter() .map(|row| json!({ "id": row.text("id"), "fullName": row.text("full_name"), // JSON text columns, through the ONE reading of them: a list // that will not parse is a person with no addresses, never a // screen that will not draw. "emails": json_list(row.text("emails")), "phones": json_list(row.text("phones")), "org": row.text("org"), })) .collect::>(), // The provenance mark under the title: the calendar this event names, // where the file holds it, and none otherwise. "calendarName": calendar.map_or(Value::Null, Value::from), // The *Projects…* sheet, in the two shapes it decodes everywhere. "projects": projects, "projectLinks": project_links, })) } // ── /thoughts ─────────────────────────────────────────────────────────────── /// Every thought's pictures in this workspace, keyed by thought — one query /// for the whole ledger, never one per row. /// /// The row shape is `get_record`'s `attachments` entry (`kind`, `id`, /// `position`, `caption`, `recordCaption`, `title`, `key`, `missing`, `width`, /// `height`, `contentType`), because the phone already has one reader for that /// shape and a second spelling would be a second renderer. LEFT joins, so a /// picture since removed still answers with `missing: true` — the thought /// remembers asking for it. `key` is what `read.mediaPath` takes: a photo's own /// key, a video's POSTER key, a document's storage path. fn thought_attachments( replica: &ReadFile<'_>, ) -> Result>, String> { let rows = replica .driver .all( "SELECT a.thought_id, a.record_kind, a.record_id, a.caption, p.id AS photo_id, p.key AS photo_key, p.caption AS photo_caption, p.content_type AS photo_type, p.width AS photo_width, p.height AS photo_height, v.id AS video_id, v.poster_key AS video_key, v.caption AS video_caption, v.content_type AS video_type, v.width AS video_width, v.height AS video_height, d.id AS document_id, d.title AS document_title, d.mime AS document_mime, d.storage_path AS document_key FROM cotton_thought_attachments a LEFT JOIN cotton_photos p ON a.record_kind = 'photo' AND p.id = a.record_id AND p.trashed_at IS NULL LEFT JOIN cotton_videos v ON a.record_kind = 'video' AND v.id = a.record_id AND v.trashed_at IS NULL LEFT JOIN cotton_documents d ON a.record_kind = 'document' AND d.id = a.record_id AND d.trashed_at IS NULL WHERE a.workspace_id = ? ORDER BY a.thought_id, a.position, a.created_at, a.id", &[workspace(replica)], ) .map_err(|error| error.to_string())?; // A document's format is said by the database's `documents` lines (an // HTML page is a "Web page"), the same words `get_record` answers. let format_lines = cotton_core::rules::shell_lines::LineSet::of_rows( "documents", &cotton_tools::presentation::line_rows(replica.driver, replica.workspace_id), ); let mut out: std::collections::HashMap> = std::collections::HashMap::new(); for row in &rows { let Some(thought_id) = row.text("thought_id") else { continue }; let kind = row.text("record_kind").unwrap_or_default(); let list = out.entry(thought_id.to_string()).or_default(); // The answer's own order, not the stored number: two rows may share a // `position` while a reorder is half-applied. let position = list.len(); let mut item = json!({ "kind": kind, "id": row.text("record_id"), "position": position, "caption": row.text("caption"), }); let found = match kind { "photo" => row.text("photo_id").map(|_| json!({ "recordCaption": row.text("photo_caption"), "title": Value::Null, "key": row.text("photo_key"), "contentType": row.text("photo_type"), "width": row.int("photo_width"), "height": row.int("photo_height"), })), "video" => row.text("video_id").map(|_| json!({ "recordCaption": row.text("video_caption"), "title": Value::Null, "key": row.text("video_key"), "contentType": row.text("video_type"), "width": row.int("video_width"), "height": row.int("video_height"), })), _ => row.text("document_id").map(|_| json!({ "recordCaption": row.text("document_title"), "title": row.text("document_title"), "key": row.text("document_key"), "mime": row.text("document_mime"), })), }; match found { Some(Value::Object(fields)) => { item["missing"] = Value::Bool(false); for (name, value) in fields { item[name] = value; } // What the file is, said by the `documents` lines from its type. let mime = item["mime"].as_str().or(item["contentType"].as_str()); let format = cotton_core::rules::file_format::FileFormat::of(mime, None) .map_or(cotton_core::rules::file_format::FileFormat::UNKNOWN_LINE, |format| format.line()); item["format"] = format_lines.as_ref().and_then(|lines| lines.say(format, &[])).map_or(Value::Null, Value::from); } _ => { item["missing"] = Value::Bool(true); item["key"] = Value::Null; } } list.push(item); } Ok(out) } /// A JSON text column, parsed, or `null`. /// /// A column that will not parse reads as ABSENT rather than as an error: the /// whole chat must not go dark for one malformed row, and a capture with no /// plan still draws its own words. fn parsed(raw: Option<&str>) -> Value { raw.and_then(|raw| serde_json::from_str::(raw).ok()) .unwrap_or(Value::Null) } /// The `{kind, id}` pairs one capture landed as. /// /// `becameOf`'s rule, which the client's `routedRefs` implements identically: /// the RECORDS list is preferred whole, and the single `routed_kind`/`routed_id` /// pointer is the fallback for a row written before plans existed. fn routed_refs(row: &cotton_store::driver::Row) -> Vec<(String, String)> { if let Some(list) = row .text("routed_records") .and_then(|raw| serde_json::from_str::(raw).ok()) .and_then(|value| value.as_array().cloned()) { let refs: Vec<(String, String)> = list .iter() .filter_map(|entry| { Some(( entry.get("kind")?.as_str()?.to_string(), entry.get("id")?.as_str()?.to_string(), )) }) .collect(); if !refs.is_empty() { return refs; } } match (row.text("routed_kind"), row.text("routed_id")) { (Some(kind), Some(id)) => vec![(kind.to_string(), id.to_string())], _ => Vec::new(), } } /// How many ids go into one `IN (…)`. `inbox.service.ts`'s `SQL_IN_CHUNK`. const SQL_IN_CHUNK: usize = 200; /// The one fact a filed chip needs about the record it points at. /// /// `listRoutedFacts`, with its own reason kept: *"Four id-scoped reads /// regardless of how long the ledger is — the capture history needs a /// destination and a resolved date on every row, and one read per row would be /// an N+1 on the tool's own front screen."* Four reads, chunked at /// [`SQL_IN_CHUNK`], not one per reference. /// /// A chip says "due Mon 10 Aug" / "starts …" / "page for …" off `dateIso`; a /// person-note chip needs `personId`, and **without it must not navigate at /// all** — falling back to the note's own id pushes a person screen under the /// wrong id. A record since deleted simply does not come back and its chip /// falls to the bare kind; that is not an error. A `location` reference /// deliberately fetches nothing: a place has no date and no person, and asking /// a table for a fact it does not hold would be a query that answers nothing. fn routed_facts(replica: &ReadFile<'_>, refs: &[(String, String)]) -> Result { /// One id-scoped read of one column, chunked. fn fact_rows( replica: &ReadFile<'_>, table: &str, column: &str, ids: &[String], ) -> Result)>, String> { let mut out: Vec<(String, Option)> = Vec::new(); for batch in ids.chunks(SQL_IN_CHUNK) { // A projection of TEXT columns (ids, ISO timestamps, dates), so the // stored value IS the decoded value. The `IN` list is // PLACEHOLDERS — an id here is the owner's own data and never goes // into SQL as a literal. let holes = vec!["?"; batch.len()].join(","); let bound: Vec = batch.iter().cloned().map(SqlValue::Text).collect(); let rows = replica .driver .all( &format!( "SELECT id, {column} AS value FROM {table} WHERE id IN ({holes})" ), &bound, ) .map_err(|error| error.to_string())?; for row in &rows { let Some(id) = row.text("id") else { continue }; out.push((id.to_string(), row.text("value").map(str::to_string))); } } Ok(out) } let ids_for = |kinds: &[&str]| -> Vec { refs.iter() .filter(|(kind, _)| kinds.contains(&kind.as_str())) .map(|(_, id)| id.clone()) .collect() }; let mut facts = Map::new(); let mut put = |id: String, date: Option, person: Option| { let mut fact = Map::new(); fact.insert("dateIso".to_string(), date.map_or(Value::Null, Value::from)); fact.insert("personId".to_string(), person.map_or(Value::Null, Value::from)); facts.insert(id, Value::Object(fact)); }; for (id, value) in fact_rows(replica, "cotton_todos", "due_at", &ids_for(&["todo"]))? { put(id, value, None); } for (id, value) in fact_rows(replica, "cotton_events", "starts_at", &ids_for(&["event"]))? { put(id, value, None); } for (id, value) in fact_rows( replica, "cotton_notes", "journal_date", &ids_for(&["note", "journal"]), )? { put(id, value, None); } for (id, value) in fact_rows( replica, "cotton_person_notes", "person_id", &ids_for(&["person_note"]), )? { put(id, None, value); } Ok(Value::Object(facts)) } /// `/thoughts` — the whole capture ledger, and what each one became. /// /// **A SIBLING of `list_thoughts`, not a caller of it.** That tool is an /// assistant's reading and answers a different question: it filters to open /// captures by default, caps at 100, folds a voice note's transcript into one /// `text`, and collapses filing / proposal / plain-thought into one word. The /// chat is an unpaginated read of everything the person ever said, dismissed /// rows included, and it draws three different attachments off distinctions /// that word erases. Five columns the tool does not read are the whole of why: /// /// * `route_confidence` — `filingHand`. Without it the chat cannot tell a /// CORRECTION (the caption says "corrected") from a hand-filing of something /// the router abstained on (the caption says nothing); /// * `route_proposal` — the entire proposal outcome: the chips, the atomic /// file, the runner-up kind `whyItStopped` names; /// * `sweep_note` — the sweep's own sentence, which REPLACES the filed caption; /// * `audio_url` — the app draws the spoken mark and the voice pill off it, and /// the point of the mark is that the transcript is checkable against the /// take. Folding it into `text` makes a spoken capture indistinguishable from /// a typed one. /// /// The one rule worth sharing verbatim IS shared: `routed_refs` here is /// `becameOf`'s records-preferred, pointer-fallback merge, which the client's /// own `routedRefs` implements the same way. pub fn thoughts(replica: &ReadFile<'_>, _args: &Map) -> Result { let rows = replica .driver .all( "SELECT id, raw_text, audio_url, captured_at, route_status, route_reason, route_confidence, routed_kind, routed_id, routed_records, route_proposal, sweep_note, swept_at FROM cotton_inbox_items WHERE workspace_id = ? ORDER BY captured_at DESC", &[workspace(replica)], ) .map_err(|error| error.to_string())?; let mut pictures = thought_attachments(replica)?; let mut refs: Vec<(String, String)> = Vec::new(); let thoughts: Vec = rows .iter() .map(|row| { // A dismissed capture landed as nothing, so it contributes no // reference — asking after records it never made would be a lookup // per row for an answer that is always empty. if row.text("route_status") != Some("dismissed") { for reference in routed_refs(row) { if !refs.contains(&reference) { refs.push(reference); } } } json!({ "id": row.text("id"), "rawText": row.text("raw_text"), "audioUrl": row.text("audio_url"), "capturedAt": row.text("captured_at"), "routeStatus": row.text("route_status"), "routeReason": row.text("route_reason"), // Stored as TEXT, read as the number the hand test compares. "routeConfidence": row .text("route_confidence") .and_then(|raw| raw.parse::().ok()) .map_or(Value::Null, |value| json!(value)), "routedKind": row.text("routed_kind"), "routedId": row.text("routed_id"), "routedRecords": parsed(row.text("routed_records")), "routeProposal": parsed(row.text("route_proposal")), "sweepNote": row.text("sweep_note"), "sweptAt": row.text("swept_at"), // The pictures on it, in its own order — `get_record`'s row // shape, so the phone draws a thought's screenshot with the // same code that draws a note's. "attachments": row .text("id") .and_then(|id| pictures.remove(id)) .unwrap_or_default(), }) }) .collect(); // The vocabulary every row needs and none of them may fetch for itself: a // person note is named by its person, a money chip by its account, the // router's project proposal by the project, and `planFilable`'s event check // by the calendars. let names = |sql: &str| -> Result, String> { Ok(replica .driver .all(sql, &[workspace(replica)]) .map_err(|error| error.to_string())? .iter() .map(|row| { json!({ "id": row.text("id"), "name": row.text("name"), }) }) .collect()) }; Ok(json!({ "thoughts": thoughts, "routedFacts": routed_facts(replica, &refs)?, "people": replica .driver .all( "SELECT id, full_name FROM cotton_people WHERE workspace_id = ? AND archived_at IS NULL ORDER BY full_name ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())? .iter() .map(|row| json!({ "id": row.text("id"), "fullName": row.text("full_name") })) .collect::>(), "moneyAccounts": names( "SELECT id, name FROM cotton_money_accounts WHERE workspace_id = ? ORDER BY name ASC", )?, // EVERY project, retired ones included — `memoriesService.listProjects` // has no status filter and this is a VOCABULARY, not an offer: its one // job is to turn the id a router proposal already carries into a name. // Filtering to `status = 'active'` made a proposal naming a // since-archived project draw the bare uuid, and put this file's // reading of `cotton_memory_projects` at odds with `person.rs`'s, which // takes them all for the same reason. // // THIS IS THE PHONE'S COMPLETE PROJECT VOCABULARY — id, slug, name, // status — and the next reader needing a project fact on this boundary // should stop looking after this line. The other project list, `read. // projects`, is `list_projects` → `project_out`, an ASSISTANT-facing // shape that answers slug, name and status and deliberately no id; it // is not widened so a screen can resolve one, because what a model is // shown is not a place to keep the phone's join keys. // // Each of the four is load bearing somewhere: // · `id` turns the id a router proposal already carries into a name, // and is what `session.send` demands — it refuses anything but a // real `cotton_memory_projects` row id (`phone/session.rs:170-180`). // · `slug` is what `link_to_project` takes, while the app holds the // project by id — `PendingLinks`' drain settles a `#` chip through // exactly that translation, and with no list answering both halves // a chip could be remembered and never settled. // · `status` is how a CALLER narrows a list this read will not narrow // for it: the picker offers active projects only // (`thoughts/index.tsx:205-209`). // // THE LIST IS DELIBERATELY UNFILTERED — do not re-add `status = // 'active'` (that is S9, and the reason is two paragraphs up). It now // carries a WRITE as well as a drawing: filtered, a chip on a // since-archived project would be unsettleable rather than merely // unnamed, which is the worse of the two failures by a distance. "projects": replica .driver .all( "SELECT id, slug, name, status FROM cotton_memory_projects WHERE workspace_id = ? ORDER BY name ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())? .iter() .map(|row| json!({ "id": row.text("id"), "slug": row.text("slug"), "name": row.text("name"), "status": row.text("status"), })) .collect::>(), "collections": replica .driver .all( "SELECT id, kind, archived_at FROM cotton_collections WHERE workspace_id = ? ORDER BY created_at ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())? .iter() .map(|row| json!({ "id": row.text("id"), "kind": row.text("kind"), "archivedAt": row.text("archived_at"), })) .collect::>(), })) } // ── /locations ────────────────────────────────────────────────────────────── /// `/locations/location/[id]` — one place, and the projects it is in. /// /// SPLIT OUT OF `read.record`, the same correction `read.goal` is one entry /// above. `read.record` is bound to `get_record`, which is an ASSISTANT's tool: /// its shape is what a model is shown, and widening it so one phone screen can /// draw a sheet would put a phone's need into a model's vocabulary. So the /// place page gets its own read, exactly as the goal page does. /// /// THE ROW'S SHAPE IS UNCHANGED — the same seven values `LOCATION_COLUMNS` /// answers, under the same key names including `created_at`'s snake case, so /// the screen's decoder needs nothing but the two new keys. `openComments` is /// deliberately not carried: the tool surfaces it on every kind so an assistant /// reading a record is told there is a conversation about it, and this screen /// does not draw one. /// /// A place that is not there answers `null` rather than refusing, the reading /// every detail read in this file takes of a stale deep link. pub fn location(replica: &ReadFile<'_>, args: &Map) -> Result { let id = id_arg(args, "place")?; let row = replica .driver .get( "SELECT id, name, address, note, lat, lng, created_at FROM cotton_locations WHERE workspace_id = ? AND id = ?", &[workspace(replica), SqlValue::Text(id.clone())], ) .map_err(|error| error.to_string())?; let Some(row) = row else { // EVERY key the found branch emits — a branch one key short throws in // Swift rather than falling back to its default. return Ok(json!({ "location": Value::Null, "projects": [], "projectLinks": [], })); }; let (projects, project_links) = record_projects(replica, "location", &id)?; Ok(json!({ "location": { "id": row.text("id"), "name": row.text("name"), "address": row.text("address"), "note": row.text("note"), "lat": row.real("lat"), "lng": row.real("lng"), "created_at": row.text("created_at"), }, "projects": projects, "projectLinks": project_links, })) } /// `/locations` — the places, and how many records name each one. /// /// `locationsService.listLocations`, and both clauses are load bearing: /// `workspace_id` because one file can hold more than one workspace row, and /// `archived_at IS NULL` because the archive is SOFT — without it every place /// somebody put away returns to both the list and the map. /// /// `ORDER BY name ASC` is the rendered order and there is no client re-sort, so /// it is load bearing too. It is SQLite's BINARY collation, deliberately left /// alone: switching to a locale collation here would silently reorder a list /// the person has learned the shape of. /// /// THE LINK COUNT IS ONE GROUPED COUNT, not one query per place. The app fans /// out `listLinksForRecord` per location and its own comment names the fix /// (`countLinksForKind`); the numbers are the same, and the two-direction OR /// that makes them right — an edge may name the place at either end, and one /// side alone under-counts — is kept exactly. pub fn locations(replica: &ReadFile<'_>, _args: &Map) -> Result { let rows = replica .driver .all( "SELECT id, name, address, lat, lng, note, updated_at FROM cotton_locations WHERE workspace_id = ? AND archived_at IS NULL ORDER BY name ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())?; let counts = replica .driver .all( // `UNION ALL`, not `UNION`: an edge between two DIFFERENT places // is one for each of them, and collapsing duplicates would lose the // second. The one shape it counts twice is a place linked to // ITSELF, which `cotton_links`' kinds admit and no surface can // write — the app's per-record `OR` counted such an edge once. // Left as it is rather than filtered: the filter would be a clause // guarding a row that does not exist, and this comment is the // cheaper record of it. "SELECT place, COUNT(*) AS n FROM ( SELECT from_id AS place FROM cotton_links WHERE workspace_id = ? AND from_kind = 'location' UNION ALL SELECT to_id AS place FROM cotton_links WHERE workspace_id = ? AND to_kind = 'location' ) GROUP BY place", &[workspace(replica), workspace(replica)], ) .map_err(|error| error.to_string())?; Ok(json!({ "locations": rows .iter() .map(|row| { let id = row.text("id").unwrap_or_default(); json!({ "id": id, "name": row.text("name"), "address": row.text("address"), // The pin, and the pin's absence: a place with no // coordinates is in the list and off the map, and the map // says how many of those there are rather than pretending // they are somewhere. "lat": row.real("lat"), "lng": row.real("lng"), "note": row.text("note"), // When the place was last written — the list's "Recent" // rows are the two most lately touched. "updatedAt": row.text("updated_at"), "linkCount": counts .iter() .find(|count| count.text("place") == Some(id)) .and_then(|count| count.int("n")) .unwrap_or(0), }) }) .collect::>(), })) } // ── /goals ────────────────────────────────────────────────────────────────── /// `/goals` — every goal, in the order the person put them in. /// /// ONE READ, NOT TWO, and the service says why: the screen draws the live goals /// and the "Behind you" section from the same list, and splitting it would mean /// two caches that can disagree about a goal the owner just achieved. So there /// is deliberately **no status filter and no archive filter** — all four /// statuses come back and the device does the partition. /// /// The order here is the fractional hand-order plus `created_at` as the /// tiebreak. The screen re-sorts (live goals by hand, finished ones by when /// they were reached, newest first), but this order is what makes two goals at /// the same position resolve the same way on every device. /// /// `why` travels even though this screen never draws it — the detail screen /// does, and it is one column. pub fn goals(replica: &ReadFile<'_>, _args: &Map) -> Result { let rows = replica .driver .all( "SELECT id, title, why, target_date, status, achieved_at, sort_order, created_at, updated_at FROM cotton_goals WHERE workspace_id = ? AND trashed_at IS NULL ORDER BY sort_order IS NULL, sort_order ASC, created_at ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())?; Ok(json!({ "goals": rows .iter() .map(|row| { json!({ "id": row.text("id"), "title": row.text("title"), "why": row.text("why"), "targetDate": row.text("target_date"), "status": row.text("status"), "achievedAt": row.text("achieved_at"), // `REAL NOT NULL DEFAULT 0`; the `IS NULL` term in the // order above is the defensive half of the same reading. "sortOrder": row.real("sort_order").unwrap_or(0.0), "createdAt": row.text("created_at"), "updatedAt": row.text("updated_at"), }) }) .collect::>(), })) } // ── /people/import ────────────────────────────────────────────────────────── /// `/people/import` — which of this device's contacts are already people here, /// and what the mirror would change if it ran. /// /// The screen's own question is small: the set of `device_contact_id`s, which /// is what "Already in People" and the linked count are made of. It is /// answered with a projection rather than `SELECT *` because the same set is /// the idempotence guard behind `uq_cotton_people_device_contact`, and it is /// read on every pass. /// /// `archived_at IS NULL` is load bearing twice over: an archived person must /// not count toward the linked figure, and their device contact must not read /// as "already in People" — the person is out of the directory, and offering /// their card as taken would make them unreachable. /// /// The mirror's planning fields ride along, because the dry-run diffs a /// person's own fields against the SNAPSHOT of the card they were last read /// from, and a second read for them would be a second answer to who is linked. /// **The plan itself is not computed here**: it compares against the DEVICE's /// address book, which no core can see. /// /// TWO FACTS THIS READ DELIBERATELY DOES NOT ANSWER, because they are not in /// the file and must not be: when this device last ran a sync, and whether the /// owner has confirmed the mirror. Both are per-DEVICE — `device_contact_id` is /// a fact about one address book, and the confirmation is a promise made about /// one — so they live in the app's own local storage, keyed by workspace. pub fn people_import(replica: &ReadFile<'_>, _args: &Map) -> Result { use cotton_core::rules::people::birthday::{columns_sql, whole_held, Birthday, PEOPLE_TABLE}; let held = whole_held(replica.driver).map_err(|error| error.to_string())?; let rows = replica .driver .all( &format!( "SELECT id, full_name, {}, org, role_title, {}, avatar_key, device_contact_id, device_contact_snapshot FROM cotton_people WHERE workspace_id = ? AND archived_at IS NULL AND device_contact_id IS NOT NULL ORDER BY full_name ASC", cotton_core::rules::people::handles::phones_and_emails_sql("cotton_people.id"), columns_sql(PEOPLE_TABLE, held) ), &[workspace(replica)], ) .map_err(|error| error.to_string())?; let linked: Vec = rows .iter() .map(|row| { json!({ "id": row.text("id"), "fullName": row.text("full_name"), // The SAME reading as everywhere else. `parsed` answers a bare // `null` on unparseable text, and `[String]` on the Swift side // decodes non-optionally: this was the one of the three that // could hand the boundary a null. "phones": json_list(row.text("phones")), "emails": json_list(row.text("emails")), "org": row.text("org"), "roleTitle": row.text("role_title"), // One fact, by `cotton_core::rules::people::birthday`'s one // rule: the three columns where set, else the date a // signed-in copy keeps whole from the object. The year is // separately optional because iOS says "a birthday with no // year" and means it. "birthday": Birthday::of_row(row).map_or(Value::Null, |birthday| json!({ "month": birthday.month, "day": birthday.day, "year": birthday.year, })), "avatarKey": row.text("avatar_key"), "deviceContactId": row.text("device_contact_id"), "deviceContactSnapshot": parsed(row.text("device_contact_snapshot")), }) }) .collect(); Ok(json!({ "linked": linked, // The figure the bar reads out, counted here rather than by the screen // walking the whole directory to filter it. "linkedCount": rows.len(), })) } // ── /todos, /todos/done, /todos/dropped ───────────────────────────────────── /// The columns every todo surface draws with. const TODO_COLUMNS: &str = "id, title, notes, status, due_at, snoozed_until, priority, \ completed_at, source_inbox_id, recurrence_id, created_at, updated_at"; /// One todo, in the app's own camel case. fn todo_out(row: &cotton_store::driver::Row) -> Value { json!({ "id": row.text("id"), "title": row.text("title"), "notes": row.text("notes"), "status": row.text("status"), "dueAt": row.text("due_at"), "snoozedUntil": row.text("snoozed_until"), "priority": row.int("priority").unwrap_or(0), "completedAt": row.text("completed_at"), "sourceInboxId": row.text("source_inbox_id"), // The ID, not a `repeating: true` — the repeat sheet reshapes THIS // series and needs to name it, and a boolean cannot. "recurrenceId": row.text("recurrence_id"), "createdAt": row.text("created_at"), // The dropped list groups by the day a todo was last touched, because // there is no `dropped_at` column to group by. "updatedAt": row.text("updated_at"), }) } /// `/todos`, `/todos/done` and `/todos/dropped` — the pool, and the dropped. /// /// **A SIBLING of `list_todos`, not a caller of it.** That tool is an /// assistant's reading and cannot draw these screens: it pages (`limit`, and a /// `more` flag), it answers `repeating: true` where the repeat editor needs the /// series' ID, it answers `priority: "high"` where the detail screen toggles a /// number, and it answers no `updatedAt` — which is the only column the dropped /// list can group by, since nothing records when a todo was let go. /// /// TWO QUERIES, because the app makes two: the POOL excludes dropped rows and /// carries open and done together (the timeline, the done list and the /// project narrowing all read it), and the DROPPED list is its own read in its /// own order. Folding them into one would make "dropped" a client filter over a /// list that is ordered for a different question. /// /// The pool's `status IN ('open', 'done')` is load bearing: a todo somebody /// let go must not come back onto their day, and a missed occurrence a later /// tick cleared is neither owed nor done. The `due_at IS NULL` term leading the pool's order is /// what reproduces "undated last" — SQLite would otherwise sort every undated /// todo above every dated one. /// /// **`project` NARROWS BOTH LISTS, AND A PROJECT THAT RESOLVES TO NOTHING /// NARROWS TO NOTHING.** The argument is **the project's id or its slug, /// resolved in that order**, because the two screens that reach this read /// carry different things and neither side can convert: `/todos/done` and /// `/todos/dropped` carry an ID (`routes.ts`'s `PROJECT_SCOPE_PARAM`, through /// `donePath(projectId)` / `droppedPath(projectId)`), while /// `/projects/[slug]/todos` has only the SLUG — and the roster the phone holds /// comes from `list_projects`, whose `project_out` writes slug, name, status, /// description and repos and never an id. The narrowing itself is the /// INTERSECTION of the project's todo edges with the pool, which is /// `narrowToScope`'s own rule: the edge says a todo belongs here and the pool /// says what state it is in, and only one of them can answer "is this still /// open". /// /// The safe-by-default half is the part that must not be lost. `EMPTY_SCOPE` /// (`TodosTimeline.tsx:119-120, 170-183`) exists because a screen that NAMED a /// project and could not resolve its membership must show NOTHING: *"The /// fallback would be every todo in the database sitting under one project's /// title, which is the silent fallback this repo bans wearing its worst face — /// a wrong answer that looks like a right one."* A project that is not there, /// or holds no todos, therefore answers two empty lists here, never the /// workspace's own. A value that resolves as NEITHER an id nor a slug is /// exactly that case, so it takes the same empty answer rather than the pool. /// /// **`projectName` is the resolved project's name, and is present on every /// branch** — `null` when no `project` was named AND `null` when one was named /// and resolved to nothing. Those two nulls mean the same thing about the /// TITLE and opposite things about the ROWS: an unscoped screen shows the /// whole pool, an unresolvable one shows nothing, because the empty scope /// still empties the lists. Read the null as "there is no title to draw", /// never as "this screen is unscoped". The name comes out of the same lookup /// that resolved the argument, so the scoped screens need no roster read of /// their own — which is what `useProjectTodoScope` answered on the other side /// (`{ scopeIds, projectName, isPending }`), and `list_projects` cannot, /// because `project_out` writes no id to match on. pub fn todos(replica: &ReadFile<'_>, args: &Map) -> Result { let project = args .get("project") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()); // The project's todo edges, when one was named. `None` is "no narrowing was // asked for" and an EMPTY LIST is "this project holds no todos" — the two // are different answers and collapsing them is the bug above. // One lookup, id BEFORE slug: `id = ?` sorts first, so a slug that happens // to spell another project's id still loses to the id. It carries the NAME // out with it, which is the whole of `projectName` below. let resolved: Option<(String, String)> = match project { None => None, Some(project) => replica .driver .all( "SELECT id, name FROM cotton_memory_projects WHERE workspace_id = ? AND (id = ? OR slug = ?) ORDER BY (id = ?) DESC LIMIT 1", &[ workspace(replica), SqlValue::Text(project.to_string()), SqlValue::Text(project.to_string()), SqlValue::Text(project.to_string()), ], ) .map_err(|error| error.to_string())? .first() .and_then(|row| { let id = row.text("id")?.to_string(); let name = row.text("name")?.to_string(); Some((id, name)) }), }; let scope: Option> = match (project, &resolved) { (None, _) => None, // Named but unresolvable: the empty scope, never the whole pool. (Some(_), None) => Some(Vec::new()), (Some(_), Some((id, _))) => Some( replica .driver .all( "SELECT record_id FROM cotton_project_links WHERE project_id = ? AND record_kind = 'todo'", &[SqlValue::Text(id.clone())], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| row.text("record_id").map(str::to_string)) .collect(), ), }; let read = |status_clause: &str, order: &str| -> Result, String> { // A scope of zero ids answers nothing without asking the file: `IN ()` // is not SQL, and the honest answer to "this project holds no todos" is // an empty list rather than a query. let holes = match &scope { Some(ids) if ids.is_empty() => return Ok(Vec::new()), Some(ids) => format!(" AND id IN ({})", vec!["?"; ids.len()].join(",")), None => String::new(), }; let mut bound = vec![workspace(replica)]; if let Some(ids) = &scope { bound.extend(ids.iter().cloned().map(SqlValue::Text)); } Ok(replica .driver .all( &format!( "SELECT {TODO_COLUMNS} FROM cotton_todos WHERE workspace_id = ? AND trashed_at IS NULL AND {status_clause}{holes} ORDER BY {order}" ), &bound, ) .map_err(|error| error.to_string())? .iter() .map(todo_out) .collect()) }; let mut todos = read("status IN ('open', 'done')", "due_at IS NULL, due_at ASC, created_at ASC")?; let mut dropped = read("status = 'dropped'", "updated_at DESC, created_at DESC")?; attach_todo_projects(replica, &mut todos, &mut dropped)?; Ok(json!({ "todos": todos, "dropped": dropped, "projectName": match &resolved { Some((_, name)) => Value::String(name.clone()), None => Value::Null, }, })) } // ── /todos/todo/[id] ──────────────────────────────────────────────────────── /// The card's project chips, for EVERY todo the list read answered — ONE query /// over `cotton_project_links` for the whole list, never one per row: the /// board draws every todo at once, and a screen of two hundred cards is not /// two hundred reads. Lifted from what the single `todo` read does with /// `record_projects`, kept to the three things a chip draws (`id`, `slug`, /// `name`), archived projects included for the same reason as there. A todo /// with no link answers `projects: []`, never a missing key. fn attach_todo_projects( replica: &ReadFile<'_>, todos: &mut [Value], dropped: &mut [Value], ) -> Result<(), String> { let mut by_todo: HashMap> = HashMap::new(); for row in replica .driver .all( "SELECT l.record_id, p.id, p.slug, p.name FROM cotton_project_links l JOIN cotton_memory_projects p ON p.id = l.project_id WHERE l.workspace_id = ? AND l.record_kind = 'todo' ORDER BY p.created_at ASC, p.id ASC", &[workspace(replica)], ) .map_err(|error| error.to_string())? { let Some(todo_id) = row.text("record_id") else { continue; }; by_todo.entry(todo_id.to_string()).or_default().push(json!({ "id": row.text("id"), "slug": row.text("slug"), "name": row.text("name"), })); } for todo in todos.iter_mut().chain(dropped.iter_mut()) { let projects = todo .get("id") .and_then(Value::as_str) .and_then(|id| by_todo.get(id).cloned()) .unwrap_or_default(); if let Some(object) = todo.as_object_mut() { object.insert("projects".to_string(), Value::Array(projects)); } } Ok(()) } /// `/todos/todo/[id]` — one todo, and the rule it repeats by. /// /// `read.record` cannot answer this and the reason is the same one the goal /// read was split out for: `get_record`'s todo shape is the assistant's, and /// this screen needs the series id (to reshape or stop the repeat), the raw /// priority number (which it toggles), `sourceInboxId` (the capture trail) and /// the template itself. /// /// A todo that is not there answers `null` rather than refusing: a stale link /// draws "This todo isn't here any more", and an error would make it draw a /// crash. The TEMPLATE is `null` when there is no `recurrence_id` — the ONE /// reachable absence: `PRAGMA foreign_keys` is on and asserted at every open /// (`driver_tests.rs`), and the column is `ON DELETE SET NULL`, so a todo /// pointing at a rule that is not in the file cannot exist. The `None` arm of /// the lookup below is the type's own totality, not a state to design for. pub fn todo(replica: &ReadFile<'_>, args: &Map) -> Result { let id = id_arg(args, "todo")?; let row = replica .driver .get( &format!("SELECT {TODO_COLUMNS} FROM cotton_todos WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL"), &[workspace(replica), SqlValue::Text(id.clone())], ) .map_err(|error| error.to_string())?; let Some(row) = row else { return Ok(json!({ "todo": Value::Null, "recurrence": Value::Null, "projects": [], "projectLinks": [], })); }; let template = match row.text("recurrence_id") { None => Value::Null, Some(recurrence) => replica .driver .get( "SELECT id, title, notes, priority, rrule, dtstart, paused, materialized_until FROM cotton_todo_recurrences WHERE id = ?", &[SqlValue::Text(recurrence.to_string())], ) .map_err(|error| error.to_string())? .map_or(Value::Null, |rule| { json!({ "id": rule.text("id"), "title": rule.text("title"), "notes": rule.text("notes"), "priority": rule.int("priority").unwrap_or(0), "rrule": rule.text("rrule"), "dtstart": rule.text("dtstart"), "paused": rule.int("paused").unwrap_or(0) != 0, // A MARK, never a schedule: everything up to it has been // projected, and it must never go backwards. "materializedUntil": rule.text("materialized_until"), }) }), }; let (projects, project_links) = record_projects(replica, "todo", &id)?; Ok(json!({ "todo": todo_out(&row), "recurrence": template, "projects": projects, "projectLinks": project_links, })) } /// Does this instant STATE an hour? Local hour or minute non-zero. /// /// It deliberately ignores seconds: a due time of 00:00:30 is a date, not an /// appointment. pub(crate) fn has_clock_time(at_ms: i64, zone: &str) -> Result { let parts = cotton_core::transforms::zoned_clock::zoned_parts(at_ms, zone)?; Ok(parts.hour != 0 || parts.minute != 0) } // Gated on the FEATURE as well as on `test`: the fixture helper these use // (`shell::client::phone_tests`) is itself phone-only, so a host-flavoured // `cargo test` would fail to resolve it — which is exactly what // `pnpm rust:verify` caught. #[cfg(test)] #[path = "day_tests.rs"] mod tests;