aither-agent 0.26.0

AI agent framework with planning, memory, and tool execution for aither
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
//! Alerts for high machine load.
//!
//! A [`HostLoadMonitor`] reads the host through a [`HostReader`] and turns
//! sustained machine load into events: the load *starts* when it stays
//! above its threshold for the start window, and *ends* when it stays below
//! for the end window, so a brief spike does not flap.
//!
//! Machine load, memory pressure and disk pressure reach the model as state
//! ([`StateSource`](crate::StateSource)): as a request is assembled, and only
//! when a condition's level differs from the one the model last saw, so a
//! condition that rises and settles while the agent is idle says nothing.
//! A final memory warning and a kill are events, each told once.
//!
//! While high load lasts, the monitor also lengthens the terminal's
//! foreground window, because commands slowed by the load would otherwise
//! outlast the normal one and move to the background.
//!
//! The monitor never kills or pauses anything.

mod system;

use crate::disk::{AnyDiskReader, DiskPressure, DiskThresholds, DiskWatch};
use crate::runaway::RunawayGuard;

use std::collections::HashMap;
use std::fmt;
use std::time::Duration;

use aither_sandbox::{ForegroundWait, JobFootprint, MemoryDomain, MemorySize};
use askama::Template;
use async_channel::{Receiver, Sender};
use serde::{Deserialize, Serialize};

use crate::clock::{AnyClock, Instant};

pub use system::{SystemReader, psi_memory_pressure};

/// How hard the host's memory is pressed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum MemoryPressure {
    /// Memory is plentiful.
    Normal,
    /// The host is reclaiming memory and tasks start to stall on it.
    Warning,
    /// The host is thrashing: nothing can make progress without memory.
    Critical,
}

impl fmt::Display for MemoryPressure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Normal => "normal",
            Self::Warning => "warning",
            Self::Critical => "critical",
        })
    }
}

/// How much of the machine's CPU capacity is in demand.
///
/// `1.0` is a machine whose cores are all busy. What exceeds it is platform
/// specific: where the host reports a load average (macOS) it is that load
/// divided by the number of cores, so a queue shows as more than `1.0`;
/// on Linux it is the share of the last ten seconds during which runnable
/// tasks waited for a CPU (PSI `cpu`), and on Windows the share of CPU time
/// not spent idle since the previous reading.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct MachineLoad(pub f64);

impl MachineLoad {
    /// The load as a whole percentage of the machine's capacity.
    #[must_use]
    pub fn percent(self) -> u64 {
        // Truncation is the point: the percentage is for a human to read.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let percent = (self.0 * 100.0).round().max(0.0) as u64;
        percent
    }
}

/// Why a reading could not be taken.
#[derive(Debug, thiserror::Error)]
pub enum ReadError {
    /// The host's source could not be read.
    #[error("reading {what} failed: {source}")]
    Io {
        /// The source that was read.
        what: &'static str,
        /// What the host answered.
        source: std::io::Error,
    },
    /// The host's source answered in a form not understood.
    #[error("{what} answered `{content}`, which is not understood")]
    Malformed {
        /// The source that was read.
        what: &'static str,
        /// What it answered.
        content: String,
    },
    /// The host offers no such source.
    #[error("{what} is not available on this host")]
    Unsupported {
        /// The source that is missing.
        what: &'static str,
    },
    /// The container could not be read.
    #[error(transparent)]
    Container(#[from] aither_sandbox::ContainerProbeError),
}

/// Reads the host's memory pressure and machine load.
///
/// Reads may block; the monitor runs them off the agent loop. A host
/// implements this for the platform it reads; tests inject their own.
pub trait HostReader: Send + 'static {
    /// The host's memory pressure now.
    ///
    /// # Errors
    ///
    /// Fails when the host's source cannot be read.
    fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError>;

    /// The machine's load now.
    ///
    /// # Errors
    ///
    /// Fails when the host's source cannot be read.
    fn machine_load(&mut self) -> Result<MachineLoad, ReadError>;
}

fn log_failed_read(error: &ReadError, what: &str) {
    if matches!(error, ReadError::Unsupported { .. }) {
        tracing::trace!(%error, "{what} is not available on this host");
    } else {
        tracing::warn!(%error, "{what} could not be read");
    }
}

/// A host that offers neither memory pressure nor machine load, such as a
/// Linux kernel built without PSI.
///
/// The monitor over it states nothing about the machine, yet still watches
/// what does not need the host's sources: a container's memory and the free
/// space of a volume.
#[derive(Debug, Clone, Copy, Default)]
pub struct UnwatchedHost;

