Skip to main content

adk_surface/verbs/
snooze.rs

1//! The first catalogue (owner question 21): `coming_up`, the caller's Coming up with the two
2//! times each item may move to, and `snooze`, which moves one an hour later or to the same time
3//! tomorrow (spec 3.3 §2 item 7, §5.1).
4
5use std::sync::Arc;
6
7use adk_kernel::drivers::EffectClass;
8use adk_kernel::{AgendaItem, AgendaState};
9use async_trait::async_trait;
10use chrono::{DateTime, Duration, FixedOffset, Utc};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13use serde_json::{Value, json};
14
15use super::registry::{Entry, single_time};
16use super::{Callers, ObjectKind, VerbDone, VerbError, VerbHandler, VerbScope, VerbSpec, words};
17
18/// Something in the caller's Coming up, and the times it may move to (spec 3.3 §5.1).
19///
20/// # Example
21///
22/// ```rust
23/// use adk_surface::verbs::ComingUpItem;
24///
25/// let item: ComingUpItem = serde_json::from_value(serde_json::json!({
26///     "id": "agenda-7f3", "title": "News digest", "area": "work",
27///     "at": "2026-10-26T15:00:00Z", "atText": "18:00", "choices": [],
28/// }))
29/// .unwrap();
30/// assert_eq!(item.title, "News digest");
31/// assert!(item.why_not.is_none());
32/// ```
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
34#[serde(rename_all = "camelCase")]
35pub struct ComingUpItem {
36    /// The agenda item's id.
37    pub id: String,
38    /// Its title.
39    pub title: String,
40    /// The area it is in.
41    pub area: String,
42    /// When it wakes, when it waits for one time.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub at: Option<DateTime<Utc>>,
45    /// When it wakes, as a person reads it: "18:00", "Tue 18:00"; empty without one time.
46    pub at_text: String,
47    /// When it ends if it has not run.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub ends: Option<DateTime<Utc>>,
50    /// The times it may move to: an hour later, the same time tomorrow — those before it ends.
51    pub choices: Vec<SnoozeChoice>,
52    /// Why it cannot be snoozed, in plain words; absent when it can.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub why_not: Option<String>,
55}
56
57/// One time an item may move to (spec 3.3 §5.1).
58///
59/// # Example
60///
61/// ```rust
62/// use adk_surface::verbs::SnoozeChoice;
63///
64/// let choice: SnoozeChoice = serde_json::from_value(serde_json::json!({
65///     "to": "2026-10-26T19:00:00+03:00", "label": "1 hour later", "atText": "19:00", "tomorrow": false,
66/// }))
67/// .unwrap();
68/// assert_eq!(choice.to.to_rfc3339(), "2026-10-26T19:00:00+03:00");
69/// ```
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
71#[serde(rename_all = "camelCase")]
72pub struct SnoozeChoice {
73    /// The new time, the `to` of `snooze`.
74    pub to: DateTime<FixedOffset>,
75    /// "1 hour later" or "Tomorrow, same time".
76    pub label: String,
77    /// The new time as a person reads it: "19:00", "Tue 18:00".
78    pub at_text: String,
79    /// It is the same time tomorrow.
80    pub tomorrow: bool,
81}
82
83/// `coming_up` and `snooze`.
84pub(crate) fn catalogue() -> Vec<Entry> {
85    let coming_up = VerbSpec::new(
86        "coming_up",
87        "Coming up",
88        "List what is coming up for the person: each item's id, title, when it wakes, and the \
89         two times it may be snoozed to. Reading it never asks the person.",
90        EffectClass::Read,
91    )
92    .with_objects([ObjectKind::ComingUp])
93    .with_callers(Callers::PersonAndAgents);
94    let snooze = VerbSpec::new(
95        "snooze",
96        words::SNOOZE,
97        words::SNOOZE_SOMETHING,
98        EffectClass::WriteLocal,
99    )
100    .with_objects([ObjectKind::ComingUp])
101    .with_args(json!({
102        "type": "object",
103        "properties": {
104            "item": {
105                "type": "string",
106                "description": "The id of the item, as coming_up lists it"
107            },
108            "to": {
109                "type": "string",
110                "format": "date-time",
111                "description": "When it should wake instead: exactly one of the two times coming_up lists for the item"
112            }
113        },
114        "required": ["item", "to"],
115        "additionalProperties": false
116    }))
117    .with_callers(Callers::PersonAndAgents)
118    .only_delays()
119    .reversible()
120    .with_voice_phrase("snooze");
121    vec![
122        Entry { spec: coming_up, handler: Arc::new(ComingUp) },
123        Entry { spec: snooze, handler: Arc::new(Snooze) },
124    ]
125}
126
127impl VerbScope {
128    /// The caller's Coming up: every scheduled or running item, soonest first, with the times
129    /// each may move to and why one cannot.
130    ///
131    /// # Errors
132    ///
133    /// The kernel's or the store's error.
134    pub async fn coming_up(&self) -> Result<Vec<ComingUpItem>, VerbError> {
135        let mut out = Vec::new();
136        for item in self.items().await? {
137            out.push(self.coming_up_item(&item).await?);
138        }
139        out.sort_by(|a, b| match (a.at, b.at) {
140            (Some(a), Some(b)) => a.cmp(&b),
141            (Some(_), None) => std::cmp::Ordering::Less,
142            (None, Some(_)) => std::cmp::Ordering::Greater,
143            (None, None) => std::cmp::Ordering::Equal,
144        });
145        Ok(out)
146    }
147
148    async fn coming_up_item(&self, item: &AgendaItem) -> Result<ComingUpItem, VerbError> {
149        let at = match &item.state {
150            AgendaState::Scheduled { wake } => single_time(wake),
151            _ => None,
152        };
153        let why_not = match &item.state {
154            AgendaState::Running { .. } => Some(words::ALREADY_STARTED),
155            AgendaState::Scheduled { .. } if at.is_none() => Some(words::NOT_ONE_TIME),
156            AgendaState::Scheduled { .. } if self.started(item).await? => {
157                Some(words::ALREADY_STARTED)
158            }
159            AgendaState::Scheduled { .. } => None,
160            _ => Some(words::NOT_SCHEDULED),
161        };
162        let choices = match (at, why_not) {
163            (Some(at), None) => self.choices(at, item.expires_at),
164            _ => Vec::new(),
165        };
166        let why_not = why_not.map(str::to_string).or_else(|| match (at, item.expires_at) {
167            (Some(_), Some(ends)) if choices.is_empty() => {
168                Some(words::ends_at(&self.time_text(ends)))
169            }
170            _ => None,
171        });
172        Ok(ComingUpItem {
173            id: item.id.clone(),
174            title: item.title.clone(),
175            area: item.partition.to_string(),
176            at,
177            at_text: at.map(|at| self.time_text(at)).unwrap_or_default(),
178            ends: item.expires_at,
179            choices,
180            why_not,
181        })
182    }
183
184    /// The times `at` may move to before `ends`.
185    fn choices(&self, at: DateTime<Utc>, ends: Option<DateTime<Utc>>) -> Vec<SnoozeChoice> {
186        [
187            (Duration::hours(1), words::ONE_HOUR_LATER, false),
188            (Duration::days(1), words::TOMORROW_SAME_TIME, true),
189        ]
190        .into_iter()
191        .map(|(by, label, tomorrow)| (at + by, label, tomorrow))
192        .filter(|(to, _, _)| ends.is_none_or(|ends| *to <= ends))
193        .map(|(to, label, tomorrow)| SnoozeChoice {
194            to: to.with_timezone(&self.offset()),
195            label: label.to_string(),
196            at_text: self.time_text(to),
197            tomorrow,
198        })
199        .collect()
200    }
201
202    /// The item `id` and the wake it moves from, when moving it to `to` is one of the times it
203    /// may move to now.
204    async fn snoozable(
205        &self,
206        id: &str,
207        to: DateTime<Utc>,
208    ) -> Result<(AgendaItem, DateTime<Utc>), VerbError> {
209        let item = self.item(id).await?;
210        let wake = match &item.state {
211            AgendaState::Scheduled { wake } => wake,
212            AgendaState::Running { .. } => return Err(VerbError::refused(words::ALREADY_STARTED)),
213            AgendaState::Proposed | AgendaState::Approved => {
214                return Err(VerbError::refused(words::NOT_SCHEDULED));
215            }
216            _ => return Err(VerbError::refused(words::ENDED)),
217        };
218        let Some(at) = single_time(wake) else {
219            return Err(VerbError::refused(words::NOT_ONE_TIME));
220        };
221        if to != at + Duration::hours(1) && to != at + Duration::days(1) {
222            // Already as late as asked: someone moved it since. Any other time is not one of
223            // its two, as an Edit can give it.
224            if to <= at {
225                return Err(VerbError::refused(words::IT_MOVED));
226            }
227            let times: Vec<String> = self
228                .choices(at, item.expires_at)
229                .into_iter()
230                .map(|choice| choice.at_text)
231                .collect();
232            return Err(VerbError::refused(match (times.is_empty(), item.expires_at) {
233                (true, Some(ends)) => words::ends_at(&self.time_text(ends)),
234                _ => words::only_moves_to(&times),
235            }));
236        }
237        if let Some(ends) = item.expires_at.filter(|ends| to > *ends) {
238            return Err(VerbError::refused(words::ends_at(&self.time_text(ends))));
239        }
240        if self.started(&item).await? {
241            return Err(VerbError::refused(words::ALREADY_STARTED));
242        }
243        Ok((item, at))
244    }
245}
246
247/// The item whose title is `title`, ignoring case, among `items` (spec 3.3 §5.2): one exact
248/// match. Without one, a title that is part of several is ambiguous and lists them.
249///
250/// # Errors
251///
252/// [`VerbError::NotFound`] when no title is `title`; [`VerbError::Ambiguous`] when several
253/// are, or when none is and several contain it.
254///
255/// # Example
256///
257/// ```rust
258/// use adk_surface::verbs::{ComingUpItem, find_by_title};
259///
260/// let item = |id: &str, title: &str| ComingUpItem {
261///     id: id.into(), title: title.into(), area: "work".into(), at: None,
262///     at_text: String::new(), ends: None, choices: vec![], why_not: None,
263/// };
264/// let items = [item("a", "News digest"), item("b", "Weekly digest")];
265/// assert_eq!(find_by_title(&items, "news DIGEST").unwrap().id, "a");
266/// assert_eq!(find_by_title(&items, "digest").unwrap_err().code(), "surface.verb.ambiguous");
267/// assert_eq!(find_by_title(&items, "laundry").unwrap_err().code(), "surface.verb.unknown");
268/// ```
269pub fn find_by_title<'a>(
270    items: &'a [ComingUpItem],
271    title: &str,
272) -> Result<&'a ComingUpItem, VerbError> {
273    let wanted = normalize(title);
274    let exact: Vec<&ComingUpItem> =
275        items.iter().filter(|item| normalize(&item.title) == wanted).collect();
276    match exact.as_slice() {
277        [only] => return Ok(only),
278        [] => {}
279        several => {
280            return Err(VerbError::Ambiguous {
281                said: title.to_string(),
282                matches: several.iter().map(|item| item.title.clone()).collect(),
283            });
284        }
285    }
286    let partial: Vec<&ComingUpItem> = items
287        .iter()
288        .filter(|item| !wanted.is_empty() && normalize(&item.title).contains(&wanted))
289        .collect();
290    if partial.len() > 1 {
291        return Err(VerbError::Ambiguous {
292            said: title.to_string(),
293            matches: partial.iter().map(|item| item.title.clone()).collect(),
294        });
295    }
296    Err(VerbError::not_found(format!("“{title}”")))
297}
298
299/// `text` lower-cased with its words single-spaced, punctuation dropped.
300pub(crate) fn normalize(text: &str) -> String {
301    text.split(|c: char| !c.is_alphanumeric() && c != '\'')
302        .filter(|word| !word.is_empty())
303        .map(str::to_lowercase)
304        .collect::<Vec<_>>()
305        .join(" ")
306}
307
308/// The item and the new time a `snooze` call names.
309fn snooze_args(args: &Value) -> Result<(String, DateTime<Utc>), VerbError> {
310    let item = args.get("item").and_then(Value::as_str).filter(|item| !item.is_empty());
311    let to = args.get("to").and_then(Value::as_str);
312    let (Some(item), Some(to)) = (item, to) else {
313        return Err(VerbError::invalid(
314            "snooze takes `item`, the id coming_up lists, and `to`, one of its two times",
315        ));
316    };
317    let to = DateTime::parse_from_rfc3339(to)
318        .map_err(|_| VerbError::invalid(format!("`to` is not a time with its offset: {to}")))?
319        .with_timezone(&Utc);
320    Ok((item.to_string(), to))
321}
322
323/// `coming_up`: the caller's Coming up, as data.
324struct ComingUp;
325
326#[async_trait]
327impl VerbHandler for ComingUp {
328    async fn describe(&self, _scope: &VerbScope, _args: &Value) -> Result<String, VerbError> {
329        Ok("List what is coming up".to_string())
330    }
331
332    async fn run(&self, scope: &VerbScope, _args: &Value) -> Result<VerbDone, VerbError> {
333        let items = scope.coming_up().await?;
334        let text = match items.len() {
335            0 => "Nothing is coming up".to_string(),
336            1 => "1 thing is coming up".to_string(),
337            count => format!("{count} things are coming up"),
338        };
339        let result = serde_json::to_value(&items).unwrap_or(Value::Null);
340        Ok(VerbDone::new("coming_up", text).with_result(json!({ "items": result })))
341    }
342}
343
344/// `snooze`: moves one item an hour later or to the same time tomorrow.
345struct Snooze;
346
347#[async_trait]
348impl VerbHandler for Snooze {
349    async fn describe(&self, scope: &VerbScope, args: &Value) -> Result<String, VerbError> {
350        let (id, to) = snooze_args(args)?;
351        let (item, _) = scope.snoozable(&id, to).await?;
352        Ok(words::move_to(&item.title, &scope.time_text(to)))
353    }
354
355    async fn run(&self, scope: &VerbScope, args: &Value) -> Result<VerbDone, VerbError> {
356        let (id, to) = snooze_args(args)?;
357        let (item, from) = scope.snoozable(&id, to).await?;
358        scope.move_wake(&id, from, to).await?;
359        let at_text = scope.time_text(to);
360        Ok(VerbDone::new("snooze", words::moved_to(&item.title, &at_text))
361            .with_target(format!("agenda:{id}"), item.title.clone())
362            .with_result(json!({
363                "item": id,
364                "title": item.title,
365                "from": from,
366                "to": to.with_timezone(&scope.offset()),
367                "atText": at_text,
368            })))
369    }
370}