adk-website 3.0.0

A prebuilt AWP 2.0 website for ADK-Rust: site kinds, a team of eight agents, agent-led onboarding, themes, capability packs, playbooks, jobs, alarms and the weekly review
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
//! Alarms by urgency (spec 3.5 §7.21, §7.20 "Alarms by urgency and channel").
//!
//! | Urgency | Examples | Delivery |
//! |---|---|---|
//! | P1 | Incident, site down, payment anomaly, key compromise suspected | Immediately on the owner's P1 channels, including inside quiet hours; repeated until acknowledged |
//! | P2 | A held decision blocking a customer, a guardrail breach, a failed renewal | On the owner's chosen channel, outside quiet hours |
//! | P3 | Everything else | The weekly review |
//!
//! [`AlarmRouter`] delivers through the kernel's `ChannelSink`s to the owner's paired
//! threads, reads the charter's reporting routes and quiet hours, and is the product's
//! `CharterEventSink` (guardrail breaches, pauses, autonomy changes) and `WalletAlarmHook`
//! (payment anomalies, reconciliation mismatches).
//!
//! With an [`AlarmStore`] ([`AlarmRouter::with_store`]) the open P1 alarms, the P2 alarms
//! deferred to the end of quiet hours and the alarms waiting for the weekly review survive a
//! restart: [`SqliteAlarmStore`] keeps them in a served site's `data/edge.db`, and every store
//! passes [`conformance::alarm_store`].

use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use adk_core::audit_log::{AuditActor, AuditTrail};
use adk_core::principal::{SubjectKind, SubjectRef};
use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
use adk_kernel::QuietHours;
use adk_kernel::channels::ChannelSink;
use adk_kernel::charter::{CharterEvent, CharterEventSink};
use adk_payments::wallet::{WalletAlarm, WalletAlarmHook};
use async_trait::async_trait;
use awp_types::{Reporting, Urgency};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::Mutex;
use uuid::Uuid;

use crate::audit;

/// How often an unacknowledged P1 alarm is sent again (spec 3.5 §7.21).
pub const P1_REPEAT: Duration = Duration::minutes(15);

/// An alarm to the owner (spec 3.5 §7.21).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Alarm {
    /// The alarm's id, given when it is raised.
    #[serde(default)]
    pub id: String,
    /// The site.
    pub site: Uuid,
    /// How soon the owner hears of it.
    pub urgency: Urgency,
    /// What it is, such as `incident`, `payment_anomaly` or `guardrail_breach`.
    pub kind: String,
    /// One line for the owner: what happened, what was done, what the owner must decide.
    pub summary: String,
    /// When it was raised.
    pub raised_at: DateTime<Utc>,
}

impl Alarm {
    /// An alarm of `kind` at `urgency` for `site`.
    pub fn new(
        site: Uuid,
        urgency: Urgency,
        kind: impl Into<String>,
        summary: impl Into<String>,
        raised_at: DateTime<Utc>,
    ) -> Self {
        Self {
            id: String::new(),
            site,
            urgency,
            kind: kind.into(),
            summary: summary.into(),
            raised_at,
        }
    }

    /// The alarm as the owner reads it on a channel.
    pub fn text(&self) -> String {
        let label = match self.urgency {
            Urgency::P1 => "Urgent",
            Urgency::P2 => "Needs you",
            _ => "For the review",
        };
        format!("{label}: {} (alarm {})", self.summary, self.id)
    }
}

/// One message an alarm sent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Delivery {
    /// The alarm.
    pub alarm: String,
    /// The channel.
    pub channel: String,
    /// The owner's thread on it.
    pub thread: String,
    /// The attempt: 1 for the first send of a P1 alarm, more for its repeats.
    pub attempt: u32,
    /// When.
    pub at: DateTime<Utc>,
}

/// What [`AlarmRouter::raise`] did with an alarm.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "routed", rename_all = "snake_case")]
pub enum Routed {
    /// Sent now.
    Sent {
        /// The messages.
        deliveries: Vec<Delivery>,
    },
    /// A P2 alarm inside quiet hours: sent when they end.
    Deferred,
    /// Held for the weekly review.
    Review,
}

