shep 0.25.1

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
//! Arguments for the verbs that show you what is running: `flock`, `fold`
//! and `lookout`.
//!
//! None of the three changes anything by itself, and all three answer the
//! same question at different widths: one listing, one fold, or a live
//! screen. The redraw floor the follow and the dashboard share is the one
//! real constant here, and its doc carries the measurement behind it.

/// The floor and the default for `shep flock --follow`'s `--interval`, in
/// seconds.
///
/// One second: `sysinfo` reports no CPU over a window shorter than its own
/// `MINIMUM_CPU_UPDATE_INTERVAL` (200 ms), and a redraw costs the shepherd
/// about 5.6 ms a tick on macOS (`crate::host`). Seconds, not milliseconds,
/// because the operator types it.
pub(crate) const FOLLOW_INTERVAL_FLOOR_SECONDS: u64 = 1;

/// Arguments to `shep flock`.
///
/// A listing is a moment, and this moment drifts: a sheep that started
/// after the list printed, one restarting. `--follow` keeps the moment
/// current.
#[derive(Debug, clap::Args)]
pub struct FlockArgs {
    /// Keep the listing current: redraw it in place until Ctrl+C
    ///
    /// One listing to start, then a fresh one every `--interval` seconds
    /// while the shepherd stays reachable, each one painted over the last.
    /// A summary of the machine rides above the tables. Ctrl+C leaves an
    /// exit of zero, a stopped shepherd leaves the code its refusal
    /// carries: an interrupted follow and a dead shepherd must not read as
    /// the same thing.
    ///
    /// Needs a live shepherd: a saved roll is a single moment, and a
    /// follow's whole reason is the moments after it. Needs a terminal
    /// too, and refuses `--format json`, since neither has anywhere to put
    /// a redraw.
    #[arg(short = 'f', long, action = clap::ArgAction::SetTrue)]
    pub follow: bool,
    /// Seconds between redraws, with `--follow`
    ///
    /// The floor is one second, which is also the default. Below it the
    /// listing costs the shepherd more than it tells the operator, and
    /// `sysinfo` reports no CPU at all over a window that short.
    #[arg(
        short = 'i',
        long,
        default_value_t = FOLLOW_INTERVAL_FLOOR_SECONDS,
        value_name = "SECONDS",
        value_parser = clap::value_parser!(u64).range(FOLLOW_INTERVAL_FLOOR_SECONDS..),
        requires = "follow"
    )]
    pub interval: u64,
}

/// Arguments to `shep fold`.
#[derive(Debug, clap::Args)]
pub struct FoldArgs {
    /// The fold to list
    pub name: String,
}

/// The config pane's `dogs` group: the only tab with a dog's table on it.
///
/// The name [`crate::lookout::pane::ConfigPane::shows_dogs`] compares on, and
/// the one group name this module writes out. The tab list itself is
/// [`shep_core::config::GROUP_ORDER`], and
/// `every_tab_is_a_group_the_pane_draws_and_nothing_else_parses` pins that
/// this one is in it.
const DOG_TAB: &str = "dogs";

/// The name [`LookoutScreen::Catalogue`] is spelled with, in its own
/// `#[command(name)]` and in the tests that check what `lookout` has.
const CATALOGUE_SCREEN: &str = "catalogue";

/// Arguments to `shep lookout`.
///
/// [`LookoutSpec`] is the clap surface: the gate flag, the three positionals,
/// and the one subcommand, with the help an operator reads. [`LookoutArgs`] is
/// that plus the one rule clap has no way to state: a dog's table sits on the
/// `dogs` tab, so a third positional after any other tab is a usage error.
#[derive(Debug)]
pub struct LookoutArgs {
    /// Whether the dashboard's action gate is closed.
    pub read_only: bool,
    /// The sheep to open on, or `None` for the dashboard.
    pub sheep: Option<String>,
    /// The config pane's group to open on, one of
    /// [`shep_core::config::GROUP_ORDER`].
    pub tab: Option<String>,
    /// The dog whose table to open, which [`clap::FromArgMatches::from_arg_matches`]
    /// admits only with [`DOG_TAB`] as its tab.
    pub dog: Option<String>,
    /// Whether lookout opens on the dog catalogue rather than the flock
    /// table, which [`LookoutScreen::Catalogue`] sets and the lookout entry
    /// turns into the `i` key's own message.
    pub catalogue: bool,
}