impl HostReader for UnwatchedHost {
    fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError> {
        Err(ReadError::Unsupported {
            what: "host memory pressure",
        })
    }

    fn machine_load(&mut self) -> Result<MachineLoad, ReadError> {
        Err(ReadError::Unsupported {
            what: "host machine load",
        })
    }
}

/// A type-erased [`HostReader`], what the builders store.
pub struct AnyHostReader(Box<dyn HostReader>);

impl AnyHostReader {
    /// Erases `reader`.
    #[must_use]
    pub fn new(reader: impl HostReader) -> Self {
        Self(Box::new(reader))
    }
}

impl HostReader for AnyHostReader {
    fn memory_pressure(&mut self) -> Result<MemoryPressure, ReadError> {
        self.0.memory_pressure()
    }

    fn machine_load(&mut self) -> Result<MachineLoad, ReadError> {
        self.0.machine_load()
    }
}

impl fmt::Debug for AnyHostReader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("AnyHostReader")
    }
}

/// When the monitor calls a condition high, and how long it must hold.
#[derive(Debug, Clone, PartialEq)]
pub struct HostLoadConfig {
    /// Machine load at or above this is high; see [`MachineLoad`] for what
    /// the platform measures.
    pub load_threshold: MachineLoad,
    /// How long a condition must stay above its threshold to start.
    pub start_after: Duration,
    /// How long a condition must stay below its threshold to end.
    pub end_after: Duration,
    /// How often the host is read.
    pub poll_interval: Duration,
    /// The terminal's foreground window while high machine load lasts.
    pub high_load_foreground_wait: Duration,
}

impl HostLoadConfig {
    /// The defaults for the platform the agent runs on.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            load_threshold: MachineLoad(SystemReader::DEFAULT_LOAD_THRESHOLD),
            start_after: Duration::from_secs(30),
            end_after: Duration::from_secs(60),
            poll_interval: Duration::from_secs(5),
            high_load_foreground_wait: Duration::from_secs(60),
        }
    }

    /// Sets the machine load at which the condition is high.
    #[must_use]
    pub const fn load_threshold(mut self, threshold: MachineLoad) -> Self {
        self.load_threshold = threshold;
        self
    }

    /// Sets how long a condition must stay above its threshold to start.
    #[must_use]
    pub const fn start_after(mut self, window: Duration) -> Self {
        self.start_after = window;
        self
    }

    /// Sets how long a condition must stay below its threshold to end.
    #[must_use]
    pub const fn end_after(mut self, window: Duration) -> Self {
        self.end_after = window;
        self
    }

    /// Sets how often the host is read.
    #[must_use]
    pub const fn poll_interval(mut self, interval: Duration) -> Self {
        self.poll_interval = interval;
        self
    }

    /// Sets the terminal's foreground window while high load lasts.
    #[must_use]
    pub const fn high_load_foreground_wait(mut self, window: Duration) -> Self {
        self.high_load_foreground_wait = window;
        self
    }
}

impl Default for HostLoadConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// A condition starting or ending, as the agent is told.
#[derive(Debug, Clone, PartialEq)]
pub enum HostLoadEvent {
    /// Machine load stayed high for the start window.
    LoadHigh {
        /// The load when the window passed.
        load: MachineLoad,
        /// The terminal's foreground window while the load lasts.
        foreground_wait: Duration,
    },
    /// Machine load stayed below the threshold for the end window.
    LoadEnded {
        /// The load when the window passed.
        load: MachineLoad,
        /// The terminal's foreground window again.
        foreground_wait: Duration,
    },
    /// Memory pressure turned warning in the machine or the container.
    MemoryYellow {
        /// Whose memory it is.
        domain: MemoryDomain,
        /// The agent's running jobs in the domain, the largest first.
        jobs: Vec<JobFootprint>,
    },
    /// Memory pressure turned critical in the machine or the container.
    MemoryRed {
        /// Whose memory it is.
        domain: MemoryDomain,
        /// The agent's running jobs in the domain, the largest first.
        jobs: Vec<JobFootprint>,
    },
    /// A job is killed unless the agent acts within the window.
    MemoryFinalWarning {
        /// Whose memory it is.
        domain: MemoryDomain,
        /// The job that goes.
        job: JobFootprint,
        /// How long the agent has.
        window: Duration,
        /// The domain's memory: the machine's physical memory, or the
        /// container's limit.
        capacity: MemorySize,
    },
    /// Memory pressure fell from critical to warning, or to normal.
    MemoryDroppedBack {
        /// Whose memory it is.
        domain: MemoryDomain,
        /// The level it fell to.
        level: MemoryPressure,
        /// The agent's running jobs in the domain, the largest first.
        jobs: Vec<JobFootprint>,
    },
    /// A job was killed for the memory it held.
    JobKilledForMemory {
        /// Whose memory it is.
        domain: MemoryDomain,
        /// The job's task ID.
        task_id: String,
        /// The script the job ran.
        command: String,
        /// What its processes held.
        footprint: MemorySize,
        /// The domain's memory: the machine's physical memory, or the
        /// container's limit.
        capacity: MemorySize,
    },
    /// The free space of the agent's volume fell to a lower level.
    DiskPressureRose {
        /// The volume.
        volume: String,
        /// The level it reached.
        level: DiskPressure,
        /// The free space.
        free: MemorySize,
    },
    /// The free space of the agent's volume rose to a higher level.
    DiskPressureDroppedBack {
        /// The volume.
        volume: String,
        /// The level it fell to.
        level: DiskPressure,
        /// The free space.
        free: MemorySize,
    },
}

