marathon-core 0.1.3

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
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
//! AI-aware mode: keep the Mac awake while AI agents and local models are
//! working, and let it sleep again once they go quiet.
//!
//! It watches activity, not mere presence: a coding agent left open in a
//! terminal, or a model server with nothing to do, does not keep the Mac
//! up. Pure logic over process samples, so it all tests without a Mac.

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

/// What kind of AI tool a process is. They differ in how busy "working"
/// looks: an agent mostly waits on the network and uses little CPU, while
/// a model server works hard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// A coding agent: Claude Code, Codex and the like.
    Agent,
    /// A local model runner: Ollama, llama.cpp, MLX, LM Studio and the like.
    Server,
    /// A desktop app that runs agents (the Claude app, ChatGPT, Cursor).
    /// Its own drawing uses some CPU, so it needs more to count as working.
    App,
}

impl Kind {
    /// Whether it runs models on this Mac ("Local AI"), rather than being
    /// an agent or an app that runs agents ("AI agents").
    pub fn is_local(self) -> bool {
        self == Server
    }
}

/// The tools of one category, by name, for showing which are covered.
pub fn labels(local: bool) -> impl Iterator<Item = &'static str> {
    TOOLS
        .iter()
        .filter(move |t| t.kind.is_local() == local)
        .map(|t| t.label)
}

/// A known AI tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tool {
    /// The name shown to the user.
    pub label: &'static str,
    pub kind: Kind,
    /// Process or script names that identify it: lowercase, any case
    /// matches; an app's name must match exactly, so the Claude app is not
    /// taken for the `claude` command. A name also matches as the start of
    /// a dotted name ("mlx_lm" matches "mlx_lm.server").
    pub names: &'static [&'static str],
}

use Kind::{Agent, App, Server};

/// Every tool AI-aware mode knows. Add a line here to support another.
#[rustfmt::skip]
pub const TOOLS: &[Tool] = &[
    // Coding agents, by command name.
    Tool { label: "Claude Code", kind: Agent, names: &["claude"] },
    Tool { label: "Codex", kind: Agent, names: &["codex"] },
    Tool { label: "Cursor Agent", kind: Agent, names: &["cursor-agent"] },
    Tool { label: "Gemini CLI", kind: Agent, names: &["gemini"] },
    Tool { label: "Grok", kind: Agent, names: &["grok"] },
    Tool { label: "opencode", kind: Agent, names: &["opencode"] },
    Tool { label: "pi", kind: Agent, names: &["pi"] },
    Tool { label: "Aider", kind: Agent, names: &["aider"] },
    Tool { label: "Goose", kind: Agent, names: &["goose"] },
    Tool { label: "Amp", kind: Agent, names: &["amp"] },
    Tool { label: "Crush", kind: Agent, names: &["crush"] },
    Tool { label: "Droid", kind: Agent, names: &["droid"] },
    Tool { label: "Copilot CLI", kind: Agent, names: &["copilot"] },
    Tool { label: "Qwen Code", kind: Agent, names: &["qwen"] },
    // Desktop apps that run agents, by their exact app name.
    Tool { label: "the Claude app", kind: App, names: &["Claude"] },
    Tool { label: "ChatGPT", kind: App, names: &["ChatGPT"] },
    Tool { label: "Cursor", kind: App, names: &["Cursor"] },
    Tool { label: "Windsurf", kind: App, names: &["Windsurf"] },
    // Local model runners.
    Tool { label: "Ollama", kind: Server, names: &["ollama"] },
    Tool { label: "llama.cpp", kind: Server, names: &["llama-server", "llama-cli", "llama-run"] },
    Tool { label: "MLX", kind: Server, names: &["mlx_lm", "mlx-lm", "mlx_vlm", "mlx-serve", "mlx_serve"] },
    Tool { label: "LM Studio", kind: Server, names: &["lm studio", "lms", "lmstudio"] },
    Tool { label: "oMLX", kind: Server, names: &["omlx"] },
    Tool { label: "Nativ", kind: Server, names: &["nativ"] },
    Tool { label: "vLLM", kind: Server, names: &["vllm"] },
    Tool { label: "KoboldCpp", kind: Server, names: &["koboldcpp"] },
    Tool { label: "LocalAI", kind: Server, names: &["local-ai", "localai"] },
    Tool { label: "Jan", kind: Server, names: &["jan"] },
    Tool { label: "Msty", kind: Server, names: &["msty"] },
    Tool { label: "exo", kind: Server, names: &["exo"] },
];

