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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
//! Parses no argv of its own: [`run`] maps an already-parsed [`Cli`] to the
//! verb's own module, the crate's single largest dispatch.

use std::io::{IsTerminal, Write};

use cli::{AdoptArgs, Cli, Commands, Format, ImportCommand};
use commands::admin;
use commands::bleats;
use commands::dev;
use commands::dial_stdio;
use commands::dogs;
use commands::hosts;
use commands::import;
use commands::kv;
use commands::lifecycle;
use commands::lifecycle::Load;
use commands::lifecycle::toggle::{Toggle, toggle, toggle_on_host};
use commands::logs;
use commands::muster;
use commands::query;
use commands::runtime;
use commands::schema;
use commands::secret;
// aliased: `commands::serve` would collide with the crate-root `serve` module
use commands::attach;
#[cfg(windows)]
use commands::logon_task;
use commands::serve::serve as serve_command;
use commands::shep_toml::{ShepToml, ShepTomlError};
use commands::signal;
#[cfg(unix)]
use commands::startup;
use commands::trigger;
use commands::whisper;
use exit::ExitCode;
use output::Streams;
use shep_client::Client;

use crate::client::{connect_or_spawn_client, load_command, run_daemon_command};
use crate::commands::init;
use crate::config::{resolve_style, style_write_is_overridden};
use crate::home::{
    ensure_home, report_home_refusal, resolve_paths, scaffold_first_run_interpreters,
};
use crate::remote::{HostScope, Link, host_scope, refuse_host};
use crate::version_guard::{VersionGuard, connect_client, flock_command};
use crate::{
    adopted_help, cli, commands, completions, dog, exit, hints, lookout, output, status, style,
    welcome, whistle,
};

