pitboard-core 0.21.1

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
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
//! `pitboard watch` run by the system's own service manager, a second job beside daily renewal
//! (`schedule::Job::Watch`): a LaunchAgent, a systemd user service, or a task that starts at
//! the person's sign-in.

use crate::context::Context;
use crate::duty::autoswitch::{Policy, Threshold};
use crate::error::{Error, Result};
use crate::permit::Permit;
use crate::schedule::{self, Job, Location};
use crate::usage::Order;
use std::path::PathBuf;

/// What the watch service does at a limit of the account in use. Either way it warms up the
/// accounts `pitboard warm on` turned on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Switching {
    /// It switches Claude Code as this says: once a limit reaches its share, and to the
    /// account its order puts first.
    At(Policy),
    /// It never switches.
    Never,
}

impl Switching {
    /// How it switches, `None` where it never does.
    pub fn policy(self) -> Option<Policy> {
        match self {
            Switching::At(policy) => Some(policy),
            Switching::Never => None,
        }
    }

    /// The five-hour share, `None` where it never switches.
    pub fn at(self) -> Option<Threshold> {
        self.policy().map(|policy| policy.threshold)
    }
}

/// Whether the watch service is installed, and what it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Installed {
    /// Installed, where `location` says. `switching` is what it does at a limit, where its job
    /// says it the way Pitboard writes it.
    Yes {
        location: Location,
        switching: Option<Switching>,
    },
    No,
    /// This machine has no scheduler Pitboard knows how to ask.
    Unsupported,
}

pub(crate) fn status(ctx: &Context) -> Installed {
    match schedule::scheduler(ctx) {
        None => Installed::Unsupported,
        Some(s) if s.installed(ctx, Job::Watch) => Installed::Yes {
            location: s.location(ctx, Job::Watch),
            switching: switching(&s.options(ctx, Job::Watch)),
        },
        Some(_) => Installed::No,
    }
}

/// The Pitboard the installed service runs. `None` where nothing is installed, and where what
/// is there does not name one the way `install` writes it.
pub(crate) fn installed_program(ctx: &Context) -> Option<PathBuf> {
    schedule::scheduler(ctx)?.program(ctx, Job::Watch)
}

// Task Scheduler's word on the task; none from launchd or systemd.
pub(crate) fn task(ctx: &Context) -> Option<crate::host::task::Task> {
    schedule::task(ctx, Job::Watch)
}

/// Install it, doing at a limit what `switching` says, and ask the system to start it now.
/// Returns where it went. A reinstall replaces the one there, which the system starts again.
///
/// Refused with [`Error::ScheduleNotDefaultHome`] where this context is not the default home's
/// ([`schedule::serves`]): it would watch `~/.pitboard`'s accounts while `PITBOARD_HOME` named
/// others. `uninstall` is not refused for it, so the service can always be taken away.
pub(crate) fn install(ctx: &Context, permit: Permit, switching: Switching) -> Result<Location> {
    if !schedule::serves(ctx) {
        return Err(Error::ScheduleNotDefaultHome {
            home: crate::home::dir(ctx),
            default: ctx.default_pitboard_home(),
            job: Job::Watch,
        });
    }
    // A run of the service a reinstall ends is then between changes, never mid-renewal.
    let _quiet = crate::switch::exclusive(ctx, permit)?;
    let location = schedule::put(
        ctx,
        permit,
        Job::Watch,
        &schedule::program(ctx, Job::Watch)?,
        &options(switching),
        &schedule::environment(ctx, schedule::proxy_variables(ctx)),
    )?;
    crate::audit::record(ctx, permit, VERB, "install", "ok");
    Ok(location)
}

/// Stop it and take it away. `false` when there was nothing installed. Its run is ended only
/// while Pitboard's lock is held, so never in the middle of a change.
pub(crate) fn uninstall(ctx: &Context, permit: Permit) -> Result<bool> {
    let watched = ctx.clone().with_pitboard_home(ctx.default_pitboard_home());
    let _quiet = match schedule::scheduler(ctx) {
        Some(s) if s.installed(ctx, Job::Watch) => {
            Some(crate::switch::exclusive(&watched, permit)?)
        }
        _ => None,
    };
    taken_away(ctx, permit)
}

