Skip to main content

adk_website/
alarms.rs

1//! Alarms by urgency (spec 3.5 §7.21, §7.20 "Alarms by urgency and channel").
2//!
3//! | Urgency | Examples | Delivery |
4//! |---|---|---|
5//! | P1 | Incident, site down, payment anomaly, key compromise suspected | Immediately on the owner's P1 channels, including inside quiet hours; repeated until acknowledged |
6//! | P2 | A held decision blocking a customer, a guardrail breach, a failed renewal | On the owner's chosen channel, outside quiet hours |
7//! | P3 | Everything else | The weekly review |
8//!
9//! [`AlarmRouter`] delivers through the kernel's `ChannelSink`s to the owner's paired
10//! threads, reads the charter's reporting routes and quiet hours, and is the product's
11//! `CharterEventSink` (guardrail breaches, pauses, autonomy changes) and `WalletAlarmHook`
12//! (payment anomalies, reconciliation mismatches).
13//!
14//! With an [`AlarmStore`] ([`AlarmRouter::with_store`]) the open P1 alarms, the P2 alarms
15//! deferred to the end of quiet hours and the alarms waiting for the weekly review survive a
16//! restart: [`SqliteAlarmStore`] keeps them in a served site's `data/edge.db`, and every store
17//! passes [`conformance::alarm_store`].
18
19use std::collections::BTreeMap;
20use std::sync::Arc;
21use std::sync::atomic::{AtomicU64, Ordering};
22
23use adk_core::audit_log::{AuditActor, AuditTrail};
24use adk_core::principal::{SubjectKind, SubjectRef};
25use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
26use adk_kernel::QuietHours;
27use adk_kernel::channels::ChannelSink;
28use adk_kernel::charter::{CharterEvent, CharterEventSink};
29use adk_payments::wallet::{WalletAlarm, WalletAlarmHook};
30use async_trait::async_trait;
31use awp_types::{Reporting, Urgency};
32use chrono::{DateTime, Duration, Utc};
33use serde::{Deserialize, Serialize};
34use serde_json::json;
35use tokio::sync::Mutex;
36use uuid::Uuid;
37
38use crate::audit;
39
40/// How often an unacknowledged P1 alarm is sent again (spec 3.5 §7.21).
41pub const P1_REPEAT: Duration = Duration::minutes(15);
42
43/// An alarm to the owner (spec 3.5 §7.21).
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct Alarm {
47    /// The alarm's id, given when it is raised.
48    #[serde(default)]
49    pub id: String,
50    /// The site.
51    pub site: Uuid,
52    /// How soon the owner hears of it.
53    pub urgency: Urgency,
54    /// What it is, such as `incident`, `payment_anomaly` or `guardrail_breach`.
55    pub kind: String,
56    /// One line for the owner: what happened, what was done, what the owner must decide.
57    pub summary: String,
58    /// When it was raised.
59    pub raised_at: DateTime<Utc>,
60}
61
62impl Alarm {
63    /// An alarm of `kind` at `urgency` for `site`.
64    pub fn new(
65        site: Uuid,
66        urgency: Urgency,
67        kind: impl Into<String>,
68        summary: impl Into<String>,
69        raised_at: DateTime<Utc>,
70    ) -> Self {
71        Self {
72            id: String::new(),
73            site,
74            urgency,
75            kind: kind.into(),
76            summary: summary.into(),
77            raised_at,
78        }
79    }
80
81    /// The alarm as the owner reads it on a channel.
82    pub fn text(&self) -> String {
83        let label = match self.urgency {
84            Urgency::P1 => "Urgent",
85            Urgency::P2 => "Needs you",
86            _ => "For the review",
87        };
88        format!("{label}: {} (alarm {})", self.summary, self.id)
89    }
90}
91
92/// One message an alarm sent.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub struct Delivery {
96    /// The alarm.
97    pub alarm: String,
98    /// The channel.
99    pub channel: String,
100    /// The owner's thread on it.
101    pub thread: String,
102    /// The attempt: 1 for the first send of a P1 alarm, more for its repeats.
103    pub attempt: u32,
104    /// When.
105    pub at: DateTime<Utc>,
106}
107
108/// What [`AlarmRouter::raise`] did with an alarm.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(tag = "routed", rename_all = "snake_case")]
111pub enum Routed {
112    /// Sent now.
113    Sent {
114        /// The messages.
115        deliveries: Vec<Delivery>,
116    },
117    /// A P2 alarm inside quiet hours: sent when they end.
118    Deferred,
119    /// Held for the weekly review.
120    Review,
121}
122
123#[derive(Debug, Clone)]
124struct OpenP1 {
125    alarm: Alarm,
126    attempts: u32,
127    last: DateTime<Utc>,
128}
129
130#[derive(Debug, Default)]
131struct RouterState {
132    open: BTreeMap<String, OpenP1>,
133    deferred: Vec<Alarm>,
134    review: Vec<Alarm>,
135    raised: Vec<Alarm>,
136}
137
138/// Where an alarm stands (spec 3.5 §7.21).
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(tag = "state", rename_all = "snake_case", rename_all_fields = "camelCase")]
141pub enum AlarmState {
142    /// A P1 alarm no person has acknowledged: it repeats.
143    Open {
144        /// Sends so far.
145        attempts: u32,
146        /// The last send.
147        last: DateTime<Utc>,
148    },
149    /// A P2 alarm raised inside quiet hours: sent when they end.
150    Deferred,
151    /// Waiting for the weekly review.
152    Review,
153    /// Sent, acknowledged or carried by a review.
154    Done,
155}
156
157/// An alarm and where it stands, as an [`AlarmStore`] keeps it.
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase")]
160pub struct AlarmRecord {
161    /// The alarm.
162    pub alarm: Alarm,
163    /// Where it stands.
164    pub state: AlarmState,
165}
166
167/// Where an [`AlarmRouter`] keeps its alarms, so a restart neither drops an open P1 alarm
168/// nor a deferred or waiting one (spec 3.5 §7.21).
169///
170/// # Example
171///
172/// ```rust
173/// use adk_website::alarms::{Alarm, AlarmRecord, AlarmState, AlarmStore, InMemoryAlarmStore};
174/// use awp_types::Urgency;
175///
176/// # #[tokio::main(flavor = "current_thread")]
177/// # async fn main() -> adk_core::Result<()> {
178/// let store = InMemoryAlarmStore::default();
179/// let mut alarm = Alarm::new(uuid::Uuid::nil(), Urgency::P3, "freshness", "Two pages are stale", chrono::Utc::now());
180/// alarm.id = "alarm-1".into();
181/// store.save(&AlarmRecord { alarm, state: AlarmState::Review }).await?;
182/// assert_eq!(store.alarms(uuid::Uuid::nil()).await?.len(), 1);
183/// # Ok(())
184/// # }
185/// ```
186#[async_trait]
187pub trait AlarmStore: Send + Sync {
188    /// Keeps `record`, replacing the one with its alarm's id; a new alarm is listed after
189    /// those kept before it.
190    ///
191    /// # Errors
192    ///
193    /// The store's error.
194    async fn save(&self, record: &AlarmRecord) -> Result<()>;
195
196    /// The alarms of `site`, in the order they were first kept.
197    ///
198    /// # Errors
199    ///
200    /// The store's error.
201    async fn alarms(&self, site: Uuid) -> Result<Vec<AlarmRecord>>;
202}
203
204/// An [`AlarmStore`] in memory, for tests.
205#[derive(Debug, Default)]
206pub struct InMemoryAlarmStore {
207    records: Mutex<Vec<AlarmRecord>>,
208}
209
210#[async_trait]
211impl AlarmStore for InMemoryAlarmStore {
212    async fn save(&self, record: &AlarmRecord) -> Result<()> {
213        let mut records = self.records.lock().await;
214        match records
215            .iter_mut()
216            .find(|kept| kept.alarm.site == record.alarm.site && kept.alarm.id == record.alarm.id)
217        {
218            Some(kept) => *kept = record.clone(),
219            None => records.push(record.clone()),
220        }
221        Ok(())
222    }
223
224    async fn alarms(&self, site: Uuid) -> Result<Vec<AlarmRecord>> {
225        Ok(self.records.lock().await.iter().filter(|r| r.alarm.site == site).cloned().collect())
226    }
227}
228
229fn alarm_store_error(error: impl std::fmt::Display) -> AdkError {
230    AdkError::config(format!("the site's alarm store: {error}"))
231}
232
233/// An [`AlarmStore`] in SQLite, such as a served site's `data/edge.db`.
234///
235/// # Example
236///
237/// ```rust
238/// use adk_website::alarms::{AlarmStore, SqliteAlarmStore};
239///
240/// # #[tokio::main(flavor = "current_thread")]
241/// # async fn main() -> adk_core::Result<()> {
242/// let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap();
243/// let store = SqliteAlarmStore::new(pool);
244/// store.migrate().await?;
245/// assert!(store.alarms(uuid::Uuid::nil()).await?.is_empty());
246/// # Ok(())
247/// # }
248/// ```
249#[derive(Debug, Clone)]
250pub struct SqliteAlarmStore {
251    pool: sqlx::SqlitePool,
252}
253
254impl SqliteAlarmStore {
255    /// The store over `pool`; call [`migrate`](Self::migrate) once.
256    pub fn new(pool: sqlx::SqlitePool) -> Self {
257        Self { pool }
258    }
259
260    /// Creates the table.
261    ///
262    /// # Errors
263    ///
264    /// The database's error.
265    pub async fn migrate(&self) -> Result<()> {
266        sqlx::query(
267            "CREATE TABLE IF NOT EXISTS website_alarms (
268                seq INTEGER PRIMARY KEY AUTOINCREMENT,
269                site TEXT NOT NULL, id TEXT NOT NULL, record TEXT NOT NULL,
270                UNIQUE (site, id))",
271        )
272        .execute(&self.pool)
273        .await
274        .map_err(alarm_store_error)?;
275        Ok(())
276    }
277}
278
279#[async_trait]
280impl AlarmStore for SqliteAlarmStore {
281    async fn save(&self, record: &AlarmRecord) -> Result<()> {
282        sqlx::query(
283            "INSERT INTO website_alarms (site, id, record) VALUES (?, ?, ?)
284             ON CONFLICT (site, id) DO UPDATE SET record = excluded.record",
285        )
286        .bind(record.alarm.site.to_string())
287        .bind(&record.alarm.id)
288        .bind(serde_json::to_string(record).map_err(alarm_store_error)?)
289        .execute(&self.pool)
290        .await
291        .map_err(alarm_store_error)?;
292        Ok(())
293    }
294
295    async fn alarms(&self, site: Uuid) -> Result<Vec<AlarmRecord>> {
296        let rows: Vec<(String,)> =
297            sqlx::query_as("SELECT record FROM website_alarms WHERE site = ? ORDER BY seq")
298                .bind(site.to_string())
299                .fetch_all(&self.pool)
300                .await
301                .map_err(alarm_store_error)?;
302        rows.iter()
303            .map(|(record,)| serde_json::from_str(record).map_err(alarm_store_error))
304            .collect()
305    }
306}
307
308/// The conformance check every [`AlarmStore`] passes (spec 3.5 §7.21).
309pub mod conformance {
310    use awp_types::Urgency;
311    use uuid::Uuid;
312
313    use super::{Alarm, AlarmRecord, AlarmState, AlarmStore};
314
315    fn alarm(site: Uuid, id: &str, urgency: Urgency) -> Alarm {
316        let mut alarm =
317            Alarm::new(site, urgency, "incident", "The site is down", chrono::Utc::now());
318        alarm.id = id.to_string();
319        alarm
320    }
321
322    /// Records read back in the order they were first kept, replaced by id, each site's
323    /// apart.
324    ///
325    /// # Panics
326    ///
327    /// When the store breaks its contract.
328    pub async fn alarm_store(store: &dyn AlarmStore) {
329        let (site, other) = (Uuid::new_v4(), Uuid::new_v4());
330        let last = chrono::Utc::now();
331        let open = AlarmRecord {
332            alarm: alarm(site, "alarm-1", Urgency::P1),
333            state: AlarmState::Open { attempts: 1, last },
334        };
335        let waiting =
336            AlarmRecord { alarm: alarm(site, "alarm-2", Urgency::P3), state: AlarmState::Review };
337        store.save(&open).await.unwrap();
338        store.save(&waiting).await.unwrap();
339        store
340            .save(&AlarmRecord {
341                alarm: alarm(other, "alarm-1", Urgency::P2),
342                state: AlarmState::Deferred,
343            })
344            .await
345            .unwrap();
346        assert_eq!(store.alarms(site).await.unwrap(), vec![open.clone(), waiting.clone()]);
347        let acknowledged = AlarmRecord { state: AlarmState::Done, ..open.clone() };
348        store.save(&acknowledged).await.unwrap();
349        assert_eq!(
350            store.alarms(site).await.unwrap(),
351            vec![acknowledged, waiting],
352            "replaced in place"
353        );
354        assert_eq!(store.alarms(other).await.unwrap()[0].state, AlarmState::Deferred);
355        assert!(store.alarms(Uuid::new_v4()).await.unwrap().is_empty());
356    }
357}
358
359/// Routes alarms to the owner by urgency (spec 3.5 §7.21).
360///
361/// # Example
362///
363/// ```rust
364/// use std::sync::Arc;
365/// use adk_website::alarms::{Alarm, AlarmRouter, Routed};
366/// use awp_types::{Reporting, Urgency, Cadence};
367///
368/// # #[tokio::main(flavor = "current_thread")]
369/// # async fn main() {
370/// let reporting = Reporting { review: Cadence::Weekly, routes: vec![], quiet_hours: None };
371/// let router = AlarmRouter::new(uuid::Uuid::nil(), &reporting);
372/// let routed = router.raise(Alarm::new(uuid::Uuid::nil(), Urgency::P3, "freshness", "Two pages are stale", chrono::Utc::now())).await;
373/// assert_eq!(routed, Routed::Review);
374/// assert_eq!(router.review_items().await.len(), 1);
375/// # }
376/// ```
377pub struct AlarmRouter {
378    site: Uuid,
379    routes: BTreeMap<Urgency, Vec<String>>,
380    quiet: Option<QuietHours>,
381    sinks: BTreeMap<String, (Arc<dyn ChannelSink>, String)>,
382    clock: Arc<dyn Clock>,
383    repeat: Duration,
384    audit: Option<AuditTrail>,
385    state: Mutex<RouterState>,
386    next: AtomicU64,
387    store: Option<Arc<dyn AlarmStore>>,
388    loaded: tokio::sync::OnceCell<()>,
389}
390
391impl std::fmt::Debug for AlarmRouter {
392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393        f.debug_struct("AlarmRouter")
394            .field("site", &self.site)
395            .field("routes", &self.routes)
396            .field("channels", &self.sinks.keys().collect::<Vec<_>>())
397            .finish_non_exhaustive()
398    }
399}
400
401/// The kernel's quiet hours for the charter's (spec 3.5 §7.21): in their IANA time zone,
402/// or UTC when the zone is unknown.
403pub fn quiet_hours(reporting: &Reporting) -> Option<QuietHours> {
404    let quiet = reporting.quiet_hours.as_ref()?;
405    let hours = QuietHours::new(quiet.start, quiet.end);
406    Some(match quiet.timezone.parse::<chrono_tz::Tz>() {
407        Ok(zone) => hours.with_time_zone(zone),
408        Err(_) => {
409            tracing::warn!(timezone = %quiet.timezone, "unknown quiet-hours time zone; reading the hours in UTC");
410            hours.with_utc_offset_minutes(0)
411        }
412    })
413}
414
415impl AlarmRouter {
416    /// A router for `site` over the charter's `reporting`: its routes per urgency and its
417    /// quiet hours. Add the owner's threads with [`with_sink`](Self::with_sink).
418    pub fn new(site: Uuid, reporting: &Reporting) -> Self {
419        let routes = reporting
420            .routes
421            .iter()
422            .map(|route| {
423                (route.urgency, route.channels.iter().map(|c| c.as_str().to_string()).collect())
424            })
425            .collect();
426        Self {
427            site,
428            routes,
429            quiet: quiet_hours(reporting),
430            sinks: BTreeMap::new(),
431            clock: Arc::new(SystemClock),
432            repeat: P1_REPEAT,
433            audit: None,
434            state: Mutex::new(RouterState::default()),
435            next: AtomicU64::new(1),
436            store: None,
437            loaded: tokio::sync::OnceCell::new(),
438        }
439    }
440
441    /// Keeps the alarms in `store`: the open, deferred and waiting ones are read back on
442    /// first use, so a restarted site repeats its open P1 alarms, sends its deferred P2
443    /// alarms and reviews what was waiting (spec 3.5 §7.21).
444    ///
445    /// # Example
446    ///
447    /// ```rust
448    /// use std::sync::Arc;
449    /// use adk_website::alarms::{AlarmRouter, InMemoryAlarmStore};
450    /// use awp_types::{Cadence, Reporting};
451    ///
452    /// let reporting = Reporting { review: Cadence::Weekly, routes: vec![], quiet_hours: None };
453    /// let router = AlarmRouter::new(uuid::Uuid::nil(), &reporting)
454    ///     .with_store(Arc::new(InMemoryAlarmStore::default()));
455    /// # let _ = router;
456    /// ```
457    #[must_use]
458    pub fn with_store(mut self, store: Arc<dyn AlarmStore>) -> Self {
459        self.store = Some(store);
460        self
461    }
462
463    /// The router's state, read from its store on first use.
464    async fn state(&self) -> tokio::sync::MutexGuard<'_, RouterState> {
465        self.loaded
466            .get_or_init(|| async {
467                let Some(store) = &self.store else { return };
468                let records = match store.alarms(self.site).await {
469                    Ok(records) => records,
470                    Err(error) => {
471                        tracing::warn!(error = %error, "the alarms could not be read back");
472                        return;
473                    }
474                };
475                let mut state = self.state.lock().await;
476                let mut highest = 0;
477                for record in records {
478                    if let Some(n) =
479                        record.alarm.id.strip_prefix("alarm-").and_then(|n| n.parse::<u64>().ok())
480                    {
481                        highest = highest.max(n);
482                    }
483                    match record.state {
484                        AlarmState::Open { attempts, last } => {
485                            let alarm = record.alarm.clone();
486                            state.open.insert(alarm.id.clone(), OpenP1 { alarm, attempts, last });
487                        }
488                        AlarmState::Deferred => state.deferred.push(record.alarm.clone()),
489                        AlarmState::Review => state.review.push(record.alarm.clone()),
490                        AlarmState::Done => {}
491                    }
492                    state.raised.push(record.alarm);
493                }
494                self.next.fetch_max(highest + 1, Ordering::Relaxed);
495            })
496            .await;
497        self.state.lock().await
498    }
499
500    /// Keeps where `alarm` stands; a failure is logged and never stops the alarm.
501    async fn keep(&self, alarm: &Alarm, state: AlarmState) {
502        let Some(store) = &self.store else { return };
503        if let Err(error) = store.save(&AlarmRecord { alarm: alarm.clone(), state }).await {
504            tracing::warn!(website.alarm = %alarm.id, error = %error, "an alarm's state could not be kept");
505        }
506    }
507
508    /// Delivers on `sink`'s channel to the owner's `thread` there.
509    #[must_use]
510    pub fn with_sink(mut self, sink: Arc<dyn ChannelSink>, thread: impl Into<String>) -> Self {
511        self.sinks.insert(sink.channel().to_string(), (sink, thread.into()));
512        self
513    }
514
515    /// The clock.
516    #[must_use]
517    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
518        self.clock = clock;
519        self
520    }
521
522    /// How often an unacknowledged P1 alarm repeats.
523    #[must_use]
524    pub fn with_repeat(mut self, every: Duration) -> Self {
525        self.repeat = every;
526        self
527    }
528
529    /// Where `website.alarm.*` records go.
530    #[must_use]
531    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
532        self.audit = Some(trail);
533        self
534    }
535
536    fn in_quiet_hours(&self, at: DateTime<Utc>) -> bool {
537        self.quiet.as_ref().is_some_and(|quiet| quiet.contains(at))
538    }
539
540    /// The channels of `urgency`: its route's channels the router has a thread on; for P1
541    /// with no route, every thread, since an incident must reach the owner.
542    fn channels(&self, urgency: Urgency) -> Vec<String> {
543        let routed: Vec<String> = self
544            .routes
545            .get(&urgency)
546            .map(|channels| {
547                channels.iter().filter(|c| self.sinks.contains_key(*c)).cloned().collect()
548            })
549            .unwrap_or_default();
550        if routed.is_empty() && urgency == Urgency::P1 {
551            return self.sinks.keys().cloned().collect();
552        }
553        routed
554    }
555
556    async fn send(&self, alarm: &Alarm, channels: &[String], attempt: u32) -> Vec<Delivery> {
557        let mut deliveries = Vec::new();
558        let at = self.clock.now();
559        for channel in channels {
560            let Some((sink, thread)) = self.sinks.get(channel) else { continue };
561            match sink.send_message(thread, &alarm.text()).await {
562                Ok(()) => deliveries.push(Delivery {
563                    alarm: alarm.id.clone(),
564                    channel: channel.clone(),
565                    thread: thread.clone(),
566                    attempt,
567                    at,
568                }),
569                Err(error) => {
570                    tracing::warn!(website.alarm = %alarm.id, channel, error = %error, "alarm delivery failed")
571                }
572            }
573        }
574        deliveries
575    }
576
577    /// Raises `alarm` (spec 3.5 §7.21): P1 at once on its channels, quiet hours or not, and
578    /// open until acknowledged; P2 on its channel outside quiet hours, deferred inside them,
579    /// and to the weekly review when the charter routes it nowhere; P3 to the weekly review.
580    pub async fn raise(&self, mut alarm: Alarm) -> Routed {
581        // Read the kept alarms first, so a new id follows theirs.
582        drop(self.state().await);
583        if alarm.id.is_empty() {
584            alarm.id = format!("alarm-{}", self.next.fetch_add(1, Ordering::Relaxed));
585        }
586        let now = self.clock.now();
587        let (routed, kept) = match alarm.urgency {
588            Urgency::P1 => {
589                let deliveries = self.send(&alarm, &self.channels(Urgency::P1), 1).await;
590                self.state().await.open.insert(
591                    alarm.id.clone(),
592                    OpenP1 { alarm: alarm.clone(), attempts: 1, last: now },
593                );
594                (Routed::Sent { deliveries }, AlarmState::Open { attempts: 1, last: now })
595            }
596            Urgency::P2 => {
597                let channels = self.channels(Urgency::P2);
598                if channels.is_empty() {
599                    self.state().await.review.push(alarm.clone());
600                    (Routed::Review, AlarmState::Review)
601                } else if self.in_quiet_hours(now) {
602                    self.state().await.deferred.push(alarm.clone());
603                    (Routed::Deferred, AlarmState::Deferred)
604                } else {
605                    let deliveries = self.send(&alarm, &channels, 1).await;
606                    (Routed::Sent { deliveries }, AlarmState::Done)
607                }
608            }
609            _ => {
610                self.state().await.review.push(alarm.clone());
611                (Routed::Review, AlarmState::Review)
612            }
613        };
614        self.state().await.raised.push(alarm.clone());
615        self.keep(&alarm, kept).await;
616        tracing::info!(website.alarm = %alarm.id, website.alarm.kind = %alarm.kind, urgency = ?alarm.urgency, "website.alarm.raised");
617        audit::record(
618            self.audit.as_ref(),
619            audit::ALARM_RAISED,
620            AuditActor::default(),
621            json!({
622                "site": self.site,
623                "alarm": alarm.id,
624                "kind": alarm.kind,
625                "urgency": alarm.urgency,
626                "routed": routed,
627            }),
628        )
629        .await;
630        routed
631    }
632
633    /// Records that a person acknowledged the P1 alarm `id`: it stops repeating.
634    ///
635    /// # Errors
636    ///
637    /// `Forbidden` when `by` is not a person; `NotFound` for an alarm that is not open.
638    pub async fn acknowledge(&self, id: &str, by: &SubjectRef) -> Result<()> {
639        if by.kind != SubjectKind::Human || adk_kernel::charter::is_agent_principal(&by.id) {
640            return Err(AdkError::new(
641                ErrorComponent::Agent,
642                ErrorCategory::Forbidden,
643                "website.alarm.agent_ack",
644                format!("{} is not a person; only a person acknowledges an alarm", by.id),
645            ));
646        }
647        let Some(open) = self.state().await.open.remove(id) else {
648            return Err(AdkError::new(
649                ErrorComponent::Agent,
650                ErrorCategory::NotFound,
651                "website.alarm.not_open",
652                format!("alarm {id} is not open"),
653            ));
654        };
655        self.keep(&open.alarm, AlarmState::Done).await;
656        audit::record(
657            self.audit.as_ref(),
658            audit::ALARM_ACKNOWLEDGED,
659            AuditActor::subject(by.clone()),
660            json!({ "site": self.site, "alarm": id }),
661        )
662        .await;
663        Ok(())
664    }
665
666    /// Sends what is due (spec 3.5 §7.21): every open P1 alarm whose last send is older than
667    /// the repeat interval, and the deferred P2 alarms once quiet hours end. Run it from the
668    /// alarms job's schedule.
669    pub async fn tick(&self) -> Vec<Delivery> {
670        let now = self.clock.now();
671        let due: Vec<(Alarm, u32)> = {
672            let mut state = self.state().await;
673            state
674                .open
675                .values_mut()
676                .filter(|open| now - open.last >= self.repeat)
677                .map(|open| {
678                    open.attempts += 1;
679                    open.last = now;
680                    (open.alarm.clone(), open.attempts)
681                })
682                .collect()
683        };
684        let mut deliveries = Vec::new();
685        for (alarm, attempt) in due {
686            deliveries.extend(self.send(&alarm, &self.channels(Urgency::P1), attempt).await);
687            self.keep(&alarm, AlarmState::Open { attempts: attempt, last: now }).await;
688        }
689        if !self.in_quiet_hours(now) {
690            let deferred = std::mem::take(&mut self.state().await.deferred);
691            let channels = self.channels(Urgency::P2);
692            for alarm in deferred {
693                deliveries.extend(self.send(&alarm, &channels, 1).await);
694                self.keep(&alarm, AlarmState::Done).await;
695            }
696        }
697        deliveries
698    }
699
700    /// The P1 alarms still open.
701    pub async fn open(&self) -> Vec<Alarm> {
702        self.state().await.open.values().map(|open| open.alarm.clone()).collect()
703    }
704
705    /// The P2 alarms deferred until quiet hours end.
706    pub async fn deferred(&self) -> Vec<Alarm> {
707        self.state().await.deferred.clone()
708    }
709
710    /// The alarms waiting for the weekly review.
711    pub async fn review_items(&self) -> Vec<Alarm> {
712        self.state().await.review.clone()
713    }
714
715    /// Takes the alarms waiting for the weekly review, which the review then carries.
716    pub async fn take_review_items(&self) -> Vec<Alarm> {
717        let taken = std::mem::take(&mut self.state().await.review);
718        for alarm in &taken {
719            self.keep(alarm, AlarmState::Done).await;
720        }
721        taken
722    }
723
724    /// Clears the alarms `ids` from those waiting for the weekly review: a review that
725    /// carried them reached the owner (spec 3.5 §7.21).
726    pub async fn clear_review_items(&self, ids: &[String]) {
727        let cleared: Vec<Alarm> = {
728            let mut state = self.state().await;
729            let (cleared, kept) =
730                std::mem::take(&mut state.review).into_iter().partition(|a| ids.contains(&a.id));
731            state.review = kept;
732            cleared
733        };
734        for alarm in &cleared {
735            self.keep(alarm, AlarmState::Done).await;
736        }
737    }
738
739    /// Every alarm raised since `since`, for the weekly review's incidents.
740    pub async fn raised_since(&self, since: DateTime<Utc>) -> Vec<Alarm> {
741        self.state().await.raised.iter().filter(|a| a.raised_at >= since).cloned().collect()
742    }
743}
744
745#[async_trait]
746impl CharterEventSink for AlarmRouter {
747    async fn emit(&self, event: &CharterEvent) {
748        let at = self.clock.now();
749        let (site, kind, summary) = match event {
750            CharterEvent::GuardrailBreached {
751                site,
752                guardrail,
753                metric,
754                value,
755                threshold,
756                jobs,
757                ..
758            } => (
759                *site,
760                "guardrail_breach",
761                format!(
762                    "guardrail {guardrail} breached: {metric} at {value:.3} against {threshold}; \
763                     paused {}",
764                    jobs.join(", ")
765                ),
766            ),
767            CharterEvent::JobPaused { site, job, reason, .. } => {
768                (*site, "job_paused", format!("job {job} paused: {reason}"))
769            }
770            CharterEvent::AutonomyChanged { site, job, from, to, reason, .. } => (
771                *site,
772                "autonomy_changed",
773                format!("job {job} moved from {from:?} to {to:?}: {reason}"),
774            ),
775            CharterEvent::PromotionOffered { site, job, to, streak, .. } => (
776                *site,
777                "promotion_offered",
778                format!("job {job} earned {to:?} after {streak} unchanged approvals"),
779            ),
780            CharterEvent::BaselineLocked { site, kpi, value, .. } => (
781                *site,
782                "baseline_locked",
783                format!("KPI {kpi} has a baseline of {value:.2}; you may set a target"),
784            ),
785            CharterEvent::Committed { site, version, .. } => {
786                (*site, "charter_committed", format!("charter version {version} took effect"))
787            }
788            other => (self.site, "charter_event", format!("{other:?}")),
789        };
790        self.raise(Alarm::new(site, event.urgency(), kind, summary, at)).await;
791    }
792}
793
794#[async_trait]
795impl WalletAlarmHook for AlarmRouter {
796    async fn raise(&self, alarm: &WalletAlarm) -> Result<()> {
797        let kind = match alarm.urgency() {
798            Urgency::P1 => "payment_anomaly",
799            _ => "reconciliation_mismatch",
800        };
801        AlarmRouter::raise(
802            self,
803            Alarm::new(self.site, alarm.urgency(), kind, alarm.summary(), alarm.raised_at),
804        )
805        .await;
806        Ok(())
807    }
808}
809
810/// The most characters of a handoff card's summary.
811const HANDOFF_SUMMARY_MAX: usize = 600;
812
813/// `lead_handoff` over `router` (spec 3.5 §7.20 "Warm handoff with context", §7.21): the
814/// Revenue agent hands a qualified lead to the owner as one P2 card with the conversation's
815/// summary, on the owner's chosen channel outside quiet hours. It implements `adk-harness`'
816/// catalogue entry, so the ladder decides it as the `handoff` job's.
817///
818/// # Example
819///
820/// ```rust
821/// use std::sync::Arc;
822/// use adk_tool::SimpleToolContext;
823/// use adk_website::alarms::{AlarmRouter, handoff_tool};
824/// use awp_types::{Cadence, Reporting};
825///
826/// # #[tokio::main(flavor = "current_thread")]
827/// # async fn main() {
828/// let reporting = Reporting { review: Cadence::Weekly, routes: vec![], quiet_hours: None };
829/// let router = Arc::new(AlarmRouter::new(uuid::Uuid::nil(), &reporting));
830/// let tool = handoff_tool(router.clone());
831/// let ctx = Arc::new(SimpleToolContext::new("revenue"));
832/// let card = tool.execute(ctx, serde_json::json!({ "leadRef": "lead-1", "summary": "A wedding cake for 120 guests on 14 February" })).await.unwrap();
833/// assert_eq!(card["handedOff"], true);
834/// assert_eq!(router.raised_since(chrono::DateTime::UNIX_EPOCH).await[0].kind, "lead_handoff");
835/// # }
836/// ```
837pub fn handoff_tool(router: Arc<AlarmRouter>) -> Arc<dyn adk_core::Tool> {
838    Arc::new(HandoffTool { router, leads: None })
839}
840
841/// `lead_handoff` over `router` that hands a lead off only once its score has reached the
842/// kind's threshold, and only once (spec 3.5 §5 S8, §7.20): the card carries the score the
843/// site computed, not one the agent states.
844pub fn handoff_tool_for(
845    router: Arc<AlarmRouter>,
846    leads: Arc<crate::leads::Leads>,
847) -> Arc<dyn adk_core::Tool> {
848    Arc::new(HandoffTool { router, leads: Some(leads) })
849}
850
851/// `lead_handoff`: one card to the owner per qualified lead.
852struct HandoffTool {
853    router: Arc<AlarmRouter>,
854    leads: Option<Arc<crate::leads::Leads>>,
855}
856
857#[async_trait]
858impl adk_core::Tool for HandoffTool {
859    fn name(&self) -> &str {
860        adk_harness::website::LEAD_HANDOFF
861    }
862
863    fn description(&self) -> &str {
864        "Hands a qualified lead to the owner: one card on their chosen channel with the lead's \
865         reference and a short summary of the conversation in your own words."
866    }
867
868    fn parameters_schema(&self) -> Option<serde_json::Value> {
869        Some(json!({
870            "type": "object",
871            "properties": {
872                "leadRef": { "type": "string" },
873                "summary": { "type": "string", "maxLength": HANDOFF_SUMMARY_MAX },
874                "score": { "type": "number" }
875            },
876            "required": ["leadRef", "summary"],
877            "additionalProperties": false
878        }))
879    }
880
881    fn origin(&self) -> &str {
882        adk_harness::website::BACK_OFFICE_ORIGIN
883    }
884
885    fn effect(&self) -> adk_core::ToolEffect {
886        adk_core::ToolEffect::NonIdempotent
887    }
888
889    async fn execute(
890        &self,
891        _ctx: Arc<dyn adk_core::ToolContext>,
892        args: serde_json::Value,
893    ) -> Result<serde_json::Value> {
894        let invalid = |message: &str| {
895            AdkError::new(
896                ErrorComponent::Tool,
897                ErrorCategory::InvalidInput,
898                "website.handoff.invalid",
899                format!("invalid arguments for lead_handoff: {message}"),
900            )
901        };
902        let lead = args["leadRef"].as_str().filter(|r| !r.trim().is_empty());
903        let lead = lead.ok_or_else(|| invalid("a leadRef is required"))?;
904        let summary: String = args["summary"]
905            .as_str()
906            .ok_or_else(|| invalid("a summary is required"))?
907            .chars()
908            .take(HANDOFF_SUMMARY_MAX)
909            .collect();
910        let score = match &self.leads {
911            Some(leads) => {
912                let scored = leads.hand_off(&awp_types::LeadRef(lead.to_string())).await?;
913                format!(" (score {:.0} of {:.0})", scored.value, scored.threshold)
914            }
915            None => args["score"]
916                .as_f64()
917                .map(|score| format!(" (score {score:.0})"))
918                .unwrap_or_default(),
919        };
920        let routed = self
921            .router
922            .raise(Alarm::new(
923                self.router.site,
924                Urgency::P2,
925                "lead_handoff",
926                format!("A warm lead is ready for you{score}: {summary} [lead {lead}]"),
927                self.router.clock.now(),
928            ))
929            .await;
930        Ok(json!({ "handedOff": true, "lead": lead, "routed": routed }))
931    }
932}