#[derive(Debug, Clone)]
struct OpenP1 {
    alarm: Alarm,
    attempts: u32,
    last: DateTime<Utc>,
}

#[derive(Debug, Default)]
struct RouterState {
    open: BTreeMap<String, OpenP1>,
    deferred: Vec<Alarm>,
    review: Vec<Alarm>,
    raised: Vec<Alarm>,
}

/// Where an alarm stands (spec 3.5 §7.21).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case", rename_all_fields = "camelCase")]
pub enum AlarmState {
    /// A P1 alarm no person has acknowledged: it repeats.
    Open {
        /// Sends so far.
        attempts: u32,
        /// The last send.
        last: DateTime<Utc>,
    },
    /// A P2 alarm raised inside quiet hours: sent when they end.
    Deferred,
    /// Waiting for the weekly review.
    Review,
    /// Sent, acknowledged or carried by a review.
    Done,
}

/// An alarm and where it stands, as an [`AlarmStore`] keeps it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlarmRecord {
    /// The alarm.
    pub alarm: Alarm,
    /// Where it stands.
    pub state: AlarmState,
}

/// Where an [`AlarmRouter`] keeps its alarms, so a restart neither drops an open P1 alarm
/// nor a deferred or waiting one (spec 3.5 §7.21).
///
/// # Example
///
/// ```rust
/// use adk_website::alarms::{Alarm, AlarmRecord, AlarmState, AlarmStore, InMemoryAlarmStore};
/// use awp_types::Urgency;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> adk_core::Result<()> {
/// let store = InMemoryAlarmStore::default();
/// let mut alarm = Alarm::new(uuid::Uuid::nil(), Urgency::P3, "freshness", "Two pages are stale", chrono::Utc::now());
/// alarm.id = "alarm-1".into();
/// store.save(&AlarmRecord { alarm, state: AlarmState::Review }).await?;
/// assert_eq!(store.alarms(uuid::Uuid::nil()).await?.len(), 1);
/// # Ok(())
/// # }
/// ```
#[async_trait]
pub trait AlarmStore: Send + Sync {
    /// Keeps `record`, replacing the one with its alarm's id; a new alarm is listed after
    /// those kept before it.
    ///
    /// # Errors
    ///
    /// The store's error.
    async fn save(&self, record: &AlarmRecord) -> Result<()>;

    /// The alarms of `site`, in the order they were first kept.
    ///
    /// # Errors
    ///
    /// The store's error.
    async fn alarms(&self, site: Uuid) -> Result<Vec<AlarmRecord>>;
}

/// An [`AlarmStore`] in memory, for tests.
#[derive(Debug, Default)]
pub struct InMemoryAlarmStore {
    records: Mutex<Vec<AlarmRecord>>,
}

#[async_trait]
impl AlarmStore for InMemoryAlarmStore {
    async fn save(&self, record: &AlarmRecord) -> Result<()> {
        let mut records = self.records.lock().await;
        match records
            .iter_mut()
            .find(|kept| kept.alarm.site == record.alarm.site && kept.alarm.id == record.alarm.id)
        {
            Some(kept) => *kept = record.clone(),
            None => records.push(record.clone()),
        }
        Ok(())
    }

    async fn alarms(&self, site: Uuid) -> Result<Vec<AlarmRecord>> {
        Ok(self.records.lock().await.iter().filter(|r| r.alarm.site == site).cloned().collect())
    }
}

fn alarm_store_error(error: impl std::fmt::Display) -> AdkError {
    AdkError::config(format!("the site's alarm store: {error}"))
}

/// An [`AlarmStore`] in SQLite, such as a served site's `data/edge.db`.
///
/// # Example
///
/// ```rust
/// use adk_website::alarms::{AlarmStore, SqliteAlarmStore};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> adk_core::Result<()> {
/// let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap();
/// let store = SqliteAlarmStore::new(pool);
/// store.migrate().await?;
/// assert!(store.alarms(uuid::Uuid::nil()).await?.is_empty());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SqliteAlarmStore {
    pool: sqlx::SqlitePool,
}