// `uninstall`, for a change that holds Pitboard's lock already.
pub(crate) fn taken_away(ctx: &Context, permit: Permit) -> Result<bool> {
    if !schedule::remove(ctx, permit, Job::Watch)? {
        return Ok(false);
    }
    crate::audit::record(ctx, permit, VERB, "uninstall", "ok");
    Ok(true)
}

const VERB: &str = "watch-service";

// Only departures from the old uniform share and default order need extra arguments, so a
// service that switches as an earlier Pitboard did is written as it wrote it.
fn options(switching: Switching) -> Vec<String> {
    match switching {
        Switching::At(Policy {
            threshold,
            weekly,
            order,
        }) => {
            let mut options = vec!["--at".to_string(), threshold.percent().to_string()];
            if weekly != Some(threshold) {
                options.extend([
                    "--weekly-at".to_string(),
                    weekly.map_or_else(|| "off".to_string(), |at| at.percent().to_string()),
                ]);
            }
            if order != Order::default() {
                options.extend(["--order".to_string(), order.code().to_string()]);
            }
            options
        }
        Switching::Never => vec!["--no-switch".to_string()],
    }
}

fn switching(options: &[String]) -> Option<Switching> {
    let threshold = |percent: &String| percent.parse().ok().and_then(Threshold::new);
    let at = |threshold, weekly, order| {
        Switching::At(Policy {
            threshold,
            weekly,
            order,
        })
    };
    let weekly = |percent: &String| match percent.as_str() {
        "off" => Some(None),
        _ => threshold(percent).map(Some),
    };
    match options {
        [at_flag, percent] if at_flag == "--at" => {
            threshold(percent).map(|threshold| at(threshold, Some(threshold), Order::default()))
        }
        [at_flag, percent, order_flag, order] if at_flag == "--at" && order_flag == "--order" => {
            let threshold = threshold(percent)?;
            Some(at(threshold, Some(threshold), Order::from_code(order)?))
        }
        [at_flag, percent, weekly_flag, week]
            if at_flag == "--at" && weekly_flag == "--weekly-at" =>
        {
            Some(at(threshold(percent)?, weekly(week)?, Order::default()))
        }
        [at_flag, percent, weekly_flag, week, order_flag, order]
            if at_flag == "--at" && weekly_flag == "--weekly-at" && order_flag == "--order" =>
        {
            Some(at(
                threshold(percent)?,
                weekly(week)?,
                Order::from_code(order)?,
            ))
        }
        [never] if never == "--no-switch" => Some(Switching::Never),
        _ => None,
    }
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test sets up its scratch files as a person or a tool would"
)]
mod tests {
    use super::*;
    use crate::host::memory::MemoryHost;
    use std::sync::Arc;

    /// A home of the test's own on a machine whose scheduler asks nobody, with a Pitboard in
    /// it for the service to run.
    struct ServiceHome(tempfile::TempDir, Arc<MemoryHost>);

    impl ServiceHome {
        fn new() -> ServiceHome {
            ServiceHome::on(MemoryHost::new())
        }

        // As Windows schedules, through Task Scheduler as this machine has it, on any system.
        fn scheduling_tasks() -> ServiceHome {
            let machine = ServiceHome::on(MemoryHost::scheduling_tasks(SID));
            let launcher = crate::host::Os::Windows
                .launcher(&machine.program())
                .expect("a launcher's name");
            std::fs::write(launcher, "").expect("a launcher");
            machine
        }

