marathon-core 0.1.1

Marathon's rules: sessions, timers, triggers and time parsing
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
//! Triggers and schedules: when to keep the Mac awake without being asked,
//! and when to stop to save the battery. Pure logic over a snapshot of the
//! world, so every rule tests without a Mac.

use jiff::civil::{DateTime, Time, Weekday, time};
use serde::{Deserialize, Serialize};

use crate::format_time;

/// The user's triggers. Stored as JSON; every field is optional on disk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "OnDisk")]
pub struct Rules {
    /// Stay awake while any of these apps runs (name or bundle id, any case).
    pub apps: Vec<String>,
    /// Stay awake while on the power adapter.
    pub on_ac_power: bool,
    /// Stay awake while an external display is connected.
    pub external_display: bool,
    /// Stay awake during these hours.
    pub schedule: Option<Schedule>,
    /// On battery, stop everything once the charge falls below this percent.
    pub stop_below_battery: Option<u8>,
    /// Stay awake while AI agents (Claude Code, Codex, Cursor, …) work.
    pub ai_agents: bool,
    /// Stay awake while local models (Ollama, MLX, LM Studio, …) work.
    pub ai_local: bool,
    /// Minutes AI tools and the Mac must stay quiet before it may sleep.
    pub ai_quiet_minutes: u32,
    /// The Mac's CPU use, in percent of all cores, that counts as quiet.
    pub ai_quiet_cpu_percent: u8,
}

/// Days and hours, e.g. weekdays 09:00 to 18:00. An end at or before the
/// start runs past midnight into the next day.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schedule {
    pub days: Vec<Day>,
    pub start: Time,
    pub end: Time,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Day {
    Mon,
    Tue,
    Wed,
    Thu,
    Fri,
    Sat,
    Sun,
}

impl Day {
    pub const ALL: [Day; 7] = [
        Day::Mon,
        Day::Tue,
        Day::Wed,
        Day::Thu,
        Day::Fri,
        Day::Sat,
        Day::Sun,
    ];

    fn of(w: Weekday) -> Day {
        Day::ALL[usize::from(w.to_monday_zero_offset().unsigned_abs())]
    }

    pub fn short(self) -> &'static str {
        ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][self as usize]
    }
}

/// What the sensors report right now.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct World {
    /// Names and bundle ids of running apps.
    pub running_apps: Vec<String>,
    pub on_ac_power: bool,
    /// Battery charge in percent, or `None` without a battery.
    pub battery: Option<u8>,
    pub external_display: bool,
    /// Whether AI-aware mode sees an agent or model at work.
    pub ai_working: bool,
    /// Local wall-clock time.
    pub now: DateTime,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// Triggers want the Mac awake, for these reasons ("Xcode is running"),
    /// in the order the rules are listed. Never empty.
    Hold(Vec<String>),
    /// No trigger applies.
    Idle,
    /// On battery below the threshold: stop everything.
    BatteryLow(u8),
}

impl Rules {
    pub fn evaluate(&self, w: &World) -> Verdict {
        if let (false, Some(pct), Some(min)) = (w.on_ac_power, w.battery, self.stop_below_battery)
            && pct < min
        {
            return Verdict::BatteryLow(pct);
        }
        let mut reasons: Vec<String> = self
            .apps
            .iter()
            .filter(|want| w.running_apps.iter().any(|r| matches_app(want, r)))
            .map(|app| format!("{} is running", app.trim()))
            .collect();
        if self.ai_aware() && w.ai_working {
            // One steady reason, so turning off pauses AI-aware mode as a
            // whole, whichever tool is busy next.
            reasons.push(AI_REASON.into());
        }
        if self.on_ac_power && w.on_ac_power {
            reasons.push("on the power adapter".into());
        }
        if self.external_display && w.external_display {
            reasons.push("an external display is connected".into());
        }
        if let Some(s) = &self.schedule
            && s.contains(w.now)
        {
            reasons.push(format!("scheduled {}", s.describe()));
        }
        if reasons.is_empty() {
            Verdict::Idle
        } else {
            Verdict::Hold(reasons)
        }
    }
}

impl Default for Rules {
    fn default() -> Self {
        Rules {
            apps: Vec::new(),
            on_ac_power: false,
            external_display: false,
            schedule: None,
            stop_below_battery: None,
            ai_agents: false,
            ai_local: false,
            ai_quiet_minutes: crate::ai::QUIET_MINUTES,
            ai_quiet_cpu_percent: crate::ai::QUIET_CPU_PERCENT,
        }
    }
}

/// `Rules` as read from disk. A file from an earlier version may have one
/// `ai_aware` switch for both AI categories.
#[derive(Deserialize)]
#[serde(default)]
struct OnDisk {
    apps: Vec<String>,
    on_ac_power: bool,
    external_display: bool,
    schedule: Option<Schedule>,
    stop_below_battery: Option<u8>,
    ai_agents: bool,
    ai_local: bool,
    ai_aware: Option<bool>,
    ai_quiet_minutes: u32,
    ai_quiet_cpu_percent: u8,
}