impl SqliteAlarmStore {
    /// The store over `pool`; call [`migrate`](Self::migrate) once.
    pub fn new(pool: sqlx::SqlitePool) -> Self {
        Self { pool }
    }

    /// Creates the table.
    ///
    /// # Errors
    ///
    /// The database's error.
    pub async fn migrate(&self) -> Result<()> {
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS website_alarms (
                seq INTEGER PRIMARY KEY AUTOINCREMENT,
                site TEXT NOT NULL, id TEXT NOT NULL, record TEXT NOT NULL,
                UNIQUE (site, id))",
        )
        .execute(&self.pool)
        .await
        .map_err(alarm_store_error)?;
        Ok(())
    }
}

#[async_trait]
impl AlarmStore for SqliteAlarmStore {
    async fn save(&self, record: &AlarmRecord) -> Result<()> {
        sqlx::query(
            "INSERT INTO website_alarms (site, id, record) VALUES (?, ?, ?)
             ON CONFLICT (site, id) DO UPDATE SET record = excluded.record",
        )
        .bind(record.alarm.site.to_string())
        .bind(&record.alarm.id)
        .bind(serde_json::to_string(record).map_err(alarm_store_error)?)
        .execute(&self.pool)
        .await
        .map_err(alarm_store_error)?;
        Ok(())
    }

    async fn alarms(&self, site: Uuid) -> Result<Vec<AlarmRecord>> {
        let rows: Vec<(String,)> =
            sqlx::query_as("SELECT record FROM website_alarms WHERE site = ? ORDER BY seq")
                .bind(site.to_string())
                .fetch_all(&self.pool)
                .await
                .map_err(alarm_store_error)?;
        rows.iter()
            .map(|(record,)| serde_json::from_str(record).map_err(alarm_store_error))
            .collect()
    }
}

/// The conformance check every [`AlarmStore`] passes (spec 3.5 §7.21).
pub mod conformance {
    use awp_types::Urgency;
    use uuid::Uuid;

    use super::{Alarm, AlarmRecord, AlarmState, AlarmStore};

    fn alarm(site: Uuid, id: &str, urgency: Urgency) -> Alarm {
        let mut alarm =
            Alarm::new(site, urgency, "incident", "The site is down", chrono::Utc::now());
        alarm.id = id.to_string();
        alarm
    }

    /// Records read back in the order they were first kept, replaced by id, each site's
    /// apart.
    ///
    /// # Panics
    ///
    /// When the store breaks its contract.
    pub async fn alarm_store(store: &dyn AlarmStore) {
        let (site, other) = (Uuid::new_v4(), Uuid::new_v4());
        let last = chrono::Utc::now();
        let open = AlarmRecord {
            alarm: alarm(site, "alarm-1", Urgency::P1),
            state: AlarmState::Open { attempts: 1, last },
        };
        let waiting =
            AlarmRecord { alarm: alarm(site, "alarm-2", Urgency::P3), state: AlarmState::Review };
        store.save(&open).await.unwrap();
        store.save(&waiting).await.unwrap();
        store
            .save(&AlarmRecord {
                alarm: alarm(other, "alarm-1", Urgency::P2),
                state: AlarmState::Deferred,
            })
            .await
            .unwrap();
        assert_eq!(store.alarms(site).await.unwrap(), vec![open.clone(), waiting.clone()]);
        let acknowledged = AlarmRecord { state: AlarmState::Done, ..open.clone() };
        store.save(&acknowledged).await.unwrap();
        assert_eq!(
            store.alarms(site).await.unwrap(),
            vec![acknowledged, waiting],
            "replaced in place"
        );
        assert_eq!(store.alarms(other).await.unwrap()[0].state, AlarmState::Deferred);
        assert!(store.alarms(Uuid::new_v4()).await.unwrap().is_empty());
    }
}

