sugarrush 2026.8.3

A terminal UI for viewing Nightscout CGM (blood glucose sensor) data
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
//! The alarm self-test.
//!
//! `docs/alarm-contract.md` lists eight independent ways a night can pass
//! without a sound. Every one of them was silent — nothing in the app could
//! tell you which, or that any of them applied. "Audible alarm: on" is a claim
//! about a config field, not about whether this machine can make a noise.
//!
//! This walks the whole chain and says what it found, loudly enough to be
//! useful at 11pm the night before you rely on it.

use anyhow::Result;
use chrono::{Local, TimeZone, Timelike};

use crate::config::Config;
use crate::nightscout::Client;
use crate::{now_ms, sound, watch};

/// One line of the report.
enum Check {
    /// Working, with what was observed.
    Ok(String, String),
    /// Not working, with what to do about it.
    Bad(String, String),
    /// Deliberately off, or not applicable. Not a failure, but worth saying —
    /// a channel someone thinks is armed and isn't is the whole problem.
    Off(String, String),
}

impl Check {
    fn render(&self) -> String {
        let (mark, label, detail) = match self {
            Check::Ok(l, d) => ("", l, d),
            Check::Bad(l, d) => ("", l, d),
            Check::Off(l, d) => ("·", l, d),
        };
        format!("{mark} {label:<22} {detail}")
    }
    fn failed(&self) -> bool {
        matches!(self, Check::Bad(..))
    }
}