/// The alert text for a host load event.
#[derive(Template)]
#[template(path = "host_load_alert.txt", escape = "none")]
struct HostLoadAlert<'a> {
    event: &'a HostLoadEvent,
}

impl HostLoadEvent {
    /// The event as the agent reads it.
    pub(crate) fn alert_text(&self) -> String {
        HostLoadAlert { event: self }
            .render()
            .expect("host load alert template must render")
    }

    /// The condition this event sets and the level it leaves it at; `None`
    /// for an event that is history rather than a condition: a final
    /// memory warning, or a job killed for memory.
    pub(crate) fn condition(&self) -> Option<(HostCondition, HostLevel)> {
        match self {
            Self::LoadHigh { .. } => Some((HostCondition::Load, HostLevel::Load { high: true })),
            Self::LoadEnded { .. } => Some((HostCondition::Load, HostLevel::Load { high: false })),
            Self::MemoryYellow { domain, .. } => Some((
                HostCondition::Memory(*domain),
                HostLevel::Memory(MemoryPressure::Warning),
            )),
            Self::MemoryRed { domain, .. } => Some((
                HostCondition::Memory(*domain),
                HostLevel::Memory(MemoryPressure::Critical),
            )),
            Self::MemoryDroppedBack { domain, level, .. } => {
                Some((HostCondition::Memory(*domain), HostLevel::Memory(*level)))
            }
            Self::DiskPressureRose { volume, level, .. }
            | Self::DiskPressureDroppedBack { volume, level, .. } => {
                Some((HostCondition::Disk(volume.clone()), HostLevel::Disk(*level)))
            }
            Self::MemoryFinalWarning { .. } | Self::JobKilledForMemory { .. } => None,
        }
    }

    /// The event that tells the model `condition` went from `seen` (what
    /// it last saw; `None` when it assumes the normal level) to `now`,
    /// filled with the readings of `reading`, the latest event of the
    /// condition.
    ///
    /// The words depend on what the model saw, never on the path the
    /// condition took meanwhile: a fall to warning is "dropped back" only
    /// for a model that saw critical.
    pub(crate) fn for_change(
        condition: &HostCondition,
        seen: Option<HostLevel>,
        now: HostLevel,
        reading: &Self,
    ) -> Self {
        match (condition, now) {
            (_, HostLevel::Load { high }) => {
                let (Self::LoadHigh {
                    load,
                    foreground_wait,
                }
                | Self::LoadEnded {
                    load,
                    foreground_wait,
                }) = *reading
                else {
                    unreachable!("a load level comes from a load event")
                };
                if high {
                    Self::LoadHigh {
                        load,
                        foreground_wait,
                    }
                } else {
                    Self::LoadEnded {
                        load,
                        foreground_wait,
                    }
                }
            }
            (HostCondition::Memory(domain), HostLevel::Memory(level)) => {
                let (Self::MemoryYellow { jobs, .. }
                | Self::MemoryRed { jobs, .. }
                | Self::MemoryDroppedBack { jobs, .. }) = reading
                else {
                    unreachable!("a memory level comes from a memory event")
                };
                let domain = *domain;
                let jobs = jobs.clone();
                match level {
                    MemoryPressure::Normal => Self::MemoryDroppedBack {
                        domain,
                        level,
                        jobs,
                    },
                    MemoryPressure::Warning
                        if seen == Some(HostLevel::Memory(MemoryPressure::Critical)) =>
                    {
                        Self::MemoryDroppedBack {
                            domain,
                            level,
                            jobs,
                        }
                    }
                    MemoryPressure::Warning => Self::MemoryYellow { domain, jobs },
                    MemoryPressure::Critical => Self::MemoryRed { domain, jobs },
                }
            }
            (HostCondition::Disk(volume), HostLevel::Disk(level)) => {
                let (Self::DiskPressureRose { free, .. }
                | Self::DiskPressureDroppedBack { free, .. }) = *reading
                else {
                    unreachable!("a disk level comes from a disk event")
                };
                let volume = volume.clone();
                let fell = matches!(seen, Some(HostLevel::Disk(before)) if before > level);
                if fell || level == DiskPressure::Normal {
                    Self::DiskPressureDroppedBack {
                        volume,
                        level,
                        free,
                    }
                } else {
                    Self::DiskPressureRose {
                        volume,
                        level,
                        free,
                    }
                }
            }
            _ => unreachable!("a condition and its level are of one kind"),
        }
    }
}