/// Programs that run other programs: for these, the script they run
/// names the tool (`node …/bin/pi`, `python -m mlx_lm.server`).
pub const INTERPRETERS: &[&str] = &[
    "node", "bun", "deno", "python", "python3", "uv", "uvx", "npx", "java",
];

const SOURCE_FILES: &[&str] = &[".js", ".mjs", ".cjs", ".ts", ".py", ".rb", ".sh"];

/// Whether a process name is a bare version number, as when a tool runs
/// from a versioned file (`~/.local/share/claude/versions/2.1.335`); its
/// first argument then names it.
pub fn is_version(name: &str) -> bool {
    name.split('.').count() >= 2
        && name
            .split('.')
            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
}

/// The tool a process is, from its name and, for interpreters, the first
/// few arguments. A process named by a version number goes by its first
/// argument.
pub fn identify(name: &str, args: &[String]) -> Option<&'static Tool> {
    if let Some(app) = TOOLS
        .iter()
        .find(|t| t.kind == App && t.names.contains(&name))
    {
        return Some(app);
    }
    if is_version(name) {
        let first = args.first()?;
        return identify(first.rsplit('/').next().unwrap_or(first), &[]);
    }
    let name = name.to_lowercase();
    let interpreter = INTERPRETERS
        .iter()
        .any(|i| name == *i || name.starts_with(&format!("{i}3.")));
    // An interpreter's script names the tool when it is an installed
    // command (`…/bin/pi`) or a module (`-m mlx_lm.server`), not a source
    // file (`llama.py`, `jan.config.js`), which could be anything.
    let candidates = std::iter::once(name.clone()).chain(
        args.iter()
            .skip(1)
            .filter(|a| !a.starts_with('-'))
            .take(if interpreter { 2 } else { 0 })
            .map(|a| a.rsplit('/').next().unwrap_or(a).to_lowercase())
            .filter(|a| !SOURCE_FILES.iter().any(|ext| a.ends_with(ext))),
    );
    candidates.into_iter().find_map(|c| {
        TOOLS
            .iter()
            .filter(|t| t.kind != App)
            .find(|t| t.names.iter().any(|n| matches(n, &c)))
    })
}

fn matches(name: &str, candidate: &str) -> bool {
    candidate == name
        || candidate
            .strip_prefix(name)
            .is_some_and(|rest| rest.starts_with('.'))
}

/// One running AI tool and the processes whose CPU time counts as its
/// work: itself and everything it started (an agent's builds and tests),
/// except what runs under another AI tool. A desktop app counts only its
/// own process, since its helpers and terminals do much that isn't AI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Seen {
    pub pid: u32,
    pub tool: &'static Tool,
    /// Each process's CPU time so far, including children it has reaped,
    /// so commands that start and finish between samples still count.
    pub procs: Vec<(u32, Duration)>,
}

/// Average CPU use, as a share of one core, that counts as working.
const AGENT_BUSY: f64 = 0.005;
const SERVER_BUSY: f64 = 0.05;
const APP_BUSY: f64 = 0.05;
/// GPU use that counts as a model running, while a model runner also
/// shows some life of its own (so an idle runner doesn't claim a video).
const GPU_BUSY: u8 = 20;
const SERVER_ALIVE: f64 = 0.005;

/// How often to look. Each look reads the process table once: well under
/// a millisecond of CPU.
pub const SAMPLE_EVERY: Duration = Duration::from_secs(15);

/// The quiet period's defaults and limits: minutes with AI idle and the
/// Mac's CPU under a percent of all cores.
pub const QUIET_MINUTES: u32 = 15;
pub const QUIET_MINUTES_MAX: u32 = 1440;
pub const QUIET_CPU_PERCENT: u8 = 10;

/// How AI-aware mode decides the work is over.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Settings {
    /// How long things must stay quiet before the Mac may sleep, so the
    /// gaps while an agent waits on a model's reply don't count as done.
    pub grace: Duration,
    /// While holding, the whole Mac's CPU use (share of all cores) above
    /// this also counts as work and restarts the countdown.
    pub idle_cpu: f64,
    /// Which categories count: AI agents, and local models.
    pub agents: bool,
    pub local: bool,
}

impl Settings {
    fn watches(&self, kind: Kind) -> bool {
        if kind.is_local() {
            self.local
        } else {
            self.agents
        }
    }
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            grace: Duration::from_secs(u64::from(QUIET_MINUTES) * 60),
            idle_cpu: f64::from(QUIET_CPU_PERCENT) / 100.0,
            agents: true,
            local: true,
        }
    }
}

/// The whole Mac's CPU time so far, in ticks: busy and in all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CpuTicks {
    pub busy: u64,
    pub total: u64,
}

