//! SAMPLE RECORDS (This Device's Add sample records / Remove sample records, //! owner's direction 22 Oct 2026): a deck full of cards to move between, //! made of invented todos and calendar events and taken away again. //! //! - **Add** makes about fifteen todos, one or more in every pace band (late, //! today, soon, upcoming, someday, done), and ten timed events over the next //! two weeks — one earlier today, two more today. Every date is set from //! the injected clock in the device's zone at the moment of the add, so the //! deck shows every band whenever it is pressed. Each is an ordinary create //! through the shared writer, under the byline [`SAMPLE_BYLINE`]. //! - **The marker** is that byline on the record's create change //! (`cotton_changes`: verb `create`, byline `sample`), a typed value no //! later edit rewrites — a sample marked done is still a sample. No words. //! - **Remove** bins exactly the live records so marked, each through the //! shared delete like any other, and touches nothing else. //! //! Titles and receipts are lines of set `samples`; nothing here is a word a //! person reads. use cotton_core::rules::shell_lines; use cotton_core::transforms::moment_split::{join_moment, MomentSplit}; use cotton_core::transforms::zoned_clock::{civil_from_days, day_number, zoned_parts}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use super::{create_sample_record, delete_record, sql_err, ToolResult, Valid, SAMPLE_BYLINE}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{iso_of_ms, now_ms, parse_ms}; use crate::mcp::protocol::ToolFailure; /// The line set every word here comes from. pub const LINES: &str = "samples"; /// The shipped tables samples are made in. pub const TABLES: [&str; 2] = ["todo", "event"]; /// Where a sample's date falls, from the reader's local now. #[derive(Debug, Clone, Copy)] enum When { /// No date at all. Never, /// A bare day, this many days from today. Day(i64), /// A clock time (minutes after midnight, never 0) this many days from today. At(i64, i64), /// Today, a little before now. EarlierToday, /// Today, a little after now. LaterToday, /// This evening, or tomorrow evening once the evening has begun. Tonight, } /// One sample todo: its title's line, its date, whether it is finished. const TODOS: [(&str, When, bool); 15] = [ ("todos.late_week", When::Day(-5), false), ("todos.late_yesterday", When::At(-1, 18 * 60), false), ("todos.late_earlier", When::EarlierToday, false), ("todos.today_day", When::Day(0), false), ("todos.today_later", When::LaterToday, false), ("todos.soon_morning", When::At(1, 9 * 60), false), ("todos.soon_tomorrow", When::Day(1), false), ("todos.soon_two_days", When::Day(2), false), ("todos.upcoming_four", When::Day(4), false), ("todos.upcoming_week", When::At(7, 10 * 60 + 30), false), ("todos.upcoming_twelve", When::Day(12), false), ("todos.someday_shelf", When::Never, false), ("todos.someday_language", When::Never, false), ("todos.done_filter", When::Day(-2), true), ("todos.done_passport", When::Day(-1), true), ]; /// One sample event: its title's line, its start, how many minutes it lasts. const EVENTS: [(&str, When, i64); 10] = [ ("events.earlier_today", When::EarlierToday, 45), ("events.later_today", When::LaterToday, 60), ("events.tonight", When::Tonight, 120), ("events.tomorrow", When::At(1, 8 * 60), 60), ("events.two_days", When::At(2, 17 * 60 + 30), 45), ("events.three_days", When::At(3, 12 * 60 + 30), 90), ("events.five_days", When::At(5, 9 * 60), 180), ("events.week", When::At(7, 10 * 60), 120), ("events.nine_days", When::At(9, 18 * 60), 150), ("events.thirteen_days", When::At(13, 7 * 60 + 15), 120), ]; const MINUTES_IN_DAY: i64 = 24 * 60; const QUARTER: i64 = 15; const MINUTE_MS: i64 = 60_000; /// `when` as (days from today, minute of the day; 0 for a bare day) against /// the local `minute_now`; `None` for no date. fn placed(when: When, minute_now: i64) -> Option<(i64, i64)> { match when { When::Never => None, When::Day(days) => Some((days, 0)), When::At(days, minute) => Some((days, minute)), When::EarlierToday => { let minute = (minute_now - 60).div_euclid(QUARTER) * QUARTER; // Just after midnight there is no earlier today with a clock // time; last night stands in, still behind. Some(if minute >= QUARTER { (0, minute) } else { (-1, 23 * 60) }) } When::LaterToday => { let minute = (minute_now + 90 + QUARTER - 1).div_euclid(QUARTER) * QUARTER; Some(if minute < MINUTES_IN_DAY { (0, minute) } else { (1, 9 * 60) }) } When::Tonight => Some(if minute_now < 19 * 60 { (0, 19 * 60 + 30) } else { (1, 19 * 60 + 30) }), } } /// The stored instant for (days, minute) from local `today` in `zone`. fn instant(zone: &str, today: i64, (days, minute): (i64, i64)) -> Valid { let (year, month, day) = civil_from_days(today + days); let moment = MomentSplit { date: format!("{year:04}-{month:02}-{day:02}"), time: (minute != 0).then(|| format!("{:02}:{:02}", minute / 60, minute % 60)), }; join_moment(&moment, zone).map_err(|error| ToolFailure::new(error.to_string())) } /// One line of the set, said with this database's rows. fn line(ctx: &Ctx<'_>, which: &str, fills: &[(&str, &str)]) -> Valid { let rows = crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); shell_lines::resolve(LINES, which, &rows, fills).ok_or_else(|| ToolFailure::new(format!("{LINES}.{which}"))) } /// A count's line: `{n}` grouped, its plural picked by it. fn counted(ctx: &Ctx<'_>, which: &str, n: usize) -> Valid { let n = shell_lines::number(i64::try_from(n).unwrap_or(i64::MAX)); line(ctx, which, &[("n", &n)]) } /// Every live sample record, `(table, id)`, oldest first: made under the /// sample byline and neither binned nor gone. pub fn live(ctx: &Ctx<'_>) -> Valid> { let mut found = Vec::new(); let tables = ctx.db().all( "SELECT DISTINCT table_id FROM cotton_changes WHERE workspace_id = ? AND verb = 'create' AND byline = ?", &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(SAMPLE_BYLINE.into())], ).map_err(sql_err)?; for row in tables { let table = row.text("table_id").ok_or_else(|| ToolFailure::new("a sample change names no table"))?; let definition = super::definition(ctx, table)?; let sql = "SELECT record_id AS id FROM cotton_changes \ WHERE workspace_id = ? AND table_id = ? AND verb = ? AND byline = ? \ ORDER BY created_at, record_id"; let rows = ctx .read .driver() .all( sql, &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(table.into()), SqlValue::Text(cotton_core::records::Verb::Create.as_str().into()), SqlValue::Text(SAMPLE_BYLINE.into()), ], ) .map_err(sql_err)?; for row in rows { if let Some(id) = row.text("id") { if super::load(ctx, &definition, id)?.is_some_and(|row| row.deleted_at.is_none()) && !found.iter().any(|(_, held): &(String, String)| held == id) { found.push((table.to_string(), id.to_string())); } } } } Ok(found) } /// Add sample records, dated from now in `zone`. While samples from an /// earlier add are still here it adds nothing and says how many there are. /// Answers `{receipt, added, todos, events}`. pub fn add(ctx: &mut Ctx<'_>, zone: &str) -> ToolResult { let here = live(ctx)?.len(); if here > 0 { return Ok(json!({ "receipt": counted(ctx, "already", here)?, "added": 0 })); } let now = zoned_parts(now_ms(ctx), zone).map_err(|error| ToolFailure::new(error.to_string()))?; let today = day_number(now.year, now.month, now.day); let minute_now = now.hour * 60 + now.minute; // Events first: the one that can be refused (no calendar yet) is // refused before anything is made. let mut events = Vec::new(); for (which, when, minutes) in EVENTS { let at = placed(when, minute_now).expect("every sample event has a time"); let starts = instant(zone, today, at)?; let ends = parse_ms(&starts) .map(|ms| iso_of_ms(ms + minutes * MINUTE_MS)) .ok_or_else(|| ToolFailure::new(starts.clone()))?; let data = json!({ "title": line(ctx, which, &[])?, "starts_at": starts, "ends_at": ends }); let written = create_sample_record(ctx, "event", &data)?; events.extend(made_id(&written)); } let mut todos = Vec::new(); for (which, when, done) in TODOS { let mut data = Map::new(); data.insert("title".into(), Value::from(line(ctx, which, &[])?)); if let Some(at) = placed(when, minute_now) { data.insert("due_at".into(), Value::from(instant(zone, today, at)?)); } if done { data.insert("status".into(), Value::from("done")); } let written = create_sample_record(ctx, "todo", &Value::Object(data))?; todos.extend(made_id(&written)); } // Samples belong to the installed kit tool's package, never a second // registry of tool ids here. The dated todo/event examples above remain // relative to this device's clock. let tools = crate::definitions::tool_definitions(ctx)?.definitions; let mut kit_records = 0; for tool in tools { let Some(package) = cotton_core::kit::package(&tool.id) else { continue }; let package = package.map_err(|error| ToolFailure::new(error.to_string()))?; // A sample may link an earlier sample of its package by // `sample:#` (a trip's ticket its trip), answered by the id // that sample was made under, as installing the tool does. let mut made: std::collections::BTreeMap> = std::collections::BTreeMap::new(); for (table, rows) in cotton_core::definitions::package::sample_order(&package.package.samples) { if TABLES.contains(&table.as_str()) { continue; } for (at, row) in rows.iter().enumerate() { let row = cotton_core::definitions::package::resolve_sample_refs(row, &made) .map_err(|why| ToolFailure::new(format!("sample rows records/{table}.json[{at}]: {why}")))?; let written = create_sample_record(ctx, &table, &row)?; made.entry(table.clone()).or_default().push(written["record"]["id"].as_str().unwrap_or_default().to_string()); kit_records += 1; } } } let added = todos.len() + events.len() + kit_records; Ok(json!({ "receipt": counted(ctx, "added", added)?, "added": added, "todos": todos, "events": events, "kit_records": kit_records })) } /// Bin every live sample record through the shared delete, and nothing else. /// Answers `{receipt, removed}`. pub fn remove(ctx: &mut Ctx<'_>) -> ToolResult { let samples = live(ctx)?; if samples.is_empty() { return Ok(json!({ "receipt": line(ctx, "none", &[])?, "removed": 0 })); } for (table, id) in &samples { let args = json!({ "table": table, "id": id }); delete_record(ctx, args.as_object().expect("an object"))?; } Ok(json!({ "receipt": counted(ctx, "removed", samples.len())?, "removed": samples.len() })) } /// The id a create answered. fn made_id(written: &Value) -> Option { written["record"]["id"].as_str().map(str::to_string) }