        fn on(host: Arc<MemoryHost>) -> ServiceHome {
            let machine = ServiceHome(tempfile::tempdir().expect("a scratch home"), host);
            std::fs::create_dir_all(machine.program().parent().expect("its folder")).expect("made");
            let program = machine.program();
            for file in crate::host::OS
                .launcher(&program)
                .into_iter()
                .chain([program])
            {
                std::fs::write(file, "").expect("a program");
            }
            std::fs::create_dir_all(machine.ctx(&[]).default_pitboard_home())
                .expect("a Pitboard home");
            machine
        }

        fn program(&self) -> PathBuf {
            self.0.path().join("bin").join("pitboard")
        }

        fn ctx(&self, vars: &[(&str, &str)]) -> Context {
            let home = self.0.path().to_string_lossy().into_owned();
            let env: crate::context::Environment =
                [("HOME", home.as_str()), ("USERPROFILE", home.as_str())]
                    .iter()
                    .chain(vars)
                    .copied()
                    .collect();
            Context::for_command_line(&env)
                .with_memory_stores(Arc::clone(&self.1))
                .with_schedule_program(self.program())
        }

        fn written(&self, ctx: &Context) -> String {
            std::fs::read_to_string(schedule::job_path(ctx, Job::Watch).expect("a scheduler"))
                .expect("the job's file")
        }
    }

    const SID: &str = "S-1-5-21-1004-1005-1006-1001";

    fn at(percent: u8) -> Switching {
        Switching::At(Policy {
            threshold: Threshold::new(percent).expect("a share there can be"),
            weekly: Threshold::new(percent),
            order: Order::MostLeft,
        })
    }

    fn soonest(percent: u8) -> Switching {
        Switching::At(Policy {
            threshold: Threshold::new(percent).expect("a share there can be"),
            weekly: Threshold::new(percent),
            order: Order::ResetsSoonest,
        })
    }

    /// Installed, the service runs `pitboard watch` with its marker and the share it was
    /// installed at, says so, and is recorded; a reinstall replaces it, and it is taken away
    /// once, apart from the renewal schedule.
    #[test]
    fn the_service_runs_watch_at_its_share_until_it_is_taken_away() {
        for machine in [ServiceHome::new(), ServiceHome::scheduling_tasks()] {
            let ctx = machine.ctx(&[]);
            assert_eq!(status(&ctx), Installed::No);

            let location = install(&ctx, Permit::for_a_test(), at(90)).expect("installed");
            assert_eq!(
                status(&ctx),
                Installed::Yes {
                    location: location.clone(),
                    switching: Some(at(90))
                }
            );
            assert_eq!(installed_program(&ctx), Some(machine.program()));
            let written = machine.written(&ctx);
            assert!(
                written.contains("watch --scheduled --at 90")
                    || written.contains(
                        "<string>watch</string>\n    <string>--scheduled</string>\n    \
                         <string>--at</string>\n    <string>90</string>"
                    ),
                "{written}"
            );
            assert_eq!(
                schedule::status(&ctx),
                schedule::Installed::No,
                "the renewal schedule is a job of its own"
            );

            install(&ctx, Permit::for_a_test(), at(80)).expect("installed again");
            assert_eq!(
                status(&ctx),
                Installed::Yes {
                    location,
                    switching: Some(at(80))
                }
            );

            schedule::install(&ctx, Permit::for_a_test()).expect("renewal too");
            assert!(uninstall(&ctx, Permit::for_a_test()).expect("taken away"));
            assert_eq!(status(&ctx), Installed::No);
            assert!(!uninstall(&ctx, Permit::for_a_test()).expect("nothing there"));
            assert!(
                matches!(schedule::status(&ctx), schedule::Installed::Yes { .. }),
                "renewal stays"
            );
            let logged: Vec<(String, String)> = crate::audit::read(&ctx, 10)
                .into_iter()
                .filter(|entry| entry.verb == VERB)
                .map(|entry| (entry.subject, entry.outcome))
                .collect();
            assert_eq!(
                logged,
                [("install", "ok"), ("install", "ok"), ("uninstall", "ok")]
                    .map(|(subject, outcome)| (subject.to_string(), outcome.to_string()))
            );
        }
    }