/// A condition of the host the agent is told about as state: the
/// machine's load, a domain's memory, or a volume's free space.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HostCondition {
    /// The machine's CPU load.
    Load,
    /// The memory of the machine or of the container.
    Memory(MemoryDomain),
    /// The free space of the volume with this name.
    Disk(String),
}

/// How a [`HostCondition`] stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HostLevel {
    /// The load is high or not.
    Load {
        /// Whether the load is high.
        high: bool,
    },
    /// The memory pressure.
    Memory(MemoryPressure),
    /// The disk pressure.
    Disk(DiskPressure),
}

impl HostLevel {
    /// Whether the condition is at its normal level.
    const fn is_normal(self) -> bool {
        matches!(
            self,
            Self::Load { high: false }
                | Self::Memory(MemoryPressure::Normal)
                | Self::Disk(DiskPressure::Normal)
        )
    }
}

/// What the monitor sends: conditions to the state the agent keeps,
/// everything else as events.
#[derive(Debug, Clone)]
pub struct HostLoadSenders {
    conditions: Sender<HostLoadEvent>,
    events: Sender<HostLoadEvent>,
}

impl HostLoadSenders {
    /// Sends `event` to the channel its kind goes through. An event for an
    /// agent that is gone is dropped.
    pub async fn send(&self, event: HostLoadEvent) {
        let channel = if event.condition().is_some() {
            &self.conditions
        } else {
            &self.events
        };
        channel.send(event).await.ok();
    }

    /// Whether the agent is gone.
    fn is_closed(&self) -> bool {
        self.conditions.is_closed() && self.events.is_closed()
    }
}

/// What the agent reads from a monitor.
#[derive(Debug)]
pub struct HostLoadChannels {
    conditions: Receiver<HostLoadEvent>,
    events: Receiver<HostLoadEvent>,
}

impl HostLoadChannels {
    /// Registers the monitor's state and events ahead of every other state
    /// and event source, rendering their alerts with `notices`.
    pub fn register(
        self,
        notices: &crate::AnyNotices,
        states: &mut Vec<crate::context::AnyStateSource>,
        events: &mut Vec<crate::context::AnyEventSource>,
    ) {
        states.insert(
            0,
            crate::context::AnyStateSource::new(HostConditions {
                receiver: self.conditions,
                readings: HashMap::new(),
                notices: notices.clone(),
            }),
        );
        events.insert(
            0,
            crate::context::AnyEventSource::new(HostEvents {
                receiver: self.events,
                notices: notices.clone(),
            }),
        );
    }
}

/// A monitor's channels: what it sends through, and what the agent reads.
pub fn channels() -> (HostLoadSenders, HostLoadChannels) {
    let (conditions, condition_receiver) = async_channel::unbounded();
    let (events, event_receiver) = async_channel::unbounded();
    (
        HostLoadSenders { conditions, events },
        HostLoadChannels {
            conditions: condition_receiver,
            events: event_receiver,
        },
    )
}

/// Host load, memory and disk pressure as state: the model hears of a
/// condition only when its level differs from the one it last saw, in the
/// words for that change.
pub struct HostConditions {
    receiver: Receiver<HostLoadEvent>,
    /// The latest event of each condition: the readings (load, jobs, free
    /// space) the alert quotes. Which words it gets depends on what the
    /// model saw, not on this event.
    readings: HashMap<HostCondition, HostLoadEvent>,
    notices: crate::AnyNotices,
}