impl Default for OnDisk {
    fn default() -> Self {
        let r = Rules::default();
        OnDisk {
            apps: r.apps,
            on_ac_power: r.on_ac_power,
            external_display: r.external_display,
            schedule: r.schedule,
            stop_below_battery: r.stop_below_battery,
            ai_agents: r.ai_agents,
            ai_local: r.ai_local,
            ai_aware: None,
            ai_quiet_minutes: r.ai_quiet_minutes,
            ai_quiet_cpu_percent: r.ai_quiet_cpu_percent,
        }
    }
}

impl From<OnDisk> for Rules {
    fn from(d: OnDisk) -> Rules {
        let both = d.ai_aware == Some(true);
        Rules {
            apps: d.apps,
            on_ac_power: d.on_ac_power,
            external_display: d.external_display,
            schedule: d.schedule,
            stop_below_battery: d.stop_below_battery,
            ai_agents: d.ai_agents || both,
            ai_local: d.ai_local || both,
            ai_quiet_minutes: d.ai_quiet_minutes,
            ai_quiet_cpu_percent: d.ai_quiet_cpu_percent,
        }
    }
}

/// The trigger reason while AI-aware mode holds.
pub const AI_REASON: &str = "AI is working";

impl Rules {
    /// The battery level the Triggers window suggests: low enough that
    /// Marathon only steps in to save the last of the charge.
    pub const SUGGESTED_BATTERY_STOP: u8 = 5;

    /// Whether a running app, by name or bundle id, is one a rule watches.
    pub fn watches_app(&self, running: &str) -> bool {
        self.apps.iter().any(|want| matches_app(want, running))
    }

    /// AI-aware mode's settings.
    pub fn ai_settings(&self) -> crate::ai::Settings {
        crate::ai::Settings {
            grace: std::time::Duration::from_secs(
                u64::from(self.ai_quiet_minutes.clamp(1, crate::ai::QUIET_MINUTES_MAX)) * 60,
            ),
            idle_cpu: f64::from(self.ai_quiet_cpu_percent.clamp(1, 100)) / 100.0,
            agents: self.ai_agents,
            local: self.ai_local,
        }
    }

    /// Whether AI-aware mode watches anything at all.
    pub fn ai_aware(&self) -> bool {
        self.ai_agents || self.ai_local
    }

    /// Whether any rule reads the power source or battery.
    pub fn watches_power(&self) -> bool {
        self.on_ac_power || self.stop_below_battery.is_some()
    }
}

fn matches_app(want: &str, running: &str) -> bool {
    running.eq_ignore_ascii_case(want.trim())
}

impl Schedule {
    /// Weekdays, 09:00 to 18:00.
    pub fn workday() -> Schedule {
        Schedule {
            days: Day::ALL[..5].to_vec(),
            start: time(9, 0, 0, 0),
            end: time(18, 0, 0, 0),
        }
    }

    fn overnight(&self) -> bool {
        self.end <= self.start
    }

    /// Whether `now` falls inside the schedule.
    pub fn contains(&self, now: DateTime) -> bool {
        let t = now.time();
        let today = Day::of(now.weekday());
        let yesterday = Day::of(now.weekday().previous());
        if self.overnight() {
            (self.days.contains(&today) && t >= self.start)
                || (self.days.contains(&yesterday) && t < self.end)
        } else {
            self.days.contains(&today) && t >= self.start && t < self.end
        }
    }

    /// The next local time after `now` at which `contains` may change:
    /// the next start or end time, on any day (a day not chosen just finds
    /// nothing has changed). `None` when no day is chosen.
    pub fn next_edge(&self, now: DateTime) -> Option<DateTime> {
        if self.days.is_empty() {
            return None;
        }
        let today = now.date();
        let tomorrow = today.tomorrow().ok()?;
        [today, tomorrow]
            .into_iter()
            .flat_map(|d| [d.to_datetime(self.start), d.to_datetime(self.end)])
            .filter(|edge| *edge > now)
            .min()
    }