    /// The service watches the default home's accounts alone, so it is installed only from
    /// there, and taken away from any home.
    #[test]
    fn the_service_is_installed_only_where_pitboard_home_is_the_default_home() {
        let machine = ServiceHome::new();
        let ctx = machine.ctx(&[]);
        let default = ctx.default_pitboard_home();
        let elsewhere = machine.0.path().join("elsewhere");
        let another = ctx.clone().with_pitboard_home(elsewhere.clone());

        let refused = install(&another, Permit::for_a_test(), at(95)).expect_err("refused");
        assert_eq!(refused.code(), "schedule_not_default_home");
        assert_eq!(
            refused.to_string(),
            format!(
                "the watch service watches only the accounts in {}, not those in {}, which \
                 PITBOARD_HOME names. Nothing was installed. To install it for {}, unset \
                 PITBOARD_HOME and install it again.",
                default.display(),
                elsewhere.display(),
                default.display()
            )
        );
        assert_eq!(status(&ctx), Installed::No, "nothing was written");

        install(&ctx, Permit::for_a_test(), at(95)).expect("installed");
        assert!(uninstall(&another, Permit::for_a_test()).expect("taken away from elsewhere"));
        assert_eq!(status(&ctx), Installed::No);
    }

    /// The system starts the service with its own environment, so it is given the installing
    /// Pitboard's proxy variables as the renewal schedule is. A run of it watches the default
    /// home whatever `PITBOARD_HOME` the system hands it, with those variables over its own
    /// where the system hands it none, as Task Scheduler does.
    #[test]
    fn a_run_of_the_service_watches_the_default_home_with_the_proxy_it_was_given() {
        let proxied = [("HTTPS_PROXY", "http://alice:s3cret@proxy.example.com:3128")];
        for machine in [ServiceHome::new(), ServiceHome::scheduling_tasks()] {
            let ctx = machine.ctx(&proxied);
            install(&ctx, Permit::for_a_test(), at(95)).expect("installed");
            let handed = schedule::scheduler(&ctx)
                .expect("a scheduler")
                .environment(&ctx, Job::Watch);
            assert_eq!(
                handed,
                [(
                    "HTTPS_PROXY".to_string(),
                    "http://alice:s3cret@proxy.example.com:3128".to_string()
                )]
            );
            let tasks = matches!(
                schedule::job_path(&ctx, Job::Watch),
                Some(path) if path.starts_with(machine.0.path().join("Tasks"))
            );
            if tasks {
                let definition = machine.written(&ctx);
                assert!(!definition.contains("alice"), "{definition}");
            }

            let started = machine
                .ctx(&[])
                .with_pitboard_home(machine.0.path().join("elsewhere"))
                .started_by_the_watch_service();
            assert_eq!(started.pitboard_home, ctx.default_pitboard_home());
            if tasks {
                assert!(
                    started.proxy.same_way(&ctx.proxy),
                    "the file's, over its own"
                );
            }
            let by_hand = machine.ctx(&[]);
            assert_eq!(
                schedule::for_its_run(&by_hand, Job::Watch).pitboard_home,
                by_hand.pitboard_home,
                "a run by hand watches its own"
            );
        }
    }

    /// A service the system will not start leaves the one before as it was, or nothing.
    #[test]
    fn a_service_the_system_will_not_start_leaves_the_one_before() {
        for machine in [ServiceHome::new(), ServiceHome::scheduling_tasks()] {
            let ctx = machine.ctx(&[]);
            machine.1.refuse_next_start();
            let refused = install(&ctx, Permit::for_a_test(), at(95)).expect_err("refused");
            assert_eq!(refused.code(), "schedule_refused");
            assert_eq!(status(&ctx), Installed::No);

            let location = install(&ctx, Permit::for_a_test(), at(95)).expect("installed");
            machine.1.refuse_next_start();
            install(&ctx, Permit::for_a_test(), at(70)).expect_err("refused");
            assert_eq!(
                status(&ctx),
                Installed::Yes {
                    location,
                    switching: Some(at(95))
                }
            );
        }
    }