impl crate::context::StateSource for HostConditions {
    const ID: &'static str = "host_conditions";
    type Key = HostCondition;
    type Value = HostLevel;

    fn poll(&mut self) -> impl Future<Output = Vec<(HostCondition, HostLevel)>> + Send {
        let mut changed = Vec::new();
        while let Ok(event) = self.receiver.try_recv() {
            let (condition, level) = event
                .condition()
                .expect("the monitor sends only conditions to the state channel");
            changed.push((condition.clone(), level));
            self.readings.insert(condition, event);
        }
        std::future::ready(changed)
    }

    fn is_normal(&self, _: &HostCondition, level: &HostLevel) -> bool {
        level.is_normal()
    }

    fn announce(
        &self,
        change: &crate::context::StateChange<'_, HostCondition, HostLevel>,
    ) -> crate::context::Block {
        let reading = self
            .readings
            .get(change.key())
            .expect("a condition with a level has the event that set it");
        crate::context::Block::new(
            "system-reminder",
            self.notices.host_condition(
                change.key(),
                change.seen().copied(),
                *change.now(),
                reading,
            ),
        )
    }
}

/// The host events that are history: a final memory warning, a job
/// killed for memory. Each reaches the model once.
pub struct HostEvents {
    receiver: Receiver<HostLoadEvent>,
    notices: crate::AnyNotices,
}

impl crate::context::EventSource for HostEvents {
    type Event = HostLoadEvent;

    fn take(&mut self) -> impl Future<Output = Vec<HostLoadEvent>> + Send {
        std::future::ready(std::iter::from_fn(|| self.receiver.try_recv().ok()).collect())
    }

    fn announce(&self, event: &HostLoadEvent) -> crate::context::Block {
        crate::context::Block::new("system-reminder", self.notices.host_load(event))
    }
}

/// One condition's progress towards starting or ending.
#[derive(Debug, Default)]
struct Condition {
    active: bool,
    /// Since when readings have disagreed with the state: above the
    /// threshold while inactive, below it while active.
    contrary_since: Option<Instant>,
}

/// What a reading did to a condition.
#[derive(Debug, PartialEq, Eq)]
enum Transition {
    Started,
    Ended,
}

impl Condition {
    fn observe(
        &mut self,
        now: Instant,
        high: bool,
        start_after: Duration,
        end_after: Duration,
    ) -> Option<Transition> {
        if high == self.active {
            self.contrary_since = None;
            return None;
        }
        let since = *self.contrary_since.get_or_insert(now);
        let window = if self.active { end_after } else { start_after };
        if now.duration_since(since) < window {
            return None;
        }
        self.contrary_since = None;
        self.active = high;
        Some(if high {
            Transition::Started
        } else {
            Transition::Ended
        })
    }
}

/// One reading of the host; a part is missing when its source failed.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HostSample {
    memory: Option<MemoryPressure>,
    load: Option<MachineLoad>,
}

impl HostSample {
    /// A sample of the given readings.
    #[must_use]
    pub const fn new(memory: Option<MemoryPressure>, load: Option<MachineLoad>) -> Self {
        Self { memory, load }
    }
}

/// Watches the host and turns sustained machine load into [`HostLoadEvent`]s.
#[derive(Debug)]
pub struct HostLoadMonitor<R> {
    reader: R,
    config: HostLoadConfig,
    foreground_wait: ForegroundWait,
    load: Condition,
    disk: Option<DiskWatch>,
}

impl<R: HostReader> HostLoadMonitor<R> {
    /// Also watches the free space of the volumes `readers` read, judged by
    /// `thresholds`: the agent hears once of each change of a volume's disk
    /// pressure level, and nothing is ever killed for it. The volumes are
    /// those of the agent's home environment alone; each monitor watches its
    /// own.
    #[must_use]
    pub fn with_disk(
        mut self,
        thresholds: DiskThresholds,
        readers: impl IntoIterator<Item = AnyDiskReader>,
    ) -> Self {
        self.disk = Some(DiskWatch::new(thresholds, readers));
        self
    }

    /// The free space of each watched volume now, in the order they were
    /// given; empty when no disk is watched. A volume that cannot be read is
    /// `None`.
    pub fn read_disks(&self) -> impl Future<Output = Vec<Option<u64>>> + Send + use<R> {
        let readers = self.disk.as_ref().map(DiskWatch::readers);
        async move { crate::disk::read_free_bytes(readers.unwrap_or_default()).await }
    }