/// Turns a series of samples into "is AI working right now".
#[derive(Debug, Default)]
pub struct Watch {
    settings: Settings,
    /// CPU time per process at the last sample, and when that was.
    last: HashMap<u32, Duration>,
    last_at: Option<Duration>,
    last_cpu: Option<CpuTicks>,
    /// When work was last seen, and by which tool.
    busy: Option<(Duration, &'static str)>,
}

impl Watch {
    pub fn new(settings: Settings) -> Self {
        Watch {
            settings,
            ..Watch::default()
        }
    }

    /// Changes the settings, keeping what has been seen so far.
    pub fn set_settings(&mut self, settings: Settings) {
        self.settings = settings;
    }

    /// The whole Mac's CPU use since the last sample, as a share of all
    /// cores.
    pub fn system_share(&self, cpu: CpuTicks) -> Option<f64> {
        let last = self.last_cpu?;
        let total = cpu.total.checked_sub(last.total).filter(|&t| t > 0)?;
        Some(cpu.busy.saturating_sub(last.busy) as f64 / total as f64)
    }

    /// The share of one core `s` used since the last sample, `elapsed`
    /// ago. Each process counts only what it gained, so a child that exits
    /// doesn't cancel out the rest; a process new since then counts from
    /// its next sample.
    pub fn share(&self, s: &Seen, elapsed: Duration) -> f64 {
        if elapsed.is_zero() {
            return 0.0;
        }
        let gained: Duration = s
            .procs
            .iter()
            .filter_map(|(pid, cpu)| self.last.get(pid).map(|was| cpu.saturating_sub(*was)))
            .sum();
        gained.as_secs_f64() / elapsed.as_secs_f64()
    }

    /// Takes a sample: the AI tools running at `now` (a clock that keeps
    /// counting while the Mac sleeps), the GPU use in percent and the
    /// Mac's CPU ticks, if known. Returns which tool is working, if any
    /// worked, or the Mac stayed busy, within the grace period.
    pub fn sample(
        &mut self,
        now: Duration,
        seen: &[Seen],
        gpu: Option<u8>,
        cpu: Option<CpuTicks>,
    ) -> Option<String> {
        // A busy Mac keeps an AI hold going (the agent's build is still
        // compiling), but doesn't start one: a video is not AI.
        let system_busy = cpu
            .and_then(|c| self.system_share(c))
            .is_some_and(|share| share > self.settings.idle_cpu);
        if let (true, Some((_, label))) = (system_busy, self.holding(now)) {
            self.busy = Some((now, label));
        }
        if cpu.is_some() {
            self.last_cpu = cpu;
        }
        if let Some(elapsed) = self.last_at.map(|t| now.saturating_sub(t)) {
            let gpu_busy = gpu.is_some_and(|g| g >= GPU_BUSY);
            // When several work at once, name an agent before a model
            // runner before an app: the most specific answer.
            let working = seen
                .iter()
                .filter(|s| self.settings.watches(s.tool.kind))
                .filter(|s| {
                    let share = self.share(s, elapsed);
                    share
                        >= match s.tool.kind {
                            Agent => AGENT_BUSY,
                            Server if gpu_busy => SERVER_ALIVE,
                            Server => SERVER_BUSY,
                            App => APP_BUSY,
                        }
                })
                .min_by_key(|s| s.tool.kind as u8);
            if let Some(s) = working {
                self.busy = Some((now, s.tool.label));
            }
        }
        self.last = seen.iter().flat_map(|s| s.procs.iter().copied()).collect();
        self.last_at = Some(now);
        self.reason(now)
    }

    /// Whether no sample has been taken yet; the first only sets a
    /// baseline, so the next can come sooner.
    pub fn is_new(&self) -> bool {
        self.last_at.is_none()
    }

    /// When and which tool last worked, if within the grace period.
    fn holding(&self, now: Duration) -> Option<(Duration, &'static str)> {
        self.busy
            .filter(|(at, _)| now.saturating_sub(*at) < self.settings.grace)
    }

    /// Which tool worked within the grace period before `now`, if any.
    pub fn reason(&self, now: Duration) -> Option<String> {
        self.holding(now)
            .map(|(_, label)| format!("{label} is working"))
    }

    /// How long until the Mac may sleep if things stay quiet; `None` when
    /// AI-aware mode is not holding.
    pub fn countdown(&self, now: Duration) -> Option<Duration> {
        let (at, _) = self.holding(now)?;
        Some((at + self.settings.grace).saturating_sub(now))
    }
}

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