/// Parses, resolves `$SHEP_HOME` for the verbs that need it, and dispatches.
///
/// Every command receives an already-connected client. Only `Start` and
/// `Muster` bring a shepherd up, through [`connect_or_spawn_client`].
///
/// `Startup` and `Unstartup` skip the shared `$SHEP_HOME` gate: the unit's
/// home is the target user's, which the gate gets wrong under `sudo`.
pub(crate) async fn run(
    cli: Cli,
    style: style::Presentation,
    resolved_style: (style::StyleLevel, style::StyleSource),
) -> ExitCode {
    let fmt = cli.global.format;
    // First, before the home is resolved or created: a verb that cannot reach
    // the host must leave this machine exactly as it found it.
    if cli.global.host.is_some() && host_scope(&cli.command) == HostScope::LocalOnly {
        return refuse_host(fmt);
    }
    // Resolved once, here: the dispatch below partially moves `cli.command`,
    // so no arm can borrow it to ask this question for itself.
    let guard = VersionGuard::for_command(&cli.command);

    // Before `ensure_home`: the answer is the host's, so a fresh machine must
    // not get a `~/.shep` or a banner out of it. The lookout is the exception:
    // it reads this machine's `lookout.allow_control` gate, so it resolves the
    // home first and takes its host from `Link` below.
    if let Some(dest) = cli.global.host.as_deref()
        && !matches!(cli.command, Commands::Lookout(_))
    {
        return run_on_host(&cli.command, cli.global.quiet, dest, guard, style, fmt).await;
    }

    // `StdoutLock`/`StderrLock` are process-wide, so the locked pair further
    // down is right only for a verb that finishes in milliseconds. A guard
    // held on the main thread for a process lifetime blocks the first record
    // any other thread writes, forever, and wedges that task.
    match cli.command {
        Commands::Completions(ref args) => {
            // Status to stderr: the script on stdout is meant to be sourced,
            // and a status line in it would be executed.
            let paths = resolve_paths(&cli.global).ok();
            if let Some(paths) = paths.as_ref() {
                let shepherd = status::ShepherdStatus::probe(paths).await;
                if std::io::stderr().is_terminal() {
                    let mut err = std::io::stderr();
                    let _ = writeln!(err, "{}", status::one_line(&shepherd));
                }
            }
            // The same tolerant read: a home that resolves nothing names no
            // dogs, and a completion script for the built-in verbs still
            // prints.
            let dogs = paths
                .as_ref()
                .map(adopted_help::adopted_verbs)
                .unwrap_or_default();
            let mut out = std::io::stdout().lock();
            return completions::completions(&mut out, args, &dogs);
        }
        Commands::Daemon(ref args) => {
            // `daemon reload` stops a shepherd and starts one rather than
            // being one. Unlocked handles: a teardown ladder plus a boot
            // takes seconds.
            if let Some(cli::DaemonCmd::Reload) = args.cmd {
                let paths = match resolve_paths(&cli.global) {
                    Ok(paths) => paths,
                    Err(refusal) => return report_home_refusal(fmt, &refusal),
                };
                let mut out = std::io::stdout();
                let mut err = std::io::stderr();
                let mut streams = Streams {
                    out: &mut out,
                    err: &mut err,
                    style,
                    fmt,
                };
                return commands::daemon::reload(&mut streams, &paths, guard).await;
            }
            return run_daemon_command(fmt, &cli.global, args).await;
        }
        // A named home goes through the shared gate: refused if missing,
        // never created. With none, the startup module resolves the target
        // user's `<passwd home>/.shep`; `ensure_home` would read this
        // process's `$HOME`, which `sudo` sets to root's.
        Commands::Startup(ref args) => {
            #[cfg(unix)]
            let named_home = if cli.global.home.is_some() {
                match ensure_home(&cli.global) {
                    Ok((paths, _)) => Some(paths.home),
                    Err(refusal) => return report_home_refusal(fmt, &refusal),
                }
            } else {
                None
            };
            // The task carries a home either way, so it is resolved and
            // created like any other verb's, with the interpreter scaffold a
            // fresh home is owed. No welcome banner, as `dial-stdio
            // --autostart` has none.
            #[cfg(windows)]
            let home = match ensure_home(&cli.global) {
                Ok((paths, home_is_new)) => {
                    if home_is_new {
                        scaffold_first_run_interpreters(&paths);
                    }
                    paths.home
                }
                Err(refusal) => return report_home_refusal(fmt, &refusal),
            };
            let mut out = std::io::stdout().lock();
            let mut err = std::io::stderr().lock();
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style,
                fmt,
            };
            #[cfg(unix)]
            return startup::startup(&mut streams, named_home.as_deref(), args);
            #[cfg(windows)]
            return logon_task::install::startup(&mut streams, &home, args);
        }
        Commands::Unstartup(ref args) => {
            let mut out = std::io::stdout().lock();
            let mut err = std::io::stderr().lock();
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style,
                fmt,
            };
            #[cfg(unix)]
            return startup::unstartup(&mut streams, args);
            #[cfg(windows)]
            return logon_task::install::unstartup(&mut streams, args);
        }
        // Resolves the home but never creates it: a probe against a machine
        // with no shep home must leave nothing behind and print no welcome.
        // `--autostart` creates it like a local `start`, minus the scaffold
        // and welcome, since stderr crosses ssh to the operator's terminal.
        Commands::DialStdio(ref args) => {
            let resolved = if args.autostart {
                ensure_home(&cli.global).map(|(paths, _)| paths)
            } else {
                resolve_paths(&cli.global)
            };
            let paths = match resolved {
                Ok(paths) => paths,
                Err(refusal) => return report_home_refusal(fmt, &refusal),
            };
            match dial_stdio::dial_stdio(fmt, &paths, args.autostart).await {}
        }
        // Needs no `$SHEP_HOME` at all, like `Completions` above.
        Commands::Schema => {
            let mut out = std::io::stdout().lock();
            let mut err = std::io::stderr().lock();
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style,
                fmt,
            };
            return schema::schema(&mut streams);
        }
        _ => {}
    }

    // Ahead of `resolve_paths`: `dev` computes its own `$SHEP_DEV_HOME`-rooted
    // paths, so the gate would refuse `shep dev` in a `$HOME`-less environment
    // for a reason the verb does not have. Unlocked handles: this runs until
    // the flock empties or a signal ends it.
    if let Commands::Dev(ref args) = cli.command {
        let mut out = std::io::stdout();
        let mut err = std::io::stderr();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style,
            fmt,
        };
        return dev::dev(
            &mut streams,
            cli.global.quiet,
            cli.global.home.is_some(),
            args,
        )
        .await;
    }

    let (paths, home_is_new) = match ensure_home(&cli.global) {
        Ok(resolved) => resolved,
        Err(refusal) => return report_home_refusal(fmt, &refusal),
    };
    if home_is_new {
        // Unconditional, unlike the welcome banner below: `shep welcome`
        // creates a fresh home too, and the scaffold that makes `shep start
        // server.js` work is owed there as well.
        scaffold_first_run_interpreters(&paths);
    }
    // `Welcome` is excluded: its own arm prints the same text to stdout a
    // moment later, and it should print once.
    if home_is_new && !matches!(cli.command, Commands::Welcome) {
        let mut err = std::io::stderr();
        let mut sink = std::io::sink();
        let mut streams = Streams {
            out: &mut sink,
            err: &mut err,
            style,
            fmt,
        };
        welcome::on_first_run(&mut streams, &paths.home, std::io::stderr().is_terminal());
    }

    // Local for every verb but the ones `host_scope` says reach a host.
    let link = Link::new(&paths, cli.global.host.as_deref());

    // `dog` is a re-exec target like `daemon`, long-lived until signalled,
    // and writes straight to stderr rather than through a `Streams` envelope.
    if let Commands::Dog(ref args) = cli.command {
        return dog::run_dog(&args.name, paths).await;
    }

    // Split out of the dispatch below only to keep its handles unlocked; the
    // `unreachable!` at the bottom of that dispatch keeps the two in step.
    if let Commands::Bleats(ref args) = cli.command {
        let mut out = std::io::stdout();
        let mut err = std::io::stderr();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style,
            fmt,
        };
        return with_client(&mut streams, &link, guard, async |client, streams| {
            bleats::bleats(client, streams, cli.global.quiet, args).await
        })
        .await;
    }

    // Not in the locked block below: a session runs until the operator
    // detaches, and a lock held that long wedges the panic hook and any other
    // thread's write.
    if let Commands::Attach(ref args) = cli.command {
        let mut out = std::io::stdout();
        let mut err = std::io::stderr();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style,
            fmt,
        };
        if let Some(code) = attach::unsupported(&mut streams) {
            return code;
        }
        return with_client(&mut streams, &link, guard, async |client, streams| {
            attach::attach(client, streams, args).await
        })
        .await;
    }

    // Not in the locked block below: this runs until the operator quits, and
    // owns stdout directly through the terminal.
    if let Commands::Lookout(ref args) = cli.command {
        let mut out = std::io::stdout();
        let mut err = std::io::stderr();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style,
            fmt,
        };
        return lookout::lookout(&mut streams, &link, &paths, args, resolved_style).await;
    }

    // Not in the locked block below: `--foreground` runs until signalled, and
    // the quick registering half shares this function so the two flags cannot
    // validate differently.
    if let Commands::Serve(ref args) = cli.command {
        let mut out = std::io::stdout();
        let mut err = std::io::stderr();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style,
            fmt,
        };
        return serve_command(&mut streams, &paths, args).await;
    }

    // Not in the locked block below: this runs until the flock empties, and
    // the supervisor's logging boots in this same process, so an off-thread
    // write would be the first thing a guard wedged.
    if let Commands::Runtime(ref args) = cli.command {
        let mut out = std::io::stdout();
        let mut err = std::io::stderr();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style,
            fmt,
        };
        return runtime::runtime(&mut streams, cli.global.quiet, paths, args).await;
    }

    // No `Streams` at all: this verb owns stdout as a wire, everything written
    // there is MCP, and an `output::emit` would corrupt the peer's parse.
    if let Commands::Whistle = cli.command {
        let mut err = std::io::stderr();
        return whistle::whistle(&mut err, fmt, &paths).await;
    }

    let mut out = std::io::stdout().lock();
    let mut err = std::io::stderr().lock();
    let mut streams = Streams {
        out: &mut out,
        err: &mut err,
        style,
        fmt,
    };

    match cli.command {
        // No client: the welcome is local text about a local directory, and
        // asking a shepherd would fail on the fresh machine it greets.
        Commands::Welcome => {
            let shepherd = status::ShepherdStatus::probe(&paths).await;
            let code = welcome::welcome(&mut streams, &paths.home);
            // After the text: the status is the one line that changes between
            // runs.
            if fmt == Format::Table && std::io::stderr().is_terminal() {
                let _ = writeln!(streams.err, "{}", status::one_line(&shepherd));
            }
            code
        }
        Commands::Style(args) => match args.level {
            // Re-resolves rather than reading the `style` parameter, which
            // the hard rule may have forced to `Bare`: this report's job is
            // saying what is configured.
            None => {
                let (level, source) = resolve_style(&cli.global);
                let message = format!("{level} (from {source})");
                streams.note("style", &message);
                ExitCode::Success
            }
            // A level turns this from a report into a write. Config first,
            // report second, so a report cannot claim a write that failed.
            Some(level) => {
                // `try_edit`, not `edit`: `set_style_level` can refuse, and
                // `edit` saves after its closure whatever it returned, which
                // would rewrite a file this call reports as untouched.
                // `result_large_err` as in `commands::shep_toml`.
                #[cfg_attr(windows, allow(clippy::result_large_err))]
                if let Err(err) =
                    ShepToml::try_edit(&paths.daemon_config, |cfg| cfg.set_style_level(level))
                {
                    let code = match err {
                        ShepTomlError::Io { .. } => ExitCode::Failure,
                        ShepTomlError::Parse { .. }
                        | ShepTomlError::WrongShape { .. }
                        | ShepTomlError::NoDogEntry { .. }
                        | ShepTomlError::BadGrants { .. } => ExitCode::InvalidConfig,
                    };
                    return streams.fail(code, &err.to_string());
                }
                // Re-resolves, so the operator is told whether the value just
                // written will run or whether `--style`/`$SHEP_STYLE` still
                // outranks the `shep.toml` this call edited.
                let (effective, source) = resolve_style(&cli.global);
                let path = paths.daemon_config.display();
                let message = if style_write_is_overridden(source) {
                    format!(
                        "wrote {level} to {path}, but {source} still governs; \
                         shep runs at {effective}"
                    )
                } else {
                    format!("wrote {level} to {path}")
                };
                streams.note("style", &message);
                ExitCode::Success
            }
        },
        // Reads and writes `hints.json` and the cached index: no shepherd.
        Commands::Hints(ref args) => {
            hints::run(&mut streams, &paths, &crate::dog_index::index_url(), args)
        }
        Commands::Start(ref args) => {
            load_command(&mut streams, &link, guard, args, Load::Start).await
        }
        Commands::Add(ref args) => load_command(&mut streams, &link, guard, args, Load::Add).await,
        Commands::Stop(ref args) | Commands::Thatlldo(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                lifecycle::stop(client, streams, args).await
            })
            .await
        }
        Commands::Restart(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                lifecycle::restart(client, streams, Some(&paths), args).await
            })
            .await
        }
        Commands::Reset(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                lifecycle::reset(client, streams, args).await
            })
            .await
        }
        Commands::Reload(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                lifecycle::reload(client, streams, args).await
            })
            .await
        }
        // Not `connect_client` at this arm: `delete` removes a dog from
        // `shep.toml` too, and that half works with no shepherd running.
        Commands::Delete(ref args) => lifecycle::delete(&mut streams, &link, guard, args).await,
        Commands::Stock(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                lifecycle::stock(client, streams, args).await
            })
            .await
        }
        Commands::Trigger(ref args) if args.action.is_none() => {
            trigger::list_actions(&mut streams, &paths, &args.selector)
        }
        Commands::Trigger(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                trigger::trigger(client, streams, args).await
            })
            .await
        }
        Commands::Signal(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                signal::signal(client, streams, args).await
            })
            .await
        }
        Commands::Whisper(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                whisper::whisper(client, streams, args).await
            })
            .await
        }
        // Falls back to the muster roll rather than refusing: looking at the
        // flock must not be a dead end on a machine that just rebooted.
        Commands::Flock(ref args) => {
            let code = flock_command(&mut streams, &link, guard, args).await;
            if code == ExitCode::Success {
                hints::print_under_flock(
                    &mut streams,
                    &paths,
                    cli.global.quiet,
                    args.follow,
                    std::io::stdout().is_terminal(),
                )
                .await;
            }
            code
        }
        // `grant` and `revoke` write `shep.toml` and tell a shepherd only if
        // one is running: tightening a dog must work with none, and never
        // autostarts one. The guard arm is what makes `--available` work with
        // no shepherd running: it never reaches `connect_client`.
        Commands::Dogs(ref args) => match (&args.command, args.available) {
            (Some(cli::DogsCommand::Grant(grant)), _) => {
                dogs::change(
                    &mut streams,
                    &paths,
                    dogs::Change::Grant,
                    &grant.name,
                    &grant.permission,
                )
                .await
            }
            (Some(cli::DogsCommand::Revoke(revoke)), _) => {
                dogs::change(
                    &mut streams,
                    &paths,
                    dogs::Change::Revoke,
                    &revoke.name,
                    &revoke.permission,
                )
                .await
            }
            (None, true) => query::available_dogs(&mut streams, &paths, args).await,
            (None, false) => {
                with_client(&mut streams, &link, guard, async |client, streams| {
                    query::dogs(client, streams, &paths, args).await
                })
                .await
            }
        },
        // None of the four goes through the connect helpers: all four must
        // write the config with no shepherd running, so each connects
        // internally. `--exec` is the hidden pm2 spelling of `adopt`, mapped
        // here so `commands::dogs::enable` keeps its `&str` signature.
        Commands::Enable(ref args) => match &args.exec {
            Some(path) => {
                dogs::adopt(
                    &mut streams,
                    &paths,
                    &AdoptArgs {
                        path: path.clone(),
                        name: Some(args.name.clone()),
                        yes: args.yes,
                    },
                )
                .await
            }
            None => toggle(&mut streams, &paths, Toggle::Enable, &args.name, args.yes).await,
        },
        Commands::Disable(ref args) => {
            toggle(&mut streams, &paths, Toggle::Disable, &args.name, false).await
        }
        Commands::Adopt(ref args) => dogs::adopt(&mut streams, &paths, args).await,
        Commands::Install(ref args) => dogs::install(&mut streams, &paths, args).await,
        Commands::Upgrade(ref args) => dogs::upgrade(&mut streams, &paths, args).await,
        Commands::Rehome(ref args) => dogs::rehome(&mut streams, &paths, &args.name).await,
        Commands::Describe(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                query::describe(client, streams, &link, args).await
            })
            .await
        }
        Commands::Fold(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                query::fold(client, streams, args).await
            })
            .await
        }
        // Not `connect_client`: a verb reporting whether a shepherd answers
        // must not fail because the answer is "no". The exit code is still
        // `DaemonUnreachable`, so `shep ping && echo up` works.
        Commands::Ping => {
            let status = status::ShepherdStatus::probe(&paths).await;
            status::render_ping(&mut streams, &status)
        }
        // `connect_client`, not `connect_or_spawn_client`: autostarting a
        // daemon to save its empty flock would overwrite a good roll.
        Commands::Save => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                muster::save(client, streams).await
            })
            .await
        }
        Commands::Muster => match connect_or_spawn_client(&mut streams, &paths, guard).await {
            Ok(client) => muster::muster(&client, &mut streams).await,
            Err(code) => code,
        },
        Commands::Reopen(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                logs::reopen(client, streams, args).await
            })
            .await
        }
        // `--daemon` empties files this binary created and the daemon merely
        // inherited, so there is nothing to ask the socket. Not connecting is
        // the feature: a wedged shepherd is when this gets reached for.
        Commands::Flush(ref args) if args.daemon => logs::flush_daemon(&mut streams, &paths),
        Commands::Flush(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                logs::flush(client, streams, args).await
            })
            .await
        }
        // Reads a file and starts nothing, so there is nothing to ask the
        // socket. The history is on disk so it survives the shepherd.
        Commands::Barks(ref args) => dogs::barks(&mut streams, &paths, args),
        // Reads and writes `kv.json` directly and never connects to the
        // shepherd.
        Commands::Kv(ref args) => match &args.command {
            cli::KvCommand::Get(args) => kv::get(&mut streams, &paths, args),
            cli::KvCommand::Set(args) => kv::set(&mut streams, &paths, args),
            cli::KvCommand::Unset(args) => kv::unset(&mut streams, &paths, args),
        },
        // Same rule, same file-first reason: `shep secret set` before a
        // first `shep start` is the ordinary first-run order.
        Commands::Secret(ref args) => secret::secret(&mut streams, &paths, args),
        // Reads and writes `shep.toml` and never connects to the local
        // shepherd: editing the list needs none running. `add` dials the new
        // entry once over ssh, to warn about a typo.
        Commands::Host(ref args) => hosts::host(&mut streams, &paths, args).await,
        // Reads two sheep's configs and writes one, so it needs the shepherd:
        // the copy is of what the running flock holds, not of a file.
        Commands::Copy(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                commands::copy::copy(client, streams, &paths, args).await
            })
            .await
        }
        // Reads the running flock's settings rather than a file, so it needs
        // the shepherd: a Flockfile on disk is not what a sheep is running.
        Commands::Get(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                commands::settings_read::get(client, streams, &paths, args).await
            })
            .await
        }
        // Writes the settings the same read reads, so the same rule: the write
        // lands on the running flock, and the old value it prints beside the
        // new one is what that flock holds, not what a file says.
        Commands::Set(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                commands::settings_write::set(client, streams, &paths, args).await
            })
            .await
        }
        // Drops what `set` wrote, from the same running flock and under the
        // same rule: the override it drops is the one that flock holds.
        Commands::Unset(ref args) => {
            with_client(&mut streams, &link, guard, async |client, streams| {
                commands::settings_write::unset(client, streams, &paths, args).await
            })
            .await
        }
        // Does its own connecting: `connect_client` reports and gives up,
        // which would leave an operator with a live daemon nothing can stop.
        Commands::Kill => admin::kill(&paths, &mut streams).await,
        Commands::Init(ref args) => init::init(&mut streams, args).await,
        // pm2 reads a file and writes a file; `env` writes an operator
        // override, which is the daemon's own store.
        Commands::Import(ref args) => match &args.command {
            ImportCommand::Pm2(args) => import::pm2::import(&mut streams, args),
            ImportCommand::Env(args) => {
                with_client(&mut streams, &link, guard, async |client, streams| {
                    import::dotenv::import_env(client, streams, &paths, args).await
                })
                .await
            }
        },
        Commands::Completions(_)
        | Commands::Daemon(_)
        | Commands::Startup(_)
        | Commands::Unstartup(_)
        | Commands::Schema
        | Commands::DialStdio(_)
        | Commands::Bleats(_)
        | Commands::Lookout(_)
        | Commands::Attach(_)
        | Commands::Whistle
        | Commands::Serve(_)
        | Commands::Runtime(_)
        | Commands::Dev(_)
        | Commands::Dog(_) => {
            unreachable!("handled above: before the shared $SHEP_HOME gate, or on unlocked handles")
        }
    }
}