/// Routes alarms to the owner by urgency (spec 3.5 §7.21).
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_website::alarms::{Alarm, AlarmRouter, Routed};
/// use awp_types::{Reporting, Urgency, Cadence};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let reporting = Reporting { review: Cadence::Weekly, routes: vec![], quiet_hours: None };
/// let router = AlarmRouter::new(uuid::Uuid::nil(), &reporting);
/// let routed = router.raise(Alarm::new(uuid::Uuid::nil(), Urgency::P3, "freshness", "Two pages are stale", chrono::Utc::now())).await;
/// assert_eq!(routed, Routed::Review);
/// assert_eq!(router.review_items().await.len(), 1);
/// # }
/// ```
pub struct AlarmRouter {
    site: Uuid,
    routes: BTreeMap<Urgency, Vec<String>>,
    quiet: Option<QuietHours>,
    sinks: BTreeMap<String, (Arc<dyn ChannelSink>, String)>,
    clock: Arc<dyn Clock>,
    repeat: Duration,
    audit: Option<AuditTrail>,
    state: Mutex<RouterState>,
    next: AtomicU64,
    store: Option<Arc<dyn AlarmStore>>,
    loaded: tokio::sync::OnceCell<()>,
}

impl std::fmt::Debug for AlarmRouter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AlarmRouter")
            .field("site", &self.site)
            .field("routes", &self.routes)
            .field("channels", &self.sinks.keys().collect::<Vec<_>>())
            .finish_non_exhaustive()
    }
}

/// The kernel's quiet hours for the charter's (spec 3.5 §7.21): in their IANA time zone,
/// or UTC when the zone is unknown.
pub fn quiet_hours(reporting: &Reporting) -> Option<QuietHours> {
    let quiet = reporting.quiet_hours.as_ref()?;
    let hours = QuietHours::new(quiet.start, quiet.end);
    Some(match quiet.timezone.parse::<chrono_tz::Tz>() {
        Ok(zone) => hours.with_time_zone(zone),
        Err(_) => {
            tracing::warn!(timezone = %quiet.timezone, "unknown quiet-hours time zone; reading the hours in UTC");
            hours.with_utc_offset_minutes(0)
        }
    })
}

impl AlarmRouter {
    /// A router for `site` over the charter's `reporting`: its routes per urgency and its
    /// quiet hours. Add the owner's threads with [`with_sink`](Self::with_sink).
    pub fn new(site: Uuid, reporting: &Reporting) -> Self {
        let routes = reporting
            .routes
            .iter()
            .map(|route| {
                (route.urgency, route.channels.iter().map(|c| c.as_str().to_string()).collect())
            })
            .collect();
        Self {
            site,
            routes,
            quiet: quiet_hours(reporting),
            sinks: BTreeMap::new(),
            clock: Arc::new(SystemClock),
            repeat: P1_REPEAT,
            audit: None,
            state: Mutex::new(RouterState::default()),
            next: AtomicU64::new(1),
            store: None,
            loaded: tokio::sync::OnceCell::new(),
        }
    }

    /// Keeps the alarms in `store`: the open, deferred and waiting ones are read back on
    /// first use, so a restarted site repeats its open P1 alarms, sends its deferred P2
    /// alarms and reviews what was waiting (spec 3.5 §7.21).
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_website::alarms::{AlarmRouter, InMemoryAlarmStore};
    /// use awp_types::{Cadence, Reporting};
    ///
    /// let reporting = Reporting { review: Cadence::Weekly, routes: vec![], quiet_hours: None };
    /// let router = AlarmRouter::new(uuid::Uuid::nil(), &reporting)
    ///     .with_store(Arc::new(InMemoryAlarmStore::default()));
    /// # let _ = router;
    /// ```
    #[must_use]
    pub fn with_store(mut self, store: Arc<dyn AlarmStore>) -> Self {
        self.store = Some(store);
        self
    }