/// Run every check and print the report. Exits non-zero if any channel that is
/// supposed to work doesn't, so it can be used in a cron or a health check.
pub async fn run(quiet: bool) -> Result<()> {
    let cfg = Config::load()?;
    let (_, mut warnings) = cfg.alerts.resolve_checked(cfg.units);
    let sites = cfg.resolve_sites()?;
    for site in &sites {
        let (_, site_warnings) = site.resolve_alerts(&cfg.alerts, cfg.units);
        warnings.extend(
            site_warnings
                .into_iter()
                .map(|w| format!("{}: {w}", site.name)),
        );
    }
    let profiles: Vec<_> = sites
        .iter()
        .map(|site| {
            (
                site.name.clone(),
                site.resolve_alerts(&cfg.alerts, cfg.units).0,
            )
        })
        .collect();
    let now = now_ms();
    let mut checks: Vec<Check> = Vec::new();

    // 1. Config.
    if warnings.is_empty() {
        checks.push(Check::Ok(
            "config".into(),
            format!("{} site(s), thresholds valid", sites.len()),
        ));
    } else {
        checks.push(Check::Bad("config".into(), warnings.join("; ")));
    }

    // 2. Can we see the data at all? An alarm can only fire on readings that
    //    arrive.
    for site in &sites {
        let site_alerts = site.resolve_alerts(&cfg.alerts, cfg.units).0;
        let label = if sites.len() > 1 {
            format!("site · {}", site.name)
        } else {
            "site".into()
        };
        match Client::for_site(site) {
            Ok(client) => match client.entries_range(now - 3_600_000, now, 12).await {
                Ok(entries) => match entries.first() {
                    Some(e) => {
                        let age = (now - e.date) / 60_000;
                        let detail = format!(
                            "reachable · newest reading {age}m old ({} {})",
                            cfg.units.format(e.sgv),
                            cfg.units.label()
                        );
                        // Older than the staleness threshold means the alarm
                        // would already be reporting a gap.
                        if age > site_alerts.stale_minutes {
                            checks.push(Check::Bad(
                                label,
                                format!("{detail} — already past stale_minutes"),
                            ));
                        } else {
                            checks.push(Check::Ok(label, detail));
                        }
                    }
                    None => checks.push(Check::Bad(
                        label,
                        "reachable, but no readings in the last hour".into(),
                    )),
                },
                Err(e) => checks.push(Check::Bad(label, e.to_string())),
            },
            Err(e) => checks.push(Check::Bad(label, e.to_string())),
        }
    }

    // 3. The audible alarm. This is the one that has to actually make a noise:
    //    a working config field and a working audio path are different claims.
    if !profiles.iter().any(|(_, alerts)| alerts.sound) {
        checks.push(Check::Off(
            "audible alarm".into(),
            "off (sound = false)".into(),
        ));
    } else if quiet {
        checks.push(Check::Off(
            "audible alarm".into(),
            "on — not played (--quiet)".into(),
        ));
    } else {
        match sound::sound_check(sound::Tone::Low) {
            sound::Played::Player(p) => {
                checks.push(Check::Ok("audible alarm".into(), format!("played via {p}")))
            }
            sound::Played::Bell => checks.push(Check::Bad(
                "audible alarm".into(),
                "no audio player worked — fell back to the terminal bell, \
                 which many terminals render silently"
                    .into(),
            )),
            sound::Played::Nothing => checks.push(Check::Bad(
                "audible alarm".into(),
                "couldn't even write the sound file".into(),
            )),
        }
    }

    // 4. Quiet hours — a scheduled, invisible silence.
    for (site, alerts) in &profiles {
        let label = if profiles.len() > 1 {
            format!("quiet hours · {site}")
        } else {
            "quiet hours".into()
        };
        match (alerts.quiet_start, alerts.quiet_end) {
            (Some(start), Some(end)) => {
                let min_of_day = Local
                    .timestamp_millis_opt(now)
                    .single()
                    .map(|d| d.hour() as i32 * 60 + d.minute() as i32)
                    .unwrap_or(0);
                let hhmm = |m: i32| format!("{:02}:{:02}", m / 60, m % 60);
                let window = format!("{}{}", hhmm(start), hhmm(end));
                if alerts.in_quiet_hours(min_of_day) {
                    let detail = if alerts.quiet_urgent_low {
                        format!("active now ({window}) — only urgent lows will sound")
                    } else {
                        format!("active now ({window}) — nothing will sound")
                    };
                    checks.push(Check::Off(label, detail));
                } else {
                    checks.push(Check::Ok(label, format!("set ({window}), not active now")));
                }
            }
            _ => checks.push(Check::Ok(label, "not set".into())),
        }
    }

    // 5. An active snooze someone forgot about.
    match watch::snoozed_until() {
        Some(t) if t > now => {
            let clock = Local
                .timestamp_millis_opt(t)
                .single()
                .map(|d| d.format("%H:%M").to_string())
                .unwrap_or_default();
            checks.push(Check::Off(
                "snooze".into(),
                format!("active until {clock} — run `sugarrush snooze off`"),
            ));
        }
        _ => checks.push(Check::Ok("snooze".into(), "none active".into())),
    }

    // 6. Desktop notifications: the D-Bus call can fail with no daemon running,
    //    and the result used to be discarded.
    if !profiles.iter().any(|(_, alerts)| alerts.desktop) {
        checks.push(Check::Off(
            "desktop notification".into(),
            "off (desktop = false)".into(),
        ));
    } else if quiet {
        checks.push(Check::Off(
            "desktop notification".into(),
            "on — not sent (--quiet)".into(),
        ));
    } else {
        let accepted = crate::notify_text("sugarrush: alarm self-test");
        for (site, alerts) in &profiles {
            if alerts.desktop {
                crate::alertlog::record_delivery(
                    site,
                    None,
                    "desktop-test",
                    if accepted { "accepted" } else { "rejected" },
                    crate::alert::Alert::InRange,
                );
            }
        }
        if accepted {
            checks.push(Check::Ok("desktop notification".into(), "accepted".into()));
        } else {
            checks.push(Check::Bad(
                "desktop notification".into(),
                "the notification daemon rejected it or isn't running".into(),
            ));
        }
    }

    // 6b. The on-screen display: the only desktop channel Do Not Disturb
    //     cannot take away, and therefore worth its own line in the report.
    if !profiles.iter().any(|(_, alerts)| alerts.osd) {
        checks.push(Check::Off(
            "on-screen display".into(),
            "off (osd = false)".into(),
        ));
    } else if quiet {
        checks.push(Check::Off(
            "on-screen display".into(),
            "on — not shown (--quiet)".into(),
        ));
    } else if crate::osd::show(&crate::osd::payload(
        crate::alert::Alert::InRange,
        None,
        crate::units::Units::Mgdl,
        false,
        3,
    )) {
        checks.push(Check::Ok("on-screen display".into(), "shown".into()));
    } else {
        // Not `Bad`: the OSD is Omarchy's, and every other desktop is
        // expected to have no shell to answer. Its absence is only news to
        // someone who turned it on.
        checks.push(Check::Off(
            "on-screen display".into(),
            "no Omarchy shell answered — nothing shown".into(),
        ));
    }

    // 7. The push webhook — the channel that reaches a phone, and the only one
    //    escalation has.
    for (site, alerts) in &profiles {
        let label = if profiles.len() > 1 {
            format!("push webhook · {site}")
        } else {
            "push webhook".into()
        };
        match (&alerts.push_url, alerts.push_enabled) {
            (Some(url), true) if !quiet => {
                let accepted = crate::push(url, "sugarrush: alarm self-test").await;
                crate::alertlog::record_delivery(
                    site,
                    None,
                    "webhook-test",
                    if accepted { "accepted" } else { "rejected" },
                    crate::alert::Alert::InRange,
                );
                if accepted {
                    checks.push(Check::Ok(label, "accepted".into()));
                } else {
                    checks.push(Check::Bad(label, "the POST failed — check push_url".into()));
                }
            }
            (Some(_), true) => {
                checks.push(Check::Off(label, "configured — not sent (--quiet)".into()))
            }
            (Some(_), false) => checks.push(Check::Off(label, "configured but disabled".into())),
            (None, _) => checks.push(Check::Off(label, "not configured".into())),
        }
    }

    // 8. Escalation with nowhere to go — a setting that reads as armed and does
    //    nothing at all.
    for (site, alerts) in &profiles {
        let label = if profiles.len() > 1 {
            format!("escalation · {site}")
        } else {
            "escalation".into()
        };
        if alerts.escalate_minutes > 0 {
            if alerts.push_url.is_some() && alerts.push_enabled {
                checks.push(Check::Ok(
                    label,
                    format!(
                        "after {} min, via the push webhook",
                        alerts.escalate_minutes
                    ),
                ));
            } else {
                checks.push(Check::Bad(
                    label,
                    format!(
                    "set to {} min but the push webhook is its only channel — it will do nothing",
                    alerts.escalate_minutes
                ),
                ));
            }
        } else {
            checks.push(Check::Off(label, "off".into()));
        }
    }

    // 9. Is anything actually watching? Everything above is moot if nothing is
    //    running while you sleep.
    if watch::is_alive(watch::Role::Watch, now) {
        checks.push(Check::Ok("watcher".into(), "running".into()));
    } else {
        checks.push(Check::Bad(
            "watcher".into(),
            "not running — start it with `systemctl --user start sugarrush-watch` \
             (see `sugarrush watch --install-service`)"
                .into(),
        ));
    }

    println!("sugarrush alarm self-test\n");
    for c in &checks {
        println!("{}", c.render());
    }

    let failures = checks.iter().filter(|c| c.failed()).count();
    println!();
    if failures == 0 {
        println!("Everything that is switched on is working.");
        println!("Lines marked · are deliberately off — check they're what you meant.");
        Ok(())
    } else {
        println!("{failures} problem(s) above would keep an alarm from reaching you.");
        std::process::exit(1);
    }
}