    /// "Mon–Fri 09:00–18:00".
    pub fn describe(&self) -> String {
        let days = match self.days.as_slice() {
            d if d.len() == 7 => "every day".to_string(),
            [Day::Mon, Day::Tue, Day::Wed, Day::Thu, Day::Fri] => "Mon–Fri".to_string(),
            [Day::Sat, Day::Sun] => "weekends".to_string(),
            d => d.iter().map(|d| d.short()).collect::<Vec<_>>().join(", "),
        };
        format!(
            "{days} {}–{}",
            format_time(self.start),
            format_time(self.end)
        )
    }
}

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

    fn dt(s: &str) -> DateTime {
        s.parse().unwrap()
    }

    fn hold(reasons: &[&str]) -> Verdict {
        Verdict::Hold(reasons.iter().map(|r| r.to_string()).collect())
    }

    fn world() -> World {
        World {
            now: dt("2026-12-03T12:00"), // a Thursday
            ..World::default()
        }
    }

    #[test]
    fn no_rules_means_idle() {
        assert_eq!(Rules::default().evaluate(&world()), Verdict::Idle);
    }

    #[test]
    fn app_trigger_matches_name_or_bundle_id_any_case() {
        let rules = Rules {
            apps: vec!["xcode".into(), "com.apple.Keynote".into()],
            ..Rules::default()
        };
        let mut w = world();
        assert_eq!(rules.evaluate(&w), Verdict::Idle);
        w.running_apps = vec!["Xcode".into(), "com.apple.dt.Xcode".into()];
        assert_eq!(rules.evaluate(&w), hold(&["xcode is running"]));
        w.running_apps = vec!["com.apple.keynote".into()];
        assert!(matches!(rules.evaluate(&w), Verdict::Hold(_)));
    }

    #[test]
    fn suggested_battery_stop_is_low() {
        assert_eq!(Rules::SUGGESTED_BATTERY_STOP, 5);
        assert_eq!(Rules::default().stop_below_battery, None);
    }

    #[test]
    fn power_and_display_triggers() {
        let rules = Rules {
            on_ac_power: true,
            external_display: true,
            ..Rules::default()
        };
        let mut w = world();
        assert_eq!(rules.evaluate(&w), Verdict::Idle);
        w.external_display = true;
        assert_eq!(
            rules.evaluate(&w),
            hold(&["an external display is connected"])
        );
        w.on_ac_power = true;
        assert_eq!(
            rules.evaluate(&w),
            hold(&["on the power adapter", "an external display is connected"])
        );
    }

    #[test]
    fn battery_guard_wins_only_on_battery() {
        let rules = Rules {
            external_display: true,
            stop_below_battery: Some(20),
            ..Rules::default()
        };
        let mut w = World {
            external_display: true,
            battery: Some(15),
            ..world()
        };
        assert_eq!(rules.evaluate(&w), Verdict::BatteryLow(15));
        w.on_ac_power = true;
        assert!(matches!(rules.evaluate(&w), Verdict::Hold(_)));
        w.on_ac_power = false;
        w.battery = Some(20);
        assert!(matches!(rules.evaluate(&w), Verdict::Hold(_)));
        w.battery = None;
        assert!(matches!(rules.evaluate(&w), Verdict::Hold(_)));
    }

    #[test]
    fn schedule_hours_and_days() {
        let s = Schedule::workday();
        assert!(s.contains(dt("2026-12-03T09:00"))); // Thu
        assert!(s.contains(dt("2026-12-03T17:59")));
        assert!(!s.contains(dt("2026-12-03T18:00")));
        assert!(!s.contains(dt("2026-12-03T08:59")));
        assert!(!s.contains(dt("2026-12-05T12:00"))); // Sat
        assert_eq!(s.describe(), "Mon–Fri 09:00–18:00");
    }

    #[test]
    fn overnight_schedule_belongs_to_its_start_day() {
        let s = Schedule {
            days: vec![Day::Fri],
            start: "22:00".parse().unwrap(),
            end: "06:00".parse().unwrap(),
        };
        assert!(s.contains(dt("2026-12-04T23:00"))); // Fri night
        assert!(s.contains(dt("2026-12-05T05:59"))); // Sat early
        assert!(!s.contains(dt("2026-12-05T06:00")));
        assert!(!s.contains(dt("2026-12-03T23:00"))); // Thu night
    }

    #[test]
    fn next_edge_finds_the_next_boundary() {
        let s = Schedule::workday();
        assert_eq!(
            s.next_edge(dt("2026-12-03T12:00")),
            Some(dt("2026-12-03T18:00"))
        );
        assert_eq!(
            s.next_edge(dt("2026-12-03T18:00")),
            Some(dt("2026-12-04T09:00"))
        );
        let none = Schedule {
            days: vec![],
            ..Schedule::workday()
        };
        assert_eq!(none.next_edge(dt("2026-12-03T12:00")), None);
    }

    #[test]
    fn rules_json_is_forgiving() {
        let r: Rules = serde_json::from_str(r#"{"apps":["Zoom"]}"#).unwrap();
        assert_eq!(r.apps, vec!["Zoom"]);
        assert!(r.watches_app("zoom") && !r.watches_power());
        assert!(!r.ai_aware());
        // An earlier version's single switch turns on both categories.
        let old: Rules = serde_json::from_str(r#"{"ai_aware":true}"#).unwrap();
        assert!(old.ai_agents && old.ai_local);
        let both = Rules {
            ai_agents: true,
            ai_local: true,
            ..r.clone()
        };
        assert_eq!(both.ai_settings(), crate::ai::Settings::default());
        let full = Rules {
            schedule: Some(Schedule::workday()),
            stop_below_battery: Some(20),
            ..r
        };
        let json = serde_json::to_string(&full).unwrap();
        assert!(
            json.contains(r#""days":["mon","tue","wed","thu","fri"]"#),
            "{json}"
        );
        assert_eq!(serde_json::from_str::<Rules>(&json).unwrap(), full);
    }
}