    // Ended while a change is under way, the service's run could lose the login it was renewing.
    #[test]
    fn the_services_run_is_ended_only_between_changes() {
        for machine in [ServiceHome::new(), ServiceHome::scheduling_tasks()] {
            let ctx = machine.ctx(&[]);
            install(&ctx, Permit::for_a_test(), at(90)).expect("installed");
            for (reinstalling, before) in [(true, 90), (false, 80)] {
                let changing =
                    crate::switch::exclusive(&ctx, Permit::for_a_test()).expect("a change");
                let asked = ctx.clone();
                let (entered, waits) = std::sync::mpsc::channel();
                let waiting = std::thread::spawn(move || {
                    let told = move || entered.send(()).expect("the test waits");
                    crate::fault::meanwhile("switch.lock_busy", told, || {
                        if reinstalling {
                            install(&asked, Permit::for_a_test(), at(80)).map(|_| true)
                        } else {
                            uninstall(&asked, Permit::for_a_test())
                        }
                    })
                });
                waits.recv().expect("it waits for the change");
                assert!(matches!(
                    status(&ctx),
                    Installed::Yes { switching, .. } if switching == Some(at(before))
                ));
                drop(changing);
                assert!(waiting.join().expect("it ends").expect("done"));
            }
            assert_eq!(status(&ctx), Installed::No);
        }
    }

    /// Where there is no scheduler, installing says what to do instead.
    #[test]
    fn a_machine_with_no_scheduler_says_to_leave_watch_running() {
        let machine = ServiceHome::new();
        machine.1.without_a_scheduler();
        let ctx = machine.ctx(&[]);
        assert_eq!(status(&ctx), Installed::Unsupported);
        let refused = install(&ctx, Permit::for_a_test(), at(95)).expect_err("nowhere");
        assert_eq!(refused.code(), "schedule_unsupported");
        assert!(
            refused
                .to_string()
                .contains("leaving `pitboard watch` running"),
            "{refused}"
        );
        assert_eq!(
            uninstall(&ctx, Permit::for_a_test())
                .expect_err("nowhere")
                .code(),
            "schedule_unsupported"
        );
    }

    /// Installed to switch nothing, the service runs `pitboard watch --no-switch` and says so.
    /// Installed again to switch, or again to switch nothing, it reads back as it was written
    /// last, and a service an earlier Pitboard wrote reads as the share it switches at.
    #[test]
    fn a_service_that_never_switches_runs_watch_with_no_switch_and_reads_back_so() {
        for machine in [ServiceHome::new(), ServiceHome::scheduling_tasks()] {
            let ctx = machine.ctx(&[]);
            let location =
                install(&ctx, Permit::for_a_test(), Switching::Never).expect("installed");
            let installed = |switching| Installed::Yes {
                location: location.clone(),
                switching: Some(switching),
            };
            assert_eq!(status(&ctx), installed(Switching::Never));
            let written = machine.written(&ctx);
            assert!(
                written.contains("watch --scheduled --no-switch")
                    || written.contains(
                        "<string>watch</string>\n    <string>--scheduled</string>\n    \
                         <string>--no-switch</string>"
                    ),
                "{written}"
            );
            assert!(!written.contains("--at"), "{written}");

            install(&ctx, Permit::for_a_test(), at(90)).expect("switching");
            assert_eq!(
                status(&ctx),
                installed(at(90)),
                "as an earlier Pitboard wrote it"
            );
            install(&ctx, Permit::for_a_test(), Switching::Never).expect("not switching");
            assert_eq!(status(&ctx), installed(Switching::Never));
        }
    }