    /// The router's state, read from its store on first use.
    async fn state(&self) -> tokio::sync::MutexGuard<'_, RouterState> {
        self.loaded
            .get_or_init(|| async {
                let Some(store) = &self.store else { return };
                let records = match store.alarms(self.site).await {
                    Ok(records) => records,
                    Err(error) => {
                        tracing::warn!(error = %error, "the alarms could not be read back");
                        return;
                    }
                };
                let mut state = self.state.lock().await;
                let mut highest = 0;
                for record in records {
                    if let Some(n) =
                        record.alarm.id.strip_prefix("alarm-").and_then(|n| n.parse::<u64>().ok())
                    {
                        highest = highest.max(n);
                    }
                    match record.state {
                        AlarmState::Open { attempts, last } => {
                            let alarm = record.alarm.clone();
                            state.open.insert(alarm.id.clone(), OpenP1 { alarm, attempts, last });
                        }
                        AlarmState::Deferred => state.deferred.push(record.alarm.clone()),
                        AlarmState::Review => state.review.push(record.alarm.clone()),
                        AlarmState::Done => {}
                    }
                    state.raised.push(record.alarm);
                }
                self.next.fetch_max(highest + 1, Ordering::Relaxed);
            })
            .await;
        self.state.lock().await
    }

    /// Keeps where `alarm` stands; a failure is logged and never stops the alarm.
    async fn keep(&self, alarm: &Alarm, state: AlarmState) {
        let Some(store) = &self.store else { return };
        if let Err(error) = store.save(&AlarmRecord { alarm: alarm.clone(), state }).await {
            tracing::warn!(website.alarm = %alarm.id, error = %error, "an alarm's state could not be kept");
        }
    }

    /// Delivers on `sink`'s channel to the owner's `thread` there.
    #[must_use]
    pub fn with_sink(mut self, sink: Arc<dyn ChannelSink>, thread: impl Into<String>) -> Self {
        self.sinks.insert(sink.channel().to_string(), (sink, thread.into()));
        self
    }

    /// The clock.
    #[must_use]
    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.clock = clock;
        self
    }

    /// How often an unacknowledged P1 alarm repeats.
    #[must_use]
    pub fn with_repeat(mut self, every: Duration) -> Self {
        self.repeat = every;
        self
    }

    /// Where `website.alarm.*` records go.
    #[must_use]
    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
        self.audit = Some(trail);
        self
    }

    fn in_quiet_hours(&self, at: DateTime<Utc>) -> bool {
        self.quiet.as_ref().is_some_and(|quiet| quiet.contains(at))
    }

    /// The channels of `urgency`: its route's channels the router has a thread on; for P1
    /// with no route, every thread, since an incident must reach the owner.
    fn channels(&self, urgency: Urgency) -> Vec<String> {
        let routed: Vec<String> = self
            .routes
            .get(&urgency)
            .map(|channels| {
                channels.iter().filter(|c| self.sinks.contains_key(*c)).cloned().collect()
            })
            .unwrap_or_default();
        if routed.is_empty() && urgency == Urgency::P1 {
            return self.sinks.keys().cloned().collect();
        }
        routed
    }

    async fn send(&self, alarm: &Alarm, channels: &[String], attempt: u32) -> Vec<Delivery> {
        let mut deliveries = Vec::new();
        let at = self.clock.now();
        for channel in channels {
            let Some((sink, thread)) = self.sinks.get(channel) else { continue };
            match sink.send_message(thread, &alarm.text()).await {
                Ok(()) => deliveries.push(Delivery {
                    alarm: alarm.id.clone(),
                    channel: channel.clone(),
                    thread: thread.clone(),
                    attempt,
                    at,
                }),
                Err(error) => {
                    tracing::warn!(website.alarm = %alarm.id, channel, error = %error, "alarm delivery failed")
                }
            }
        }
        deliveries
    }

    /// Raises `alarm` (spec 3.5 §7.21): P1 at once on its channels, quiet hours or not, and
    /// open until acknowledged; P2 on its channel outside quiet hours, deferred inside them,
    /// and to the weekly review when the charter routes it nowhere; P3 to the weekly review.
    pub async fn raise(&self, mut alarm: Alarm) -> Routed {
        // Read the kept alarms first, so a new id follows theirs.
        drop(self.state().await);
        if alarm.id.is_empty() {
            alarm.id = format!("alarm-{}", self.next.fetch_add(1, Ordering::Relaxed));
        }
        let now = self.clock.now();
        let (routed, kept) = match alarm.urgency {
            Urgency::P1 => {
                let deliveries = self.send(&alarm, &self.channels(Urgency::P1), 1).await;
                self.state().await.open.insert(
                    alarm.id.clone(),
                    OpenP1 { alarm: alarm.clone(), attempts: 1, last: now },
                );
                (Routed::Sent { deliveries }, AlarmState::Open { attempts: 1, last: now })
            }
            Urgency::P2 => {
                let channels = self.channels(Urgency::P2);
                if channels.is_empty() {
                    self.state().await.review.push(alarm.clone());
                    (Routed::Review, AlarmState::Review)
                } else if self.in_quiet_hours(now) {
                    self.state().await.deferred.push(alarm.clone());
                    (Routed::Deferred, AlarmState::Deferred)
                } else {
                    let deliveries = self.send(&alarm, &channels, 1).await;
                    (Routed::Sent { deliveries }, AlarmState::Done)
                }
            }
            _ => {
                self.state().await.review.push(alarm.clone());
                (Routed::Review, AlarmState::Review)
            }
        };
        self.state().await.raised.push(alarm.clone());
        self.keep(&alarm, kept).await;
        tracing::info!(website.alarm = %alarm.id, website.alarm.kind = %alarm.kind, urgency = ?alarm.urgency, "website.alarm.raised");
        audit::record(
            self.audit.as_ref(),
            audit::ALARM_RAISED,
            AuditActor::default(),
            json!({
                "site": self.site,
                "alarm": alarm.id,
                "kind": alarm.kind,
                "urgency": alarm.urgency,
                "routed": routed,
            }),
        )
        .await;
        routed
    }

    /// Records that a person acknowledged the P1 alarm `id`: it stops repeating.
    ///
    /// # Errors
    ///
    /// `Forbidden` when `by` is not a person; `NotFound` for an alarm that is not open.
    pub async fn acknowledge(&self, id: &str, by: &SubjectRef) -> Result<()> {
        if by.kind != SubjectKind::Human || adk_kernel::charter::is_agent_principal(&by.id) {
            return Err(AdkError::new(
                ErrorComponent::Agent,
                ErrorCategory::Forbidden,
                "website.alarm.agent_ack",
                format!("{} is not a person; only a person acknowledges an alarm", by.id),
            ));
        }
        let Some(open) = self.state().await.open.remove(id) else {
            return Err(AdkError::new(
                ErrorComponent::Agent,
                ErrorCategory::NotFound,
                "website.alarm.not_open",
                format!("alarm {id} is not open"),
            ));
        };
        self.keep(&open.alarm, AlarmState::Done).await;
        audit::record(
            self.audit.as_ref(),
            audit::ALARM_ACKNOWLEDGED,
            AuditActor::subject(by.clone()),
            json!({ "site": self.site, "alarm": id }),
        )
        .await;
        Ok(())
    }

    /// Sends what is due (spec 3.5 §7.21): every open P1 alarm whose last send is older than
    /// the repeat interval, and the deferred P2 alarms once quiet hours end. Run it from the
    /// alarms job's schedule.
    pub async fn tick(&self) -> Vec<Delivery> {
        let now = self.clock.now();
        let due: Vec<(Alarm, u32)> = {
            let mut state = self.state().await;
            state
                .open
                .values_mut()
                .filter(|open| now - open.last >= self.repeat)
                .map(|open| {
                    open.attempts += 1;
                    open.last = now;
                    (open.alarm.clone(), open.attempts)
                })
                .collect()
        };
        let mut deliveries = Vec::new();
        for (alarm, attempt) in due {
            deliveries.extend(self.send(&alarm, &self.channels(Urgency::P1), attempt).await);
            self.keep(&alarm, AlarmState::Open { attempts: attempt, last: now }).await;
        }
        if !self.in_quiet_hours(now) {
            let deferred = std::mem::take(&mut self.state().await.deferred);
            let channels = self.channels(Urgency::P2);
            for alarm in deferred {
                deliveries.extend(self.send(&alarm, &channels, 1).await);
                self.keep(&alarm, AlarmState::Done).await;
            }
        }
        deliveries
    }

    /// The P1 alarms still open.
    pub async fn open(&self) -> Vec<Alarm> {
        self.state().await.open.values().map(|open| open.alarm.clone()).collect()
    }

    /// The P2 alarms deferred until quiet hours end.
    pub async fn deferred(&self) -> Vec<Alarm> {
        self.state().await.deferred.clone()
    }

    /// The alarms waiting for the weekly review.
    pub async fn review_items(&self) -> Vec<Alarm> {
        self.state().await.review.clone()
    }

    /// Takes the alarms waiting for the weekly review, which the review then carries.
    pub async fn take_review_items(&self) -> Vec<Alarm> {
        let taken = std::mem::take(&mut self.state().await.review);
        for alarm in &taken {
            self.keep(alarm, AlarmState::Done).await;
        }
        taken
    }

    /// Clears the alarms `ids` from those waiting for the weekly review: a review that
    /// carried them reached the owner (spec 3.5 §7.21).
    pub async fn clear_review_items(&self, ids: &[String]) {
        let cleared: Vec<Alarm> = {
            let mut state = self.state().await;
            let (cleared, kept) =
                std::mem::take(&mut state.review).into_iter().partition(|a| ids.contains(&a.id));
            state.review = kept;
            cleared
        };
        for alarm in &cleared {
            self.keep(alarm, AlarmState::Done).await;
        }
    }

    /// Every alarm raised since `since`, for the weekly review's incidents.
    pub async fn raised_since(&self, since: DateTime<Utc>) -> Vec<Alarm> {
        self.state().await.raised.iter().filter(|a| a.raised_at >= since).cloned().collect()
    }
}