/// Arguments to `shep lookout catalogue`.
///
/// The gate flag is the subcommand's own, so the verb that names the screen
/// also closes it. A `--read-only` typed before `catalogue` is `lookout`'s, and
/// the word after it is a sheep's name.
#[derive(Debug, clap::Args)]
struct CatalogueSpec {
    /// Close the dashboard's action gate. Actions are permitted by default.
    ///
    /// The same gate `shep lookout --read-only` closes and the same one
    /// `shep kv set lookout.allow_control false` closes: `x` (stop), `R`
    /// (restart) and `L` (reload) each refuse outright with it closed.
    #[arg(short = 'R', long)]
    read_only: bool,
}

/// A screen `shep lookout` opens straight on, ahead of the flock table.
#[derive(Debug, clap::Subcommand)]
enum LookoutScreen {
    /// Open on the dog catalogue.
    ///
    /// The same screen the `i` key opens, reached the same way: lookout sends
    /// itself that keypress before it draws, so `Esc` leaves to the dashboard
    /// and every key the catalogue binds is the key it already binds. A sheep,
    /// tab or dog named `catalogue` is reached with `--`, the way a name beside
    /// any other subcommand is: `shep lookout -- web dogs catalogue`.
    #[command(name = CATALOGUE_SCREEN)]
    Catalogue(CatalogueSpec),
}

/// The clap surface for `shep lookout`.
///
/// `args_conflicts_with_subcommands` is what keeps the three positionals: clap
/// stops looking for a subcommand once it has read a value, so `shep lookout
/// web dogs catalogue` still names a dog. The mirror of that is a name: `shep
/// lookout --read-only catalogue` is a sheep called `catalogue`, gate closed.
/// `disable_help_subcommand` keeps `help` a name in all three slots.
#[derive(Debug, clap::Args)]
#[command(args_conflicts_with_subcommands = true, disable_help_subcommand = true)]
struct LookoutSpec {
    /// Close the dashboard's action gate. Actions are permitted by default.
    ///
    /// With the gate open, `x` (stop), `R` (restart) and `L` (reload) each
    /// arm a confirm instead of acting on the keypress that pressed it;
    /// Enter sends the request, any other key cancels, and an unanswered
    /// confirm expires after ten seconds. Closed, all three refuse outright.
    ///
    /// A guard against a keystroke in a window you were reading, not a
    /// security boundary: lookout runs as you, so anything it could do you can
    /// already do with `shep stop`. Can also be closed with `shep kv set
    /// lookout.allow_control false`.
    #[arg(short = 'R', long)]
    read_only: bool,
    /// Open on one sheep's own screen
    ///
    /// The name is the one `shep describe` takes. A fold, a fold selector or
    /// a `fold/app` selector is not one sheep and is not accepted here.
    /// With no tab, lookout opens that sheep's status page, the screen
    /// Enter opens from the dashboard.
    #[arg(value_name = "SHEEP")]
    sheep: Option<String>,
    /// Open that sheep's config pane on one tab
    ///
    /// The tabs are the ones the pane itself draws, in the order it draws
    /// them. With a tab, lookout opens the config pane `e` opens, already
    /// sitting on it.
    #[arg(
        value_name = "TAB",
        value_parser = clap::builder::PossibleValuesParser::new(
            shep_core::config::GROUP_ORDER.iter().copied()
        )
    )]
    tab: Option<String>,
    /// Open one dog's table, on the dogs tab
    ///
    /// The dog is one this shepherd lists, or one the sheep already carries a
    /// table for. Refused unless the tab before it is `dogs`: a dog's table is
    /// that tab's own, and no other tab has one.
    #[arg(value_name = "DOG")]
    dog: Option<String>,
    /// Open straight on one screen instead of the flock table
    #[command(subcommand)]
    screen: Option<LookoutScreen>,
}

impl clap::Args for LookoutArgs {
    fn augment_args(cmd: clap::Command) -> clap::Command {
        <LookoutSpec as clap::Args>::augment_args(cmd)
    }

    fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
        <LookoutSpec as clap::Args>::augment_args_for_update(cmd)
    }
}

impl clap::FromArgMatches for LookoutArgs {
    fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
        Self::finish(<LookoutSpec as clap::FromArgMatches>::from_arg_matches(
            matches,
        )?)
    }

    fn from_arg_matches_mut(matches: &mut clap::ArgMatches) -> Result<Self, clap::Error> {
        Self::finish(<LookoutSpec as clap::FromArgMatches>::from_arg_matches_mut(
            matches,
        )?)
    }

    fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
        *self = Self::from_arg_matches(matches)?;
        Ok(())
    }

    fn update_from_arg_matches_mut(
        &mut self,
        matches: &mut clap::ArgMatches,
    ) -> Result<(), clap::Error> {
        *self = Self::from_arg_matches_mut(matches)?;
        Ok(())
    }
}