/// Connects without autostarting, runs `step` on the client, and returns its
/// code; a failed connect has already reported itself and returns its own.
async fn with_client(
    streams: &mut Streams<'_>,
    link: &Link<'_>,
    guard: VersionGuard,
    step: impl AsyncFnOnce(&Client, &mut Streams<'_>) -> ExitCode,
) -> ExitCode {
    match connect_client(streams, link, guard).await {
        Ok(client) => step(&client, streams).await,
        Err(code) => code,
    }
}

/// The verbs [`host_scope`] lets reach `dest`, run against its shepherd.
///
/// Unlocked handles: `flock --follow` and a followed `bleats` run until
/// interrupted, and a lock held that long wedges any other thread's write.
async fn run_on_host(
    command: &Commands,
    quiet: bool,
    dest: &str,
    guard: VersionGuard,
    style: style::Presentation,
    fmt: Format,
) -> ExitCode {
    let link = Link::to_host(dest);
    let mut out = std::io::stdout();
    let mut err = std::io::stderr();
    let mut streams = Streams {
        out: &mut out,
        err: &mut err,
        style,
        fmt,
    };
    match command {
        Commands::Flock(args) => return flock_command(&mut streams, &link, guard, args).await,
        // Connects for itself, for a dog half that has no host to run on.
        Commands::Delete(args) => return lifecycle::delete(&mut streams, &link, guard, args).await,
        // Connects for itself, to skip the dog half a host has no `shep.toml` for.
        Commands::Enable(args) => {
            return toggle_on_host(&mut streams, &link, guard, Toggle::Enable, &args.name).await;
        }
        Commands::Disable(args) => {
            return toggle_on_host(&mut streams, &link, guard, Toggle::Disable, &args.name).await;
        }
        // Connects for itself: a bare `start` is refused before any dial.
        Commands::Start(args) => {
            return load_command(&mut streams, &link, guard, args, Load::Start).await;
        }
        // Dials with `--autostart`: the one verb that boots a host's shepherd.
        Commands::Muster => {
            let booting = Link::to_host_booting(dest);
            return match connect_client(&mut streams, &booting, guard).await {
                Ok(client) => muster::muster(&client, &mut streams).await,
                Err(code) => code,
            };
        }
        // Refused before the dial, which an unreachable host would fail first.
        Commands::Attach(_) => {
            if let Some(code) = attach::unsupported(&mut streams) {
                return code;
            }
        }
        _ => {}
    }
    let client = match connect_client(&mut streams, &link, guard).await {
        Ok(client) => client,
        Err(code) => return code,
    };
    match command {
        Commands::Describe(args) => query::describe(&client, &mut streams, &link, args).await,
        Commands::Fold(args) => query::fold(&client, &mut streams, args).await,
        Commands::Stop(args) | Commands::Thatlldo(args) => {
            lifecycle::stop(&client, &mut streams, args).await
        }
        Commands::Restart(args) => lifecycle::restart(&client, &mut streams, None, args).await,
        Commands::Reset(args) => lifecycle::reset(&client, &mut streams, args).await,
        Commands::Reload(args) => lifecycle::reload(&client, &mut streams, args).await,
        Commands::Bleats(args) => {
            bleats::bleats_on_host(&client, &mut streams, quiet, dest, args).await
        }
        Commands::Stock(args) => lifecycle::stock(&client, &mut streams, args).await,
        Commands::Trigger(args) => trigger::trigger(&client, &mut streams, args).await,
        Commands::Signal(args) => signal::signal(&client, &mut streams, args).await,
        Commands::Whisper(args) => whisper::whisper(&client, &mut streams, args).await,
        Commands::Attach(args) => attach::attach(&client, &mut streams, args).await,
        other => unreachable!("`host_scope` refused {other:?} before it got here"),
    }
}

#[cfg(test)]
mod tests;