    /// Applies readings of the volumes' free space, as [`Self::read_disks`]
    /// returns them; returns the events their changes of level raise.
    pub fn observe_disks(&mut self, free: &[Option<u64>]) -> Vec<HostLoadEvent> {
        self.disk
            .as_mut()
            .map_or_else(Vec::new, |disk| disk.observe(free))
    }

    /// A monitor reading `reader`, lengthening `foreground_wait` while high
    /// load lasts.
    #[must_use]
    pub fn new(reader: R, config: HostLoadConfig, foreground_wait: ForegroundWait) -> Self {
        Self {
            reader,
            config,
            foreground_wait,
            load: Condition::default(),
            disk: None,
        }
    }

    /// Reads the host. A source that fails is logged and left out of the
    /// sample, which leaves its condition as it was.
    ///
    /// A host that has no such source at all ([`UnwatchedHost`]) is not an
    /// error each time it is read; the embedder was told once.
    pub fn read(&mut self) -> HostSample {
        let memory = self
            .reader
            .memory_pressure()
            .inspect_err(|error| log_failed_read(error, "memory pressure"))
            .ok();
        let load = self
            .reader
            .machine_load()
            .inspect_err(|error| log_failed_read(error, "machine load"))
            .ok();
        HostSample { memory, load }
    }

    /// Applies a sample taken at `now`; returns the events it completes.
    ///
    /// Starting high load lengthens the terminal's foreground window, and
    /// ending it restores the normal one.
    pub fn observe(&mut self, now: Instant, sample: HostSample) -> Vec<HostLoadEvent> {
        let config = &self.config;
        let mut events = Vec::new();
        if let Some(load) = sample.load {
            let high = load >= config.load_threshold;
            match self
                .load
                .observe(now, high, config.start_after, config.end_after)
            {
                Some(Transition::Started) => {
                    let window = config.high_load_foreground_wait;
                    self.foreground_wait.extend(window);
                    events.push(HostLoadEvent::LoadHigh {
                        load,
                        foreground_wait: window,
                    });
                }
                Some(Transition::Ended) => {
                    self.foreground_wait.restore();
                    events.push(HostLoadEvent::LoadEnded {
                        load,
                        foreground_wait: self.foreground_wait.normal(),
                    });
                }
                None => {}
            }
        }
        events
    }

    /// Reads and observes the host in one step, as the monitor task does;
    /// the disks are read apart, with [`Self::read_disks`].
    pub fn tick(&mut self, clock: &AnyClock) -> Vec<HostLoadEvent> {
        let sample = self.read();
        self.observe(clock.now(), sample)
    }
}

/// Runs `monitor` on `executor` until the returned channels are dropped.
///
/// The reads run on the blocking pool, so a slow host source never stalls
/// the agent loop or the executor.
///
/// With a `guard`, the same readings also drive the agent's memory guard.
pub fn spawn<R, E>(
    executor: &E,
    monitor: HostLoadMonitor<R>,
    guard: Option<RunawayGuard>,
    clock: AnyClock,
) -> HostLoadChannels
where
    R: HostReader,
    E: executor_core::Executor,
{
    use executor_core::Task;

    let (senders, channels) = channels();
    executor.spawn(run(monitor, guard, clock, senders)).detach();
    channels
}

async fn run<R: HostReader>(
    mut monitor: HostLoadMonitor<R>,
    mut guard: Option<RunawayGuard>,
    clock: AnyClock,
    events: HostLoadSenders,
) {
    let interval = monitor.config.poll_interval;
    while !events.is_closed() {
        let (back, sample) = blocking::unblock(move || {
            let sample = monitor.read();
            (monitor, sample)
        })
        .await;
        monitor = back;
        let now = clock.now();
        let mut raised = monitor.observe(now, sample);
        // The volumes and the jobs are read independently of each other.
        let (disks, guarded) = futures::join!(monitor.read_disks(), async {
            match guard.as_mut() {
                Some(guard) => guard.observe(now, sample.memory).await,
                None => Vec::new(),
            }
        });
        raised.extend(guarded);
        raised.extend(monitor.observe_disks(&disks));
        for event in raised {
            tracing::info!(?event, "host load condition changed");
            events.send(event).await;
        }
        async_io::Timer::after(interval).await;
    }
}

#[cfg(test)]
mod tests;