#[async_trait]
impl CharterEventSink for AlarmRouter {
    async fn emit(&self, event: &CharterEvent) {
        let at = self.clock.now();
        let (site, kind, summary) = match event {
            CharterEvent::GuardrailBreached {
                site,
                guardrail,
                metric,
                value,
                threshold,
                jobs,
                ..
            } => (
                *site,
                "guardrail_breach",
                format!(
                    "guardrail {guardrail} breached: {metric} at {value:.3} against {threshold}; \
                     paused {}",
                    jobs.join(", ")
                ),
            ),
            CharterEvent::JobPaused { site, job, reason, .. } => {
                (*site, "job_paused", format!("job {job} paused: {reason}"))
            }
            CharterEvent::AutonomyChanged { site, job, from, to, reason, .. } => (
                *site,
                "autonomy_changed",
                format!("job {job} moved from {from:?} to {to:?}: {reason}"),
            ),
            CharterEvent::PromotionOffered { site, job, to, streak, .. } => (
                *site,
                "promotion_offered",
                format!("job {job} earned {to:?} after {streak} unchanged approvals"),
            ),
            CharterEvent::BaselineLocked { site, kpi, value, .. } => (
                *site,
                "baseline_locked",
                format!("KPI {kpi} has a baseline of {value:.2}; you may set a target"),
            ),
            CharterEvent::Committed { site, version, .. } => {
                (*site, "charter_committed", format!("charter version {version} took effect"))
            }
            other => (self.site, "charter_event", format!("{other:?}")),
        };
        self.raise(Alarm::new(site, event.urgency(), kind, summary, at)).await;
    }
}