    fn args(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn identifies_tools_by_name_or_script() {
        let label = |n: &str, a: &[&str]| identify(n, &args(a)).map(|t| t.label);
        assert_eq!(label("claude", &[]), Some("Claude Code"));
        assert_eq!(label("ollama", &["ollama", "serve"]), Some("Ollama"));
        assert_eq!(label("llama-server", &[]), Some("llama.cpp"));
        assert_eq!(label("LM Studio", &[]), Some("LM Studio"));
        assert_eq!(label("node", &["node", "/opt/homebrew/bin/pi"]), Some("pi"));
        assert_eq!(
            label(
                "Python",
                &["python3", "-m", "mlx_lm.server", "--port", "8080"]
            ),
            Some("MLX")
        );
        assert_eq!(
            label("python3.12", &["python3.12", "-m", "vllm"]),
            Some("vLLM")
        );
        // A non-interpreter's arguments don't count, nor do unknown names.
        assert_eq!(label("vim", &["vim", "claude"]), None);
        assert_eq!(label("node", &["node", "server.js"]), None);
        assert_eq!(label("node", &["node", "jan.config.js"]), None);
        assert_eq!(label("python3", &["python3", "llama.py"]), None);
        assert_eq!(label("claude.exe", &[]), Some("Claude Code"));
        assert_eq!(
            label("2.1.335", &["claude", "--resume"]),
            Some("Claude Code")
        );
        assert_eq!(label("2.1.335", &["/usr/bin/vim"]), None);
        assert_eq!(label("claudette", &[]), None);
        // The Claude app is not the `claude` command.
        assert_eq!(label("Claude", &[]), Some("the Claude app"));
        assert_eq!(label("CLAUDE", &[]), Some("Claude Code"));
    }

    fn tool(label: &str) -> &'static Tool {
        TOOLS.iter().find(|t| t.label == label).unwrap()
    }

    fn seen(pid: u32, label: &str, cpu_ms: u64) -> Seen {
        Seen {
            pid,
            tool: tool(label),
            procs: vec![(pid, Duration::from_millis(cpu_ms))],
        }
    }

    #[test]
    fn a_child_exiting_does_not_hide_work() {
        let ms = Duration::from_millis;
        let tree = |procs: Vec<(u32, Duration)>| Seen {
            pid: 7,
            tool: tool("Claude Code"),
            procs,
        };
        let mut w = Watch::default();
        // The agent, and a build it started.
        w.sample(
            S(0),
            &[tree(vec![(7, ms(10_000)), (8, ms(100_000))])],
            None,
            None,
        );
        // The build exited; the agent itself did 500 ms of work.
        assert!(
            w.sample(S(15), &[tree(vec![(7, ms(10_500))])], None, None)
                .is_some()
        );
    }

    const S: fn(u64) -> Duration = Duration::from_secs;

    #[test]
    fn only_the_chosen_categories_count() {
        let agents_only = Settings {
            local: false,
            ..Settings::default()
        };
        let mut w = Watch::new(agents_only);
        w.sample(S(0), &[seen(1, "Ollama", 0)], None, None);
        // Ollama computing hard, but Local AI is off.
        assert_eq!(
            w.sample(S(15), &[seen(1, "Ollama", 10_000)], None, None),
            None
        );
        w.sample(S(30), &[seen(2, "Claude Code", 0)], None, None);
        assert!(
            w.sample(S(45), &[seen(2, "Claude Code", 500)], None, None)
                .is_some()
        );
    }

    #[test]
    fn every_tool_is_in_one_category() {
        let agents: Vec<_> = labels(false).collect();
        let local: Vec<_> = labels(true).collect();
        assert!(agents.contains(&"Claude Code") && agents.contains(&"Cursor"));
        assert!(local.contains(&"Ollama") && local.contains(&"LM Studio"));
        assert_eq!(agents.len() + local.len(), TOOLS.len());
    }

    #[test]
    fn busy_agent_holds_and_grace_runs_out() {
        let mut w = Watch::default();
        // First sample only sets the baseline.
        assert_eq!(
            w.sample(S(0), &[seen(7, "Claude Code", 1000)], None, None),
            None
        );
        // 300 ms of CPU in 15 s is 2%: working.
        assert_eq!(
            w.sample(S(15), &[seen(7, "Claude Code", 1300)], None, None)
                .as_deref(),
            Some("Claude Code is working")
        );
        // Idle afterwards: still held during the grace period...
        assert!(
            w.sample(S(30), &[seen(7, "Claude Code", 1300)], None, None)
                .is_some()
        );
        let grace = Settings::default().grace;
        assert_eq!(grace, S(15 * 60));
        assert_eq!(w.countdown(S(30)), Some(grace - S(15)));
        assert!(w.reason(S(15) + grace - S(1)).is_some());
        // ...then released.
        assert_eq!(w.reason(S(15) + grace), None);
        assert_eq!(w.countdown(S(15) + grace), None);
    }