impl LookoutArgs {
    /// Builds the arguments, refusing a dog that follows any tab but
    /// [`DOG_TAB`].
    ///
    /// The one grammar rule clap cannot say, since clap's requirements run
    /// between arguments, never between one value and another's presence. It
    /// runs inside the parse, before any terminal is opened.
    fn finish(spec: LookoutSpec) -> Result<Self, clap::Error> {
        if let (Some(tab), Some(dog)) = (spec.tab.as_deref(), spec.dog.as_ref())
            && tab != DOG_TAB
        {
            return Err(usage_error(format!(
                "{dog} names a dog's table, and {tab} has none: the third positional needs `dogs` as its tab"
            )));
        }
        Ok(Self {
            read_only: spec.read_only
                || matches!(
                    spec.screen,
                    Some(LookoutScreen::Catalogue(ref args)) if args.read_only
                ),
            sheep: spec.sheep,
            tab: spec.tab,
            dog: spec.dog,
            catalogue: matches!(spec.screen, Some(LookoutScreen::Catalogue(_))),
        })
    }
}

/// A usage error carrying `shep lookout`'s own usage line.
///
/// The error is built here rather than left to clap because the rule it
/// reports is checked here. `bin_name` is spelled out for the same reason
/// [`crate::cli::Cli`] spells it out: every rendering of a verb's usage reads
/// `shep <verb>`, whichever binary produced it.
fn usage_error(why: String) -> clap::Error {
    let mut cmd = <LookoutSpec as clap::Args>::augment_args(
        clap::Command::new("lookout").bin_name("shep lookout"),
    );
    clap::Error::raw(clap::error::ErrorKind::ValueValidation, why).format(&mut cmd)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{Cli, Commands};

    /// Pins the three facts `flock`'s own arguments settle: a bare listing
    /// does not follow, the interval defaults to the floor, and an interval
    /// without a follow is a usage error rather than a silent no-op.
    #[test]
    fn flock_follows_only_when_asked_and_defaults_to_a_one_second_interval() {
        use clap::Parser;

        let Commands::Flock(args) = Cli::try_parse_from(["shep", "flock"]).unwrap().command else {
            panic!("expected flock")
        };
        assert!(!args.follow, "a bare listing is still one moment");
        assert_eq!(args.interval, FOLLOW_INTERVAL_FLOOR_SECONDS);

        let Commands::Flock(args) =
            Cli::try_parse_from(["shep", "flock", "--follow", "--interval", "5"])
                .unwrap()
                .command
        else {
            panic!("expected flock")
        };
        assert!(args.follow);
        assert_eq!(args.interval, 5);

        assert!(
            Cli::try_parse_from(["shep", "flock", "--interval", "5"]).is_err(),
            "an interval with nothing to pace is a usage error"
        );
    }

    /// fails if the floor is dropped from `--interval`. Zero would spin the
    /// redraw against the shepherd as fast as the socket answers, and
    /// `sysinfo` reports no CPU at all over a window under 200 ms.
    #[test]
    fn a_zero_interval_is_refused() {
        use clap::Parser;

        assert!(Cli::try_parse_from(["shep", "flock", "--follow", "--interval", "0"]).is_err());
    }

    /// fails if the control gate stops being on by default, or stops being
    /// closeable from the flag.
    #[test]
    fn actions_are_on_unless_read_only_says_otherwise() {
        use clap::Parser;
        let Commands::Lookout(default) = Cli::try_parse_from(["shep", "lookout"]).unwrap().command
        else {
            panic!("lookout parses to its own variant")
        };
        assert!(!default.read_only);

        let Commands::Lookout(flagged) = Cli::try_parse_from(["shep", "lookout", "--read-only"])
            .unwrap()
            .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert!(flagged.read_only);
    }

    /// fails if `--allow-control` starts parsing again: lookout takes no
    /// such flag.
    #[test]
    fn allow_control_no_longer_parses() {
        use clap::Parser;
        assert!(Cli::try_parse_from(["shep", "lookout", "--allow-control"]).is_err());
    }

    /// Each of the four shapes the verb takes, read out of the parse rather
    /// than inferred from a usage line: the dashboard, one sheep's status
    /// page, one tab of its config pane, and one dog's table on the `dogs`
    /// tab.
    #[test]
    fn lookout_takes_up_to_three_positionals() {
        use clap::Parser;

        // The fourth slot is the subcommand: every one of these shapes opens
        // the flock table, and adding `catalogue` to the verb must not have
        // moved any of them.
        let focus = |argv: &[&str]| {
            let Commands::Lookout(args) = Cli::try_parse_from(argv).unwrap().command else {
                panic!("lookout parses to its own variant")
            };
            (args.sheep, args.tab, args.dog, args.catalogue)
        };

        assert_eq!(
            focus(&["shep", "lookout"]),
            (None, None, None, false),
            "bare lookout is still the dashboard"
        );
        assert_eq!(
            focus(&["shep", "lookout", "web"]),
            (Some("web".to_string()), None, None, false)
        );
        assert_eq!(
            focus(&["shep", "lookout", "web", "watch"]),
            (
                Some("web".to_string()),
                Some("watch".to_string()),
                None,
                false
            )
        );
        assert_eq!(
            focus(&["shep", "lookout", "web", "dogs", "jobs"]),
            (
                Some("web".to_string()),
                Some("dogs".to_string()),
                Some("jobs".to_string()),
                false
            )
        );
    }

    /// Every tab clap will name is a group the pane draws, and the list is
    /// `GROUP_ORDER` itself: a tenth group added there reaches this parse
    /// with no edit here, and a name invented here fails it.
    #[test]
    fn every_tab_is_a_group_the_pane_draws_and_nothing_else_parses() {
        use clap::Parser;

        for group in shep_core::config::GROUP_ORDER {
            let Commands::Lookout(args) = Cli::try_parse_from(["shep", "lookout", "web", group])
                .unwrap()
                .command
            else {
                panic!("lookout parses to its own variant")
            };
            assert_eq!(args.tab.as_deref(), Some(*group), "{group}");
        }

        for argv in [
            vec!["shep", "lookout", "web", "processes"],
            vec!["shep", "lookout", "web", "Dogs"],
            vec!["shep", "lookout", "web", ""],
        ] {
            let err = Cli::try_parse_from(&argv).expect_err(&format!("{argv:?}"));
            assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue, "{argv:?}");
            assert!(err.to_string().contains("possible values"), "{err}");
        }
    }

    /// The issue's third acceptance line: `shep lookout web dogs kelpie` still
    /// parses as before, with the sheep, the `dogs` tab and the dog each set,
    /// and the subcommand slot added to `lookout` taking none of the three.
    #[test]
    fn web_dogs_kelpie_parses_with_all_three_slots_set() {
        use clap::Parser;

        let Commands::Lookout(args) =
            Cli::try_parse_from(["shep", "lookout", "web", "dogs", "kelpie"])
                .unwrap()
                .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert_eq!(args.sheep.as_deref(), Some("web"));
        assert_eq!(args.tab.as_deref(), Some("dogs"));
        assert_eq!(args.dog.as_deref(), Some("kelpie"));
        assert!(!args.catalogue, "three positionals are not a screen");
    }

    /// The line this replaced, `shep lookout web config dogs`, was never a
    /// parse: `config` is no group the pane draws, so the tab slot refuses it
    /// before the third positional is read, on `main` and here. Kept as that
    /// same refusal, message included, so the subcommand slot added to
    /// `lookout` cannot be what changed it.
    #[test]
    fn web_config_dogs_is_refused_as_it_always_was() {
        use clap::Parser;

        let err = Cli::try_parse_from(["shep", "lookout", "web", "config", "dogs"])
            .expect_err("config is no tab the pane draws");
        assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue);
        let rendered = err.to_string();
        assert!(rendered.contains("config"), "{rendered}");
        for group in shep_core::config::GROUP_ORDER {
            assert!(rendered.contains(group), "{rendered}");
        }
    }

    /// A dog is a table on the `dogs` tab. On any other tab there is nothing
    /// for the third positional to name, and it is refused by the parse, not
    /// by lookout once the screen is up.
    #[test]
    fn a_third_positional_after_another_tab_is_refused() {
        use clap::Parser;

        for tab in shep_core::config::GROUP_ORDER.iter().copied() {
            let argv = vec!["shep", "lookout", "web", tab, "jobs"];
            let parsed = Cli::try_parse_from(&argv);
            if tab == DOG_TAB {
                assert!(parsed.is_ok(), "{argv:?}");
                continue;
            }
            let err = parsed.expect_err(&format!("{argv:?}"));
            assert_eq!(
                err.kind(),
                clap::error::ErrorKind::ValueValidation,
                "{argv:?}"
            );
            let rendered = err.to_string();
            assert!(rendered.contains("jobs"), "{rendered}");
            assert!(rendered.contains(tab), "{rendered}");
            assert!(rendered.contains("shep lookout"), "{rendered}");
        }
    }

    /// `dash` is lookout's visible alias, so it takes the same three. The
    /// alias is what an operator who already has a habit types.
    #[test]
    fn the_alias_takes_the_same_positionals() {
        use clap::Parser;

        let Commands::Lookout(args) = Cli::try_parse_from(["shep", "dash", "web", "dogs", "jobs"])
            .unwrap()
            .command
        else {
            panic!("dash parses to lookout's variant")
        };
        assert_eq!(args.sheep.as_deref(), Some("web"));
        assert_eq!(args.tab.as_deref(), Some("dogs"));
        assert_eq!(args.dog.as_deref(), Some("jobs"));

        let Commands::Lookout(args) = Cli::try_parse_from(["shep", "dash", "catalogue"])
            .unwrap()
            .command
        else {
            panic!("dash carries the subcommand too")
        };
        assert!(args.catalogue);
    }

    /// The gate flag is the subcommand's own and the subcommand takes no
    /// positional: `shep lookout catalogue` opens the screen with the gate
    /// open, `shep lookout catalogue --read-only` with it closed, and a flag
    /// before the verb changes neither.
    #[test]
    fn the_catalogue_subcommand_takes_the_gate_flag_and_no_positional() {
        use clap::Parser;

        let Commands::Lookout(args) = Cli::try_parse_from(["shep", "lookout", "catalogue"])
            .unwrap()
            .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert!(args.catalogue);
        assert!(!args.read_only);
        assert_eq!(
            (
                args.sheep.as_deref(),
                args.tab.as_deref(),
                args.dog.as_deref()
            ),
            (None, None, None),
            "a sheep named `catalogue` is reached from the dashboard, not from here"
        );

        let Commands::Lookout(args) =
            Cli::try_parse_from(["shep", "lookout", "catalogue", "--read-only"])
                .unwrap()
                .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert!(args.catalogue);
        assert!(args.read_only);
        assert_eq!(args.sheep, None);

        // A flag on the top level sits outside `lookout`'s own parser, so it is
        // not one in front of the subcommand and does not push `catalogue` into
        // the sheep's slot.
        let Commands::Lookout(args) =
            Cli::try_parse_from(["shep", "--host", "amp2", "lookout", "catalogue"])
                .unwrap()
                .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert!(args.catalogue);
        assert_eq!(args.sheep, None);
    }

    /// A sheep, tab or dog named `catalogue` is still a name, in every slot and
    /// with the gate flag in front of it. The subcommand claims the word only
    /// where clap looks for a subcommand, and `--` ends that search the way
    /// `shep dogs -- grant` reaches a dog named `grant`.
    #[test]
    fn a_name_that_reads_like_the_catalogue_still_names_one() {
        use clap::Parser;

        let Commands::Lookout(args) =
            Cli::try_parse_from(["shep", "lookout", "web", "dogs", "catalogue"])
                .unwrap()
                .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert_eq!(args.sheep.as_deref(), Some("web"));
        assert_eq!(args.tab.as_deref(), Some("dogs"));
        assert_eq!(args.dog.as_deref(), Some("catalogue"));
        assert!(
            !args.catalogue,
            "the third positional is a dog, not a screen"
        );

        let Commands::Lookout(args) = Cli::try_parse_from(["shep", "lookout", "--", "catalogue"])
            .unwrap()
            .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert_eq!(args.sheep.as_deref(), Some("catalogue"));
        assert!(!args.catalogue, "`--` is what makes the name a name again");

        // The gate flag in front of the word is `lookout`'s own and moves it
        // nowhere: both spellings opened a sheep called `catalogue` with the
        // gate closed before the subcommand existed, and open it still.
        for argv in [
            vec!["shep", "lookout", "--read-only", "catalogue"],
            vec!["shep", "lookout", "--read-only", "--", "catalogue"],
        ] {
            let Commands::Lookout(args) = Cli::try_parse_from(&argv).unwrap().command else {
                panic!("lookout parses to its own variant")
            };
            assert_eq!(args.sheep.as_deref(), Some("catalogue"), "{argv:?}");
            assert!(args.read_only, "{argv:?}");
            assert!(!args.catalogue, "{argv:?}");
        }
    }

    /// What the parse refuses. The subcommand has no positionals, so a tab or
    /// a dog after `catalogue` is an unknown argument carrying a `shep lookout`
    /// usage line; `catalogue` in the tab slot is not a tab the pane draws; and
    /// `catalogue` as a dog on another tab is the dog-after-tab rule.
    #[test]
    fn a_tab_or_dog_after_the_catalogue_is_a_usage_error() {
        use clap::Parser;

        for argv in [
            vec!["shep", "lookout", "catalogue", "web"],
            vec!["shep", "lookout", "catalogue", "web", "dogs"],
            vec!["shep", "lookout", "catalogue", "web", "dogs", "jobs"],
        ] {
            let err = Cli::try_parse_from(&argv).expect_err(&format!("{argv:?}"));
            assert_eq!(
                err.kind(),
                clap::error::ErrorKind::UnknownArgument,
                "{argv:?}"
            );
            let rendered = err.to_string();
            assert!(rendered.contains("shep lookout"), "{rendered}");
            assert!(rendered.contains(CATALOGUE_SCREEN), "{rendered}");
        }

        let err = Cli::try_parse_from(["shep", "lookout", "web", "catalogue"])
            .expect_err("catalogue is no tab the pane draws");
        assert_eq!(err.kind(), clap::error::ErrorKind::InvalidValue);

        let err = Cli::try_parse_from(["shep", "lookout", "web", "watch", "catalogue"])
            .expect_err("a dog's table is the dogs tab's own");
        assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
    }

    /// `lookout` disables clap's implicit `help` subcommand, because adding a
    /// subcommand to a verb with three positionals would otherwise take
    /// `help` out of all three: a sheep named `help` used to be opened by
    /// `shep lookout help`, and still is.
    #[test]
    fn a_sheep_or_dog_named_help_stays_a_name() {
        use clap::Parser;

        let Commands::Lookout(args) = Cli::try_parse_from(["shep", "lookout", "help"])
            .unwrap()
            .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert_eq!(args.sheep.as_deref(), Some("help"));
        assert!(!args.catalogue);

        let Commands::Lookout(args) =
            Cli::try_parse_from(["shep", "lookout", "web", "dogs", "help"])
                .unwrap()
                .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert_eq!(args.sheep.as_deref(), Some("web"));
        assert_eq!(args.dog.as_deref(), Some("help"));
        assert!(!args.catalogue);
    }

    /// `CATALOGUE_SCREEN` is the name the subcommand declares with its own
    /// `#[command(name)]`, so a rename of one and not the other shows up here.
    /// There is no filter for clap's own `help` subcommand: `lookout` disables
    /// it, so a `help` showing up here is the bug.
    #[test]
    fn the_catalogue_subcommand_is_the_only_one_lookout_has() {
        use clap::CommandFactory;

        let lookout = Cli::command().find_subcommand("lookout").unwrap().clone();
        let names: Vec<&str> = lookout
            .get_subcommands()
            .map(|sub| sub.get_name())
            .collect();
        assert_eq!(names, [CATALOGUE_SCREEN]);
    }

    /// `DOG_TAB` is the one group name this module spells out, so it is the
    /// one that can drift from the pane's own list without a parse test
    /// noticing.
    #[test]
    fn the_dogs_tab_is_one_of_the_groups_the_pane_draws() {
        assert!(
            shep_core::config::GROUP_ORDER.contains(&DOG_TAB),
            "{DOG_TAB} is not a config pane group"
        );
    }

    /// The positionals sit alongside the gate flag and the host flag, which
    /// is where an operator actually types them.
    #[test]
    fn the_positionals_sit_alongside_the_flags() {
        use clap::Parser;

        let Commands::Lookout(args) = Cli::try_parse_from([
            "shep",
            "--host",
            "amp2",
            "lookout",
            "web",
            "dogs",
            "jobs",
            "--read-only",
        ])
        .unwrap()
        .command
        else {
            panic!("lookout parses to its own variant")
        };
        assert!(args.read_only);
        assert_eq!(args.sheep.as_deref(), Some("web"));
        assert_eq!(args.tab.as_deref(), Some("dogs"));
        assert_eq!(args.dog.as_deref(), Some("jobs"));
    }
}