    /// Only what Pitboard writes is read back.
    #[test]
    fn only_what_pitboard_writes_is_read() {
        let given = |words: &[&str]| words.iter().map(|o| (*o).to_string()).collect::<Vec<_>>();
        assert_eq!(switching(&given(&["--at", "90"])), Some(at(90)));
        assert_eq!(
            switching(&given(&["--at", "90", "--order", "resets-soonest"])),
            Some(soonest(90))
        );
        assert_eq!(
            switching(&given(&["--at", "90", "--order", "most-left"])),
            Some(at(90))
        );
        assert_eq!(switching(&given(&["--no-switch"])), Some(Switching::Never));
        for written in [at(90), soonest(90), Switching::Never] {
            assert_eq!(switching(&options(written)), Some(written), "{written:?}");
        }
        assert_eq!(
            options(at(90)),
            given(&["--at", "90"]),
            "written as an earlier Pitboard wrote it"
        );
        for unread in [
            &["--order", "resets-soonest"][..],
            &["--at", "90", "--order", "soon"],
            &["--at", "90", "--order"],
            &["--order", "resets-soonest", "--at", "90"],
            &["--no-switch", "--order", "most-left"],
            &["--at", "100"][..],
            &["--at", "ninety"],
            &["--at"],
            &[],
            &["--at", "90", "--once"],
            &["--no-switch", "--at", "90"],
            &["--at", "90", "--no-switch"],
            &["--no-switch", "--once"],
            &["--no-switch=true"],
        ] {
            assert_eq!(switching(&given(unread)), None, "{unread:?}");
        }
    }

    #[test]
    fn independent_weekly_shares_and_off_read_back_from_each_service() {
        for machine in [ServiceHome::new(), ServiceHome::scheduling_tasks()] {
            let ctx = machine.ctx(&[]);
            for weekly in [Threshold::new(99), None] {
                for order in [Order::MostLeft, Order::ResetsSoonest] {
                    let policy = Policy {
                        threshold: Threshold::new(93).unwrap(),
                        weekly,
                        order,
                    };
                    let switching = Switching::At(policy);
                    let location =
                        install(&ctx, Permit::for_a_test(), switching).expect("installed");
                    assert_eq!(
                        status(&ctx),
                        Installed::Yes {
                            location,
                            switching: Some(switching)
                        }
                    );
                    assert!(machine.written(&ctx).contains("--weekly-at"));
                }
            }
        }
    }

    #[test]
    fn weekly_service_arguments_are_explicit_and_strict() {
        let given = |words: &[&str]| words.iter().map(|o| (*o).to_string()).collect::<Vec<_>>();
        for (weekly, value) in [(Threshold::new(99), "99"), (None, "off")] {
            for order in [Order::MostLeft, Order::ResetsSoonest] {
                let policy = Switching::At(Policy {
                    threshold: Threshold::new(93).unwrap(),
                    weekly,
                    order,
                });
                let mut expected = given(&["--at", "93", "--weekly-at", value]);
                if order != Order::MostLeft {
                    expected.extend(given(&["--order", order.code()]));
                }
                assert_eq!(options(policy), expected);
                assert_eq!(switching(&expected), Some(policy));
            }
        }
        assert_eq!(switching(&given(&["--at", "93"])), Some(at(93)));
        assert_eq!(
            switching(&given(&["--at", "93", "--weekly-at", "93"])),
            Some(at(93))
        );
        for unread in [
            &["--at", "93", "--weekly-at"][..],
            &["--at", "93", "--weekly-at", "100"],
            &["--at", "93", "--weekly-at", "49"],
            &["--at", "93", "--weekly-at", "OFF"],
            &["--at", "93", "--weekly-at", "none"],
            &["--weekly-at", "99"],
            &["--weekly-at", "99", "--at", "93"],
            &["--at", "93", "--weekly-at", "99", "--weekly-at", "off"],
            &["--no-switch", "--weekly-at", "off"],
            &["--at", "93", "--weekly-at", "off", "--once"],
            &["--at", "93", "--weekly-at", "99", "--order", "soon"],
        ] {
            assert_eq!(switching(&given(unread)), None, "{unread:?}");
        }
    }
}