/// The classification the self-test would report for a given state, so the
/// tests can exercise the decision without a network or a sound card.
#[cfg(test)]
pub fn escalation_is_inert(alerts: &crate::config::Alerts) -> bool {
    alerts.escalate_minutes > 0 && !(alerts.push_url.is_some() && alerts.push_enabled)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn escalation_without_a_push_url_is_reported_as_inert() {
        let mut a = crate::config::Alerts {
            escalate_minutes: 10,
            push_url: None,
            push_enabled: false,
            ..crate::config::Alerts::default()
        };

        // The exact combination the review flagged: "Escalate after 10 min"
        // sitting next to "Push alerts: not configured", reading as two
        // independent switches when one is the other's only channel.
        assert!(escalation_is_inert(&a));

        a.push_url = Some("http://example.invalid/hook".into());
        assert!(
            escalation_is_inert(&a),
            "a URL that is switched off is still no channel"
        );

        a.push_enabled = true;
        assert!(!escalation_is_inert(&a));

        a.escalate_minutes = 0;
        a.push_url = None;
        a.push_enabled = false;
        assert!(
            !escalation_is_inert(&a),
            "escalation that is off cannot be inert"
        );
    }

    #[test]
    fn a_check_renders_its_state() {
        assert!(Check::Ok("a".into(), "b".into()).render().starts_with(''));
        assert!(Check::Bad("a".into(), "b".into()).render().starts_with(''));
        assert!(Check::Off("a".into(), "b".into()).render().starts_with('·'));
        assert!(Check::Bad("a".into(), "b".into()).failed());
        assert!(!Check::Off("a".into(), "b".into()).failed());
    }
}