#[async_trait]
impl WalletAlarmHook for AlarmRouter {
    async fn raise(&self, alarm: &WalletAlarm) -> Result<()> {
        let kind = match alarm.urgency() {
            Urgency::P1 => "payment_anomaly",
            _ => "reconciliation_mismatch",
        };
        AlarmRouter::raise(
            self,
            Alarm::new(self.site, alarm.urgency(), kind, alarm.summary(), alarm.raised_at),
        )
        .await;
        Ok(())
    }
}

/// The most characters of a handoff card's summary.
const HANDOFF_SUMMARY_MAX: usize = 600;

/// `lead_handoff` over `router` (spec 3.5 §7.20 "Warm handoff with context", §7.21): the
/// Revenue agent hands a qualified lead to the owner as one P2 card with the conversation's
/// summary, on the owner's chosen channel outside quiet hours. It implements `adk-harness`'
/// catalogue entry, so the ladder decides it as the `handoff` job's.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_tool::SimpleToolContext;
/// use adk_website::alarms::{AlarmRouter, handoff_tool};
/// use awp_types::{Cadence, Reporting};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let reporting = Reporting { review: Cadence::Weekly, routes: vec![], quiet_hours: None };
/// let router = Arc::new(AlarmRouter::new(uuid::Uuid::nil(), &reporting));
/// let tool = handoff_tool(router.clone());
/// let ctx = Arc::new(SimpleToolContext::new("revenue"));
/// let card = tool.execute(ctx, serde_json::json!({ "leadRef": "lead-1", "summary": "A wedding cake for 120 guests on 14 February" })).await.unwrap();
/// assert_eq!(card["handedOff"], true);
/// assert_eq!(router.raised_since(chrono::DateTime::UNIX_EPOCH).await[0].kind, "lead_handoff");
/// # }
/// ```
pub fn handoff_tool(router: Arc<AlarmRouter>) -> Arc<dyn adk_core::Tool> {
    Arc::new(HandoffTool { router, leads: None })
}

