wavekat_flow/book.rs
1//! The `book` component (schema_version 2): its bounds, and the
2//! vocabulary that lets a caller be told a time.
3//!
4//! # Why a vocabulary exists at all
5//!
6//! Every sound a flow makes is a clip. The daemon runs no text-to-speech:
7//! prompts are rendered when the flow is published and frozen as version
8//! assets, and playback is a file read. That is what makes a flow work
9//! with no network, and it is why `book` cannot simply "say the time" —
10//! the time is not known until a caller is on the line, hours or days
11//! after the last thing was rendered.
12//!
13//! So the times a flow can *ever* offer are enumerated at publish and
14//! rendered then, exactly like its prompts. Two things make that a small
15//! finite set rather than an impossible one: starts snap to a half hour
16//! ([`BOOK_GRANULARITY_MINS`]), and the node already declares the only
17//! hours it books in. A business open 9–5 on weekdays therefore needs 16
18//! time clips, not 1440 — and needs them regardless of which week the
19//! caller rings in, because "nine thirty" is the same two words on every
20//! one of those days.
21//!
22//! # Why it is split day + time
23//!
24//! An utterance is two clips: a day phrase, then a time phrase
25//! ("Tuesday", then "ten thirty a.m."). One clip per (day, time) pair
26//! multiplies the render count by nine for no gain. Going finer the
27//! other way — composing "ten", "thirty" and "a.m." separately — is what
28//! a naive reading suggests and is wrong: word order and grammar differ across
29//! the languages this platform ships, and an engine concatenating
30//! fragments in English order produces something between odd and
31//! unintelligible elsewhere. Whole phrases keep each language's grammar
32//! inside the phrase, where a translator can see it; day-before-time is
33//! the one ordering assumption left, and it holds across all of them.
34//!
35//! # The contract
36//!
37//! These refs are the contract between the two sides: the platform
38//! renders exactly this set at publish and stores it with the version's
39//! frozen assets; the daemon plays them and never asks what they mean.
40//! Both sides compute the set from the same node config with
41//! [`vocabulary_refs`], so neither can render one thing and expect
42//! another. The refs join [`crate::model_ext`]'s `required_assets`,
43//! which puts them behind the daemon's existing "don't arm a flow whose
44//! audio hasn't synced" gate with no new machinery.
45//!
46//! Twin: `packages/flow-schema/src/book.ts`. Keep the two in lockstep —
47//! the conformance corpus pins the ref sets they produce.
48
49use std::collections::BTreeSet;
50
51use time::OffsetDateTime;
52use time_tz::{OffsetDateTimeExt, Tz};
53
54use crate::model::{Node, TimeRange};
55
56// ── Defaults (mirroring the schema's own, which typify reads) ───────────
57
58pub const DEFAULT_BOOK_BUFFER_MINS: u64 = 0;
59pub const DEFAULT_BOOK_LEAD_MINS: u64 = 120;
60pub const DEFAULT_BOOK_HORIZON_DAYS: u64 = 14;
61pub const DEFAULT_BOOK_MAX_OFFERS: u64 = 3;
62pub const DEFAULT_BOOK_RETRIES: u64 = 1;
63pub const DEFAULT_BOOK_TIMEOUT_SECS: u64 = 5;
64
65// ── Bounds (the validator's, per "schema owns shape, validators own
66// semantics" — see CLAUDE.md) ───────────────────────────────────────
67
68/// Shortest and longest one appointment may run.
69pub const MIN_BOOK_DURATION_MINS: u64 = 5;
70pub const MAX_BOOK_DURATION_MINS: u64 = 480;
71/// Widest clear time that may be kept on each side of an appointment.
72pub const MAX_BOOK_BUFFER_MINS: u64 = 240;
73/// Furthest ahead a caller may be pushed before the first offer (30 days).
74pub const MAX_BOOK_LEAD_MINS: u64 = 60 * 24 * 30;
75/// Furthest ahead a `book` node may look.
76pub const MAX_BOOK_HORIZON_DAYS: u64 = 31;
77/// How many times one caller may be offered — bounded by the keypad
78/// digits the vocabulary carries.
79pub const MAX_BOOK_OFFERS: u64 = 5;
80
81/// Every candidate appointment start lands on a half hour.
82///
83/// Load-bearing, not cosmetic: this is what bounds the vocabulary.
84/// Twin: the platform's `SLOT_GRANULARITY_MINS`, which must agree — if
85/// the server offers a time the vocabulary has no clip for, the caller
86/// hears silence where the time should be.
87///
88/// **This constant is why the change is staged.** [`required_assets`]
89/// is computed from the value compiled into *this* build, not from
90/// anything a version carries — so a daemon still on the quarter hour,
91/// handed a version published after this moved, asks for `bktime_0915`,
92/// does not find it, and refuses to arm the flow at all. Platforms
93/// narrow what they offer first; this follows once the fleet has it.
94///
95/// [`required_assets`]: crate::model_ext::required_assets
96pub const BOOK_GRANULARITY_MINS: u64 = 30;
97
98// ── Vocabulary refs ────────────────────────────────────────────────────
99
100/// Prefix every vocabulary ref carries, so nothing collides with a
101/// platform-generated clip ref (`vprompt_…`) or an author's own file.
102const PREFIX: &str = "bk";
103
104/// The day phrases, always required. `today`/`tomorrow` are how a person
105/// says a date this close to now, and a caller told "Monday" on a Monday
106/// has to work out which Monday.
107pub const BOOK_DAY_KEYS: &[&str] = &[
108 "today", "tomorrow", "mon", "tue", "wed", "thu", "fri", "sat", "sun",
109];
110
111/// `bkday_tue` — the day half of an utterance.
112pub fn day_ref(day: &str) -> String {
113 format!("{PREFIX}day_{day}")
114}
115
116/// The day key for a slot, given how many civil days away it falls and
117/// which weekday it lands on (0 = Monday, matching [`BOOK_DAY_KEYS`]'s
118/// weekday order). Today and tomorrow win over the weekday name.
119pub fn day_key(days_ahead: i64, weekday_from_monday: usize) -> &'static str {
120 match days_ahead {
121 0 => "today",
122 1 => "tomorrow",
123 _ => BOOK_DAY_KEYS[2 + (weekday_from_monday % 7)],
124 }
125}
126
127/// `bktime_0930` — the time half, in the flow's own timezone.
128pub fn time_ref(minutes_of_day: u64) -> String {
129 format!(
130 "{PREFIX}time_{:02}{:02}",
131 minutes_of_day / 60,
132 minutes_of_day % 60
133 )
134}
135
136/// `bkpress_2` — "press two", the digit that takes the offer.
137pub fn press_ref(digit: u64) -> String {
138 format!("{PREFIX}press_{digit}")
139}
140
141/// The one fixed line the component speaks on its own account: the slot
142/// the caller chose was taken between hearing it and pressing the key.
143/// Everything else a caller hears is either the author's prompt or a time.
144pub fn taken_ref() -> String {
145 format!("{PREFIX}taken")
146}
147
148/// What a vocabulary ref means — so the side that *renders* it can look
149/// up the words without re-deriving the ref format.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub enum VocabularyRef {
152 Day { day: String },
153 Time { hour: u64, minute: u64 },
154 Press { digit: u64 },
155 Taken,
156}
157
158/// Read a ref back into what it says. `None` for anything that is not a
159/// vocabulary ref (an author's clip, a filename), so a caller can filter
160/// a mixed asset list with it.
161pub fn parse_vocabulary_ref(reference: &str) -> Option<VocabularyRef> {
162 if reference == taken_ref() {
163 return Some(VocabularyRef::Taken);
164 }
165 if let Some(day) = reference.strip_prefix(&format!("{PREFIX}day_")) {
166 return BOOK_DAY_KEYS.contains(&day).then(|| VocabularyRef::Day {
167 day: day.to_string(),
168 });
169 }
170 if let Some(digits) = reference.strip_prefix(&format!("{PREFIX}time_")) {
171 if digits.len() != 4 || !digits.chars().all(|c| c.is_ascii_digit()) {
172 return None;
173 }
174 let hour: u64 = digits[..2].parse().ok()?;
175 let minute: u64 = digits[2..].parse().ok()?;
176 return (hour <= 23 && minute <= 59).then_some(VocabularyRef::Time { hour, minute });
177 }
178 if let Some(digits) = reference.strip_prefix(&format!("{PREFIX}press_")) {
179 let digit: u64 = digits.parse().ok()?;
180 return (1..=MAX_BOOK_OFFERS)
181 .contains(&digit)
182 .then_some(VocabularyRef::Press { digit });
183 }
184 None
185}
186
187// ── Enumerating a node's vocabulary ────────────────────────────────────
188
189/// `"HH:MM"` → minutes since midnight, or `None` if it isn't one.
190/// Lenient in the same direction as the runtime: a range this can't read
191/// is a range that offers nothing, not a document that fails to load.
192fn minutes_of(hhmm: &str) -> Option<u64> {
193 let (h, m) = hhmm.trim().split_once(':')?;
194 if m.len() != 2 || h.is_empty() || h.len() > 2 {
195 return None;
196 }
197 let hours: u64 = h.parse().ok()?;
198 let mins: u64 = m.parse().ok()?;
199 (hours <= 23 && mins <= 59).then_some(hours * 60 + mins)
200}
201
202/// The starts a single open range can produce: on the half-hour grid,
203/// from the first grid point at or after `open`, while the whole
204/// appointment still finishes by `close`.
205///
206/// Mirrors the platform's slot walk, including that the walk uses real
207/// instants and so may drop a candidate this keeps on a daylight-saving
208/// boundary. That direction is safe: the vocabulary may be a superset (a
209/// clip nobody plays), never a subset (a time nobody can say).
210fn starts_in_range(range: &TimeRange, duration_mins: u64) -> Vec<u64> {
211 let (Some(open), Some(close)) = (minutes_of(&range.open), minutes_of(&range.close)) else {
212 return Vec::new();
213 };
214 if close <= open {
215 return Vec::new();
216 }
217 let first = open.div_ceil(BOOK_GRANULARITY_MINS) * BOOK_GRANULARITY_MINS;
218 let mut starts = Vec::new();
219 let mut mins = first;
220 while mins < close {
221 if mins + duration_mins <= close {
222 starts.push(mins);
223 }
224 mins += BOOK_GRANULARITY_MINS;
225 }
226 starts
227}
228
229/// Every asset ref a `book` node needs in order to speak: the nine day
230/// phrases, one clip per bookable time of day, one "press N" per offer
231/// it may make, and the taken line. Sorted and unique, so two callers of
232/// this compare equal.
233///
234/// Reads only the node's own config, never a clock — the answer must be
235/// the same at publish (when it is rendered) and on a call months later
236/// (when it is played). Empty for every other kind of node, so a caller
237/// can map it over a whole flow.
238pub fn vocabulary_refs(node: &Node) -> Vec<String> {
239 let Node::Book {
240 schedule,
241 exceptions,
242 duration_mins,
243 max_offers,
244 ..
245 } = node
246 else {
247 return Vec::new();
248 };
249
250 let mut refs: BTreeSet<String> = BTreeSet::new();
251
252 for day in BOOK_DAY_KEYS {
253 refs.insert(day_ref(day));
254 }
255 refs.insert(taken_ref());
256
257 for digit in 1..=(*max_offers).min(MAX_BOOK_OFFERS) {
258 refs.insert(press_ref(digit));
259 }
260
261 // A duration outside the bounds is a document the validator rejects;
262 // clamping keeps a bad draft from asking for an unbounded render
263 // while the editor is still showing the error.
264 let duration = duration_mins.clamp(&MIN_BOOK_DURATION_MINS, &MAX_BOOK_DURATION_MINS);
265
266 let weekly = [
267 &schedule.mon,
268 &schedule.tue,
269 &schedule.wed,
270 &schedule.thu,
271 &schedule.fri,
272 &schedule.sat,
273 &schedule.sun,
274 ];
275 let mut ranges: Vec<&TimeRange> = weekly.iter().flat_map(|day| day.iter()).collect();
276 for exception in exceptions {
277 // A closed day offers nothing; its `ranges`, if any, are ignored
278 // by the runtime too.
279 if exception.closed {
280 continue;
281 }
282 ranges.extend(exception.ranges.iter());
283 }
284
285 for range in ranges {
286 for start in starts_in_range(range, *duration) {
287 refs.insert(time_ref(start));
288 }
289 }
290
291 refs.into_iter().collect()
292}
293
294// ── Saying one time ────────────────────────────────────────────────────
295
296/// The clips that say one appointment time, in order: the day phrase
297/// then the time phrase ("Tuesday" → "ten thirty a.m.").
298///
299/// `start` is an absolute instant — the server answers in UTC — so the
300/// business's own zone is what turns it back into the words a caller
301/// expects; a 9 a.m. appointment must not be announced as 21:00 because
302/// the platform happens to run in UTC. `now` decides only whether the
303/// day is worth naming: "Tuesday" is a poor way to say tomorrow.
304pub fn time_refs(start: OffsetDateTime, now: OffsetDateTime, tz: &Tz) -> Vec<String> {
305 let local = start.to_timezone(tz);
306 let today = now.to_timezone(tz).date();
307 let days_ahead = (local.date() - today).whole_days();
308 let minutes = u64::from(local.hour()) * 60 + u64::from(local.minute());
309 vec![
310 day_ref(day_key(
311 days_ahead,
312 local.date().weekday().number_days_from_monday() as usize,
313 )),
314 time_ref(minutes),
315 ]
316}
317
318/// The clips that offer one time: what it is, then which key takes it.
319pub fn offer_refs(start: OffsetDateTime, now: OffsetDateTime, tz: &Tz, digit: u64) -> Vec<String> {
320 let mut refs = time_refs(start, now, tz);
321 refs.push(press_ref(digit));
322 refs
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328 use time::macros::datetime;
329
330 #[test]
331 fn grid_starts_leave_room_for_the_whole_appointment() {
332 let range = TimeRange {
333 open: "09:10".into(),
334 close: "10:30".into(),
335 };
336 // First grid point at or after 09:10 is 09:30 — never 09:10, and
337 // no longer 09:15; the last start that still finishes by 10:30
338 // with a 30-minute appointment is 10:00.
339 assert_eq!(starts_in_range(&range, 30), vec![570, 600]);
340 // An appointment longer than the window produces nothing at all.
341 assert!(starts_in_range(&range, 120).is_empty());
342 }
343
344 #[test]
345 fn unreadable_ranges_offer_nothing_rather_than_failing() {
346 let backwards = TimeRange {
347 open: "17:00".into(),
348 close: "09:00".into(),
349 };
350 assert!(starts_in_range(&backwards, 30).is_empty());
351 let nonsense = TimeRange {
352 open: "nine".into(),
353 close: "five".into(),
354 };
355 assert!(starts_in_range(&nonsense, 30).is_empty());
356 }
357
358 #[test]
359 fn refs_round_trip_through_their_meaning() {
360 assert_eq!(
361 parse_vocabulary_ref(&time_ref(9 * 60 + 30)),
362 Some(VocabularyRef::Time {
363 hour: 9,
364 minute: 30
365 })
366 );
367 assert_eq!(
368 parse_vocabulary_ref(&day_ref("tue")),
369 Some(VocabularyRef::Day { day: "tue".into() })
370 );
371 assert_eq!(
372 parse_vocabulary_ref(&press_ref(2)),
373 Some(VocabularyRef::Press { digit: 2 })
374 );
375 assert_eq!(
376 parse_vocabulary_ref(&taken_ref()),
377 Some(VocabularyRef::Taken)
378 );
379
380 // Not vocabulary: an author's clip, and refs that look like one
381 // but say nothing sayable.
382 assert_eq!(parse_vocabulary_ref("vprompt_ab12cd34"), None);
383 assert_eq!(parse_vocabulary_ref("bkday_funday"), None);
384 assert_eq!(parse_vocabulary_ref("bktime_2599"), None);
385 assert_eq!(parse_vocabulary_ref("bkpress_9"), None);
386 }
387
388 #[test]
389 fn day_key_prefers_today_and_tomorrow_over_the_weekday_name() {
390 assert_eq!(day_key(0, 3), "today");
391 assert_eq!(day_key(1, 4), "tomorrow");
392 assert_eq!(day_key(2, 0), "mon");
393 assert_eq!(day_key(6, 6), "sun");
394 }
395
396 #[test]
397 fn a_time_is_said_in_the_businesss_zone_not_the_servers() {
398 let tz = crate::hours::resolve_tz("America/New_York").unwrap();
399 // 14:30 UTC on Tuesday 7 July 2026 is 10:30 EDT the same day.
400 let start = datetime!(2026-07-07 14:30 UTC);
401 let now = datetime!(2026-07-06 12:00 UTC); // Monday: the slot is tomorrow
402 assert_eq!(
403 time_refs(start, now, tz),
404 vec!["bkday_tomorrow".to_string(), "bktime_1030".to_string()],
405 );
406
407 // Same instant, a week earlier in the caller's life: now it needs
408 // its weekday name.
409 let earlier = datetime!(2026-07-01 12:00 UTC);
410 assert_eq!(
411 time_refs(start, earlier, tz),
412 vec!["bkday_tue".to_string(), "bktime_1030".to_string()],
413 );
414 }
415
416 #[test]
417 fn a_late_utc_instant_can_be_the_previous_local_day() {
418 let tz = crate::hours::resolve_tz("America/New_York").unwrap();
419 // 01:00 UTC Wednesday is 21:00 EDT Tuesday — the local date, and
420 // therefore the day word, belongs to Tuesday.
421 let start = datetime!(2026-07-08 01:00 UTC);
422 let now = datetime!(2026-07-07 13:00 UTC); // Tuesday morning, local
423 assert_eq!(
424 time_refs(start, now, tz),
425 vec!["bkday_today".to_string(), "bktime_2100".to_string()],
426 );
427 }
428
429 #[test]
430 fn an_offer_ends_with_the_key_that_takes_it() {
431 let tz = crate::hours::resolve_tz("UTC").unwrap();
432 let start = datetime!(2026-07-07 09:30 UTC);
433 let now = datetime!(2026-07-07 08:00 UTC);
434 assert_eq!(
435 offer_refs(start, now, tz, 2),
436 vec![
437 "bkday_today".to_string(),
438 "bktime_0930".to_string(),
439 "bkpress_2".to_string()
440 ],
441 );
442 }
443}