    #[test]
    fn open_but_idle_tools_do_not_hold() {
        let mut w = Watch::default();
        let idle = [seen(7, "Claude Code", 1000), seen(9, "Ollama", 5000)];
        w.sample(S(0), &idle, Some(3), None);
        // 30 ms in 15 s is 0.2%: an idle terminal, not work.
        let idle = [seen(7, "Claude Code", 1030), seen(9, "Ollama", 5100)];
        assert_eq!(w.sample(S(15), &idle, Some(3), None), None);
    }

    #[test]
    fn server_needs_real_work_or_a_busy_gpu() {
        let mut w = Watch::default();
        w.sample(S(0), &[seen(9, "Ollama", 0)], None, None);
        // 400 ms in 15 s (2.7%) is not enough for a server...
        assert_eq!(w.sample(S(15), &[seen(9, "Ollama", 400)], None, None), None);
        // ...but a busy GPU while it shows some life (1.3%) is.
        assert_eq!(
            w.sample(S(30), &[seen(9, "Ollama", 600)], Some(85), None)
                .as_deref(),
            Some("Ollama is working")
        );
        // A busy GPU with an idle runner open (a video, a game) is not AI.
        let mut w = Watch::default();
        w.sample(S(0), &[seen(9, "Ollama", 0)], Some(90), None);
        assert_eq!(
            w.sample(S(15), &[seen(9, "Ollama", 10)], Some(90), None),
            None
        );
        // A busy GPU with no model server (a game, a video) is not AI.
        let mut w = Watch::default();
        w.sample(S(0), &[seen(7, "Claude Code", 0)], Some(90), None);
        assert_eq!(
            w.sample(S(15), &[seen(7, "Claude Code", 0)], Some(90), None),
            None
        );
    }

    #[test]
    fn names_the_agent_when_its_app_is_busy_too() {
        let mut w = Watch::default();
        w.sample(
            S(0),
            &[seen(1, "the Claude app", 0), seen(2, "Claude Code", 0)],
            None,
            None,
        );
        let busy = [seen(1, "the Claude app", 5000), seen(2, "Claude Code", 500)];
        assert_eq!(
            w.sample(S(15), &busy, None, None).as_deref(),
            Some("Claude Code is working")
        );
    }

    fn ticks(busy: u64, total: u64) -> Option<CpuTicks> {
        Some(CpuTicks { busy, total })
    }

    #[test]
    fn a_busy_mac_extends_an_ai_hold_but_never_starts_one() {
        let mut w = Watch::new(Settings {
            grace: S(60),
            idle_cpu: 0.10,
            ..Settings::default()
        });
        let quiet = [seen(7, "Claude Code", 0)];
        // The Mac at 50% with no AI at work: no hold.
        w.sample(S(0), &quiet, None, ticks(0, 1000));
        assert_eq!(w.sample(S(15), &quiet, None, ticks(500, 2000)), None);
        // The agent works once...
        assert!(
            w.sample(
                S(30),
                &[seen(7, "Claude Code", 500)],
                None,
                ticks(600, 3000)
            )
            .is_some()
        );
        // ...then its build keeps the Mac at 30% long past the grace period:
        // each busy sample restarts the countdown.
        let mut now = 30;
        let mut t = (600, 3000);
        for _ in 0..10 {
            now += 15;
            t = (t.0 + 300, t.1 + 1000);
            assert!(
                w.sample(
                    S(now),
                    &[seen(7, "Claude Code", 500)],
                    None,
                    ticks(t.0, t.1)
                )
                .is_some()
            );
        }
        // At 10% or less the countdown runs out.
        for _ in 0..4 {
            now += 15;
            t = (t.0 + 100, t.1 + 1000);
            w.sample(
                S(now),
                &[seen(7, "Claude Code", 500)],
                None,
                ticks(t.0, t.1),
            );
        }
        assert_eq!(w.reason(S(now)), None);
    }

    #[test]
    fn new_process_starts_from_its_first_sample() {
        let mut w = Watch::default();
        w.sample(S(0), &[], None, None);
        // Appeared with 10 s of CPU already used: no history, no verdict yet.
        assert_eq!(
            w.sample(S(15), &[seen(3, "Codex", 10_000)], None, None),
            None
        );
        assert!(
            w.sample(S(30), &[seen(3, "Codex", 10_500)], None, None)
                .is_some()
        );
    }
}