/// `lead_handoff` over `router` that hands a lead off only once its score has reached the
/// kind's threshold, and only once (spec 3.5 §5 S8, §7.20): the card carries the score the
/// site computed, not one the agent states.
pub fn handoff_tool_for(
    router: Arc<AlarmRouter>,
    leads: Arc<crate::leads::Leads>,
) -> Arc<dyn adk_core::Tool> {
    Arc::new(HandoffTool { router, leads: Some(leads) })
}

/// `lead_handoff`: one card to the owner per qualified lead.
struct HandoffTool {
    router: Arc<AlarmRouter>,
    leads: Option<Arc<crate::leads::Leads>>,
}

#[async_trait]
impl adk_core::Tool for HandoffTool {
    fn name(&self) -> &str {
        adk_harness::website::LEAD_HANDOFF
    }

    fn description(&self) -> &str {
        "Hands a qualified lead to the owner: one card on their chosen channel with the lead's \
         reference and a short summary of the conversation in your own words."
    }

    fn parameters_schema(&self) -> Option<serde_json::Value> {
        Some(json!({
            "type": "object",
            "properties": {
                "leadRef": { "type": "string" },
                "summary": { "type": "string", "maxLength": HANDOFF_SUMMARY_MAX },
                "score": { "type": "number" }
            },
            "required": ["leadRef", "summary"],
            "additionalProperties": false
        }))
    }

    fn origin(&self) -> &str {
        adk_harness::website::BACK_OFFICE_ORIGIN
    }

    fn effect(&self) -> adk_core::ToolEffect {
        adk_core::ToolEffect::NonIdempotent
    }

    async fn execute(
        &self,
        _ctx: Arc<dyn adk_core::ToolContext>,
        args: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let invalid = |message: &str| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "website.handoff.invalid",
                format!("invalid arguments for lead_handoff: {message}"),
            )
        };
        let lead = args["leadRef"].as_str().filter(|r| !r.trim().is_empty());
        let lead = lead.ok_or_else(|| invalid("a leadRef is required"))?;
        let summary: String = args["summary"]
            .as_str()
            .ok_or_else(|| invalid("a summary is required"))?
            .chars()
            .take(HANDOFF_SUMMARY_MAX)
            .collect();
        let score = match &self.leads {
            Some(leads) => {
                let scored = leads.hand_off(&awp_types::LeadRef(lead.to_string())).await?;
                format!(" (score {:.0} of {:.0})", scored.value, scored.threshold)
            }
            None => args["score"]
                .as_f64()
                .map(|score| format!(" (score {score:.0})"))
                .unwrap_or_default(),
        };
        let routed = self
            .router
            .raise(Alarm::new(
                self.router.site,
                Urgency::P2,
                "lead_handoff",
                format!("A warm lead is ready for you{score}: {summary} [lead {lead}]"),
                self.router.clock.now(),
            ))
            .await;
        Ok(json!({ "handedOff": true, "lead": lead, "routed": routed }))
    }
}