pitchfork-cli 2.36.0

Daemons with DX
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
use crate::Result;
use crate::daemon_id::DaemonId;
use crate::daemon_status::DaemonStatus;
use crate::env;
use crate::ipc::client::IpcClient;
use crate::pitchfork_toml::{PitchforkToml, is_global_config, project_dir_for_config};
use crate::procs::PROCS;
use crate::state_file::StateFile;
use miette::WrapErr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Sends a stop signal to a daemon
#[derive(Debug, usage_rs::Args)]
#[usage(
    verbatim_doc_comment,
    long_about = "\
Sends a stop signal to a daemon

Uses a graceful shutdown strategy:
1. Send the configured stop signal (SIGTERM by default) to the process group
   and wait for stop_signal.timeout or supervisor.stop_timeout (default: 5s)
2. If still running, send SIGKILL to force termination

Most processes exit promptly after the first signal. The escalation
ensures stubborn processes are eventually terminated while giving well-behaved
processes time to clean up resources.

--all stops daemons of every project, not only the current one. If that includes
daemons outside this project's config, they are listed and --all asks for
confirmation. Without an interactive terminal (scripts, CI, coding agents) it
refuses instead, unless --force is given. Use --local to stop only this
project's daemons.

When using --all/--local/--global, daemons are stopped in reverse dependency order:
dependents are stopped before the daemons they depend on.

If the supervisor is not running, there is nothing to stop: the command warns
and exits 0, so cleanup scripts can call it unconditionally. It does not start
the supervisor. If a supervisor that crashed left daemon processes behind, it
fails instead, naming them: start the supervisor, which takes over or cleans
up what a crashed supervisor left, and stop them again.

Examples:

    pitchfork stop api           Stop a single daemon
    pitchfork stop api worker    Stop multiple daemons
    pitchfork stop --group backend Stop all daemons in the 'backend' group
    pitchfork stop --all         Stop all running daemons in dependency order
    pitchfork stop --all -f      Same, without confirming daemons outside this project
    pitchfork stop -l            Stop all local daemons in pitchfork.toml
    pitchfork stop -g            Stop all global daemons in config.toml
    pitchfork kill api           Same as 'stop' (alias)"
)]
pub struct Stop {
    /// The name of the daemon(s) to stop
    #[usage(conflicts = "local", conflicts = "global", conflicts = "all")]
    id: Vec<String>,
    /// Stop all daemons in the named group
    #[usage(
        long,
        value_name = "GROUP",
        conflicts = "local",
        conflicts = "global",
        conflicts = "all"
    )]
    group: Option<String>,
    /// Stop all running daemons (in reverse dependency order)
    #[usage(long, short, conflicts = "local", conflicts = "global")]
    all: bool,
    /// Do not ask before stopping daemons outside this project with --all
    #[usage(long, short = 'f', requires = "--all")]
    force: bool,
    /// Stop all local daemons in pitchfork.toml
    #[usage(
        long,
        short = 'l',
        visible_alias = "all-local",
        conflicts = "all",
        conflicts = "global"
    )]
    local: bool,
    /// Stop all global daemons in ~/.config/pitchfork/config.toml and /etc/pitchfork/config.toml
    #[usage(
        long,
        short = 'g',
        visible_alias = "all-global",
        conflicts = "local",
        conflicts = "all"
    )]
    global: bool,
}

impl Stop {
    pub async fn run(&self) -> Result<()> {
        let no_target = self.no_target();

        if no_target {
            super::interactive::require_interactive_terminal()?;
        }

        let mut approved: Vec<DaemonId> = Vec::new();
        if !supervisor_running().await? {
            if self.all {
                // Before stopping marks anything stopped, so a declined
                // confirmation leaves every record as it was.
                let recorded: Vec<DaemonId> = read_state()?
                    .daemons
                    .into_values()
                    .filter(|d| d.id != DaemonId::pitchfork())
                    .filter(|d| d.pid.is_some() || d.status.is_running() || has_retries_pending(d))
                    .map(|d| d.id)
                    .collect();
                self.guard_all(&recorded).await?;
                approved = recorded;
            }
            if self.stop_without_supervisor()? {
                return Ok(());
            }
        }

        let ipc = Arc::new(IpcClient::connect(false).await?);

        let ids: Vec<DaemonId> = if self.all {
            let ids = ipc.get_stoppable_daemons().await?;
            // A supervisor that appeared after the check above may have
            // started daemons since. Those already confirmed are not asked
            // about twice, but any new ones are checked.
            let new: Vec<DaemonId> = ids
                .iter()
                .filter(|id| !approved.contains(id))
                .cloned()
                .collect();
            self.guard_all(&new).await?;
            ids
        } else if self.global || self.local {
            ipc.get_stoppable_configured_daemons(self.global).await?
        } else if no_target {
            let candidates = ipc.get_stoppable_daemons().await?;
            super::interactive::select_daemons_interactively(&candidates, "stop")?
        } else {
            PitchforkToml::resolve_ids_and_group(&self.id, self.group.as_deref())?
        };

        if ids.is_empty() {
            warn!("No daemons to stop");
            return Ok(());
        }

        let result = ipc.stop_daemons(&ids).await?;

        if result.any_failed {
            std::process::exit(1);
        }
        Ok(())
    }

    /// Confirms `--all` among `ids` unless `--force` was given: asks, or
    /// refuses without a terminal, when some are outside the current project.
    async fn guard_all(&self, ids: &[DaemonId]) -> Result<()> {
        if self.force {
            return Ok(());
        }
        let local = IpcClient::get_local_configured_daemons()?;
        let namespace = PitchforkToml::namespace_for_dir(&env::CWD)?;
        let project_dir = current_project_dir();
        // Fresh, so a daemon recorded since an earlier check has its directory.
        let state = read_state()?;
        let outside = outside_project(ids, &local, &namespace, &project_dir, |id| {
            state.daemons.get(id).and_then(|d| {
                // The defining project for a configured daemon, the start
                // directory for an ad-hoc one. A configured record without
                // its project (older ones) has no origin: its working
                // directory says nothing about where its config lives.
                match &d.watch_base_dir {
                    Some(base) => Some(base.clone()),
                    None if d.is_adhoc() => d.dir.clone(),
                    None => None,
                }
            })
        });
        // The prompt reads stdin synchronously.
        tokio::task::spawn_blocking(move || confirm_outside_project(&outside))
            .await
            .map_err(|e| miette::miette!("confirmation prompt failed: {e}"))?
    }

    /// With no supervisor, nothing pitchfork manages is running unless a
    /// crashed supervisor left processes behind. Those cannot be stopped
    /// gracefully from here (no hooks, no dependency order), so they are
    /// reported rather than silently left running or killed.
    ///
    /// Returns false, having changed nothing, if a supervisor started in the
    /// meantime, so the caller stops through it instead.
    fn stop_without_supervisor(&self) -> Result<bool> {
        let targets: Option<Vec<DaemonId>> = if self.all || self.no_target() {
            None
        } else if self.global {
            Some(IpcClient::get_global_configured_daemons()?)
        } else if self.local {
            Some(IpcClient::get_local_configured_daemons()?)
        } else {
            Some(PitchforkToml::resolve_ids_and_group(
                &self.id,
                self.group.as_deref(),
            )?)
        };
        // The check and the update happen under one state file lock, so a
        // supervisor starting concurrently cannot record a daemon in between
        // that this then marks stopped. A state file that cannot be read must
        // not pass for one with no daemons in it: the orphan check could not
        // be done.
        let path = &*env::PITCHFORK_STATE_FILE;
        let outcome = StateFile::update_in_file(path, |sf| {
            if sf
                .daemons
                .get(&DaemonId::pitchfork())
                .is_some_and(crate::supervisor::supervisor_record_is_live)
            {
                return (false, Unsupervised::SupervisorStarted);
            }
            let orphans = orphaned_daemons(sf, targets.as_deref());
            if !orphans.is_empty() {
                return (false, Unsupervised::Orphans(orphans));
            }
            // A failed daemon with retries left, or one that died with a
            // crashed supervisor, would be started again by the next
            // supervisor; the user asked for it to stay stopped.
            let canceled = cancel_pending_retries(sf, targets.as_deref());
            (!canceled.is_empty(), Unsupervised::Canceled(canceled))
        })
        .wrap_err_with(|| format!("failed to read state file {}", path.display()))?;
        let orphans = match outcome {
            Unsupervised::SupervisorStarted => return Ok(false),
            Unsupervised::Orphans(orphans) => orphans,
            Unsupervised::Canceled(canceled) => {
                for id in canceled {
                    info!("Marked {id} stopped so a supervisor does not restart it");
                }
                warn!("Supervisor is not running, nothing to stop");
                return Ok(true);
            }
        };
        let list = orphans
            .iter()
            .map(|o| format!("{} (pid {})", o.id, o.pid))
            .collect::<Vec<_>>()
            .join(", ");
        let mut help = "start the supervisor, which takes over or cleans up what a crashed \
                        supervisor left, then stop them again: pitchfork supervisor start"
            .to_string();
        // A supervisor only takes over a daemon through its recorded leader;
        // a group that outlived its leader has to be signalled directly.
        let leaderless: Vec<String> = orphans
            .iter()
            .filter(|o| !o.leader_alive)
            .map(|o| format!("kill -TERM -{}", o.pid))
            .collect();
        if !leaderless.is_empty() {
            help = format!(
                "{help}\nprocesses whose leader already exited are not taken over by the \
                 supervisor; signal their process groups directly: {}",
                leaderless.join("; ")
            );
        }
        Err(miette::miette!(
            help = help,
            "supervisor is not running, but daemons it started are still running: {list}"
        ))
    }

    /// Whether no daemon was named or selected, so the command picks
    /// interactively.
    fn no_target(&self) -> bool {
        self.id.is_empty() && self.group.is_none() && !self.local && !self.global && !self.all
    }
}

/// The directory of the project the command runs in: that of the nearest
/// project config at or above the working directory, else the working
/// directory itself.
fn current_project_dir() -> PathBuf {
    PitchforkToml::list_paths_from(&env::CWD)
        .into_iter()
        .filter(|p| p.exists() && !is_global_config(p))
        .filter_map(|p| project_dir_for_config(&p))
        .max_by_key(|dir| dir.components().count())
        .unwrap_or_else(|| env::CWD.clone())
}

/// Whether `dir` is `project_dir` or inside it. The paths as written are
/// compared first; only when that fails and both exist are they canonicalized
/// and compared again, so symlinks (`/tmp` against `/private/tmp`) match
/// without a missing directory being compared in a different form.
fn is_within(dir: &Path, project_dir: &Path) -> bool {
    if dir.starts_with(project_dir) {
        return true;
    }
    match (dir.canonicalize(), project_dir.canonicalize()) {
        (Ok(dir), Ok(project_dir)) => dir.starts_with(project_dir),
        _ => false,
    }
}

/// The daemons in `ids` that do not belong to the current project.
///
/// A daemon belongs to it if its config defines it (`local`) or it is an
/// ad-hoc daemon, as `pitchfork run` starts, sharing the project's
/// `namespace`. Either way, `origin_of` must place where the daemon came from
/// (the project that defined a configured daemon, the directory an ad-hoc one
/// started in) inside `project_dir`: that keeps two projects that share a
/// directory name, and so a namespace and perhaps daemon names, apart. A
/// daemon with no recorded origin is judged by `local` alone. `global` is not
/// a project namespace, so it never excuses a daemon.
fn outside_project(
    ids: &[DaemonId],
    local: &[DaemonId],
    namespace: &str,
    project_dir: &Path,
    origin_of: impl Fn(&DaemonId) -> Option<PathBuf>,
) -> Vec<DaemonId> {
    let mut outside: Vec<DaemonId> = ids
        .iter()
        .filter(|id| {
            let claimed =
                local.contains(id) || (namespace != "global" && id.namespace() == namespace);
            let inside = match origin_of(id) {
                // A config inherited from a parent directory is defined above
                // the project, so for configured daemons an origin that
                // contains the project counts too.
                Some(origin) => {
                    claimed
                        && (is_within(&origin, project_dir)
                            || (local.contains(id) && is_within(project_dir, &origin)))
                }
                None => local.contains(id),
            };
            !inside
        })
        .cloned()
        .collect();
    outside.sort();
    outside
}

/// Guards `stop --all` against taking down other projects' daemons by
/// mistake: asks on a terminal, refuses elsewhere. Does nothing when every
/// daemon belongs to this project.
fn confirm_outside_project(outside: &[DaemonId]) -> Result<()> {
    use std::io::{BufRead, IsTerminal, Write};

    if outside.is_empty() {
        return Ok(());
    }
    let list = outside
        .iter()
        .map(|id| format!("  * {}", id.qualified()))
        .collect::<Vec<_>>()
        .join("\n");
    let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
    if !interactive {
        miette::bail!(
            help = "re-run with --force to stop them, or use --local to stop only this \
                    project's daemons",
            "--all would stop daemons outside this project:\n{list}"
        );
    }
    eprintln!("This will stop the following daemons outside this project:\n{list}");
    eprint!("Stop all daemons? [y/N] ");
    std::io::stderr()
        .flush()
        .map_err(|e| miette::miette!("Failed to write prompt: {e}"))?;
    let mut answer = String::new();
    std::io::stdin()
        .lock()
        .read_line(&mut answer)
        .map_err(|e| miette::miette!("Failed to read confirmation: {e}"))?;
    if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") {
        miette::bail!(
            help = "use --local to stop only this project's daemons",
            "Aborted, no daemons were stopped"
        );
    }
    Ok(())
}

/// How long a supervisor that has recorded itself may take to open its IPC
/// socket before it is treated as not running.
const SUPERVISOR_STARTUP_WAIT: Duration = Duration::from_secs(5);

/// Whether a supervisor is running, waiting out one that is starting up.
///
/// The socket is the ground truth for a running supervisor. A starting
/// supervisor records itself, and may already start daemons, before it opens
/// the socket, so a live record without a listening socket is waited on
/// rather than taken to mean nothing is running.
async fn supervisor_running() -> Result<bool> {
    if crate::ipc::supervisor_listening().await {
        return Ok(true);
    }
    let starting = read_state()?
        .daemons
        .get(&DaemonId::pitchfork())
        .is_some_and(crate::supervisor::supervisor_record_is_live);
    if !starting {
        return Ok(false);
    }
    let deadline = Instant::now() + SUPERVISOR_STARTUP_WAIT;
    while Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(100)).await;
        if crate::ipc::supervisor_listening().await {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Read the state file fresh, failing rather than falling back to an empty
/// state when it cannot be read.
fn read_state() -> Result<StateFile> {
    let path = &*env::PITCHFORK_STATE_FILE;
    StateFile::read(path).wrap_err_with(|| format!("failed to read state file {}", path.display()))
}

/// Whether a failed daemon with no process would be started again.
fn has_retries_pending(d: &crate::daemon::Daemon) -> bool {
    d.status.is_errored() && d.pid.is_none() && d.retry_count < d.retry.count()
}

/// Mark daemons (restricted to `targets` when given) that a supervisor would
/// start again as stopped, returning their IDs: failed daemons with retries
/// left, and records still marked running, which a starting supervisor turns
/// into retries once it finds their process gone. Only called once no
/// targeted daemon is still running, so those records' processes are dead.
fn cancel_pending_retries(sf: &mut StateFile, targets: Option<&[DaemonId]>) -> Vec<DaemonId> {
    let ids: Vec<DaemonId> = sf
        .daemons
        .values()
        .filter(|d| d.id != DaemonId::pitchfork())
        .filter(|d| targets.is_none_or(|t| t.contains(&d.id)))
        .filter(|d| {
            (d.status.is_running()
                && d.pid
                    .is_none_or(|pid| recorded_process_is_gone(pid, d.start_time)))
                || has_retries_pending(d)
        })
        .map(|d| d.id.clone())
        .collect();
    for id in &ids {
        if let Some(d) = sf.daemons.get_mut(id) {
            d.status = DaemonStatus::Stopped;
            d.pid = None;
        }
    }
    ids
}

/// Whether the process recorded at `pid` is known to have exited: the PID is
/// dead, or now belongs to a process with a different kernel start token.
/// Rechecked rather than trusting the orphan scan; a live PID whose identity
/// cannot be compared is left for the supervisor to sort out.
fn recorded_process_is_gone(pid: u32, recorded_start_time: Option<u64>) -> bool {
    if !PROCS.is_live(pid) {
        return true;
    }
    matches!(
        (recorded_start_time, PROCS.start_time(pid)),
        (Some(recorded), Some(current)) if recorded != current
    )
}

/// What `stop` found in the state file when no supervisor was listening.
enum Unsupervised {
    /// A supervisor has recorded itself since, so stopping goes through it.
    SupervisorStarted,
    /// Targeted daemons a crashed supervisor left running.
    Orphans(Vec<Orphan>),
    /// Nothing targeted is running; these records were marked stopped.
    Canceled(Vec<DaemonId>),
}

/// A daemon left running by a supervisor that is no longer running.
struct Orphan {
    id: DaemonId,
    /// The recorded PID, which is also the daemon's process group ID.
    pid: u32,
    /// Whether the group's leader is still alive, as opposed to only other
    /// members of its group.
    leader_alive: bool,
}

/// Daemons (restricted to `targets` when given) whose processes are still
/// alive with no supervisor to manage them. A PID now belonging to another
/// process, or one recorded in a previous boot, does not count.
fn orphaned_daemons(sf: &StateFile, targets: Option<&[DaemonId]>) -> Vec<Orphan> {
    let current_boot = PROCS.boot_time();
    // The reported boot time shifts with NTP steps and sleep/resume, so it
    // only rules a record out when it is clearly from another boot.
    let same_boot = |recorded: Option<u64>| {
        recorded
            .is_none_or(|b| b.abs_diff(current_boot) <= crate::supervisor::BOOT_TIME_TOLERANCE_SECS)
    };
    sf.daemons
        .values()
        .filter(|d| d.id != DaemonId::pitchfork())
        .filter(|d| targets.is_none_or(|t| t.contains(&d.id)))
        .filter_map(|d| {
            let pid = d.pid?;
            let leader_alive = PROCS.is_live(pid);
            let alive = if leader_alive {
                match (d.start_time, PROCS.start_time(pid)) {
                    // The kernel start token is the process's identity, but
                    // Linux counts it from boot, so it only holds within one.
                    (Some(recorded), Some(current)) => {
                        recorded == current && same_boot(d.boot_time)
                    }
                    _ => same_boot(d.boot_time),
                }
            } else {
                // Daemons lead their own process group (PGID == PID), and a
                // PID is not handed out while a group with that ID exists, so
                // members still in the group are the daemon's even after
                // the leader (e.g. a wrapping shell) has exited. Members that
                // have exited but were never reaped are not running. Without
                // a recorded boot time, nothing ties the group ID to this
                // boot, so the group is not attributed to the daemon.
                d.boot_time.is_some()
                    && same_boot(d.boot_time)
                    && PROCS.process_group_has_live_member(pid)
            };
            alive.then(|| Orphan {
                id: d.id.clone(),
                pid,
                leader_alive,
            })
        })
        .collect()
}

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

    fn errored(name: &str, retry: u32, retry_count: u32) -> Daemon {
        Daemon {
            id: DaemonId::new("proj", name),
            status: DaemonStatus::Errored(1),
            retry: crate::config_types::Retry(retry),
            retry_count,
            ..Default::default()
        }
    }

    #[test]
    fn stopping_without_a_supervisor_cancels_pending_retries() {
        let mut sf = StateFile::new(std::path::PathBuf::from("state.toml"));
        for d in [
            errored("retrying", 3, 1),
            errored("exhausted", 3, 3),
            errored("other", 3, 0),
            Daemon {
                id: DaemonId::new("proj", "crashed"),
                status: DaemonStatus::Running,
                // Above any PID the kernel hands out, so never alive.
                pid: Some(2_000_000_000),
                ..Default::default()
            },
            Daemon {
                id: DaemonId::new("proj", "alive"),
                status: DaemonStatus::Running,
                pid: Some(std::process::id()),
                ..Default::default()
            },
            // A live PID whose start token differs: reused by another process.
            Daemon {
                id: DaemonId::new("proj", "recycled"),
                status: DaemonStatus::Running,
                pid: Some(std::process::id()),
                start_time: PROCS.start_time(std::process::id()).map(|t| t + 1),
                ..Default::default()
            },
        ] {
            sf.insert_daemon(&d.id.clone(), d);
        }
        let target = DaemonId::new("proj", "retrying");
        let exhausted = DaemonId::new("proj", "exhausted");
        let other = DaemonId::new("proj", "other");
        let crashed = DaemonId::new("proj", "crashed");
        let alive = DaemonId::new("proj", "alive");
        let recycled = DaemonId::new("proj", "recycled");

        let mut canceled = cancel_pending_retries(
            &mut sf,
            Some(&[
                target.clone(),
                exhausted.clone(),
                crashed.clone(),
                alive.clone(),
                recycled.clone(),
            ]),
        );
        canceled.sort_by_key(|id| id.to_string());

        assert_eq!(
            canceled,
            vec![crashed.clone(), recycled.clone(), target.clone()]
        );
        assert!(matches!(sf.daemons[&crashed].status, DaemonStatus::Stopped));
        assert_eq!(sf.daemons[&crashed].pid, None);
        assert!(matches!(sf.daemons[&alive].status, DaemonStatus::Running));
        assert!(matches!(sf.daemons[&target].status, DaemonStatus::Stopped));
        assert!(sf.daemons[&exhausted].status.is_errored());
        assert!(sf.daemons[&other].status.is_errored());
    }

    fn id(ns: &str, name: &str) -> DaemonId {
        DaemonId::try_new(ns, name).unwrap()
    }

    fn dirs(id: &DaemonId) -> Option<PathBuf> {
        match id.name() {
            "adhoc" => Some(PathBuf::from("/work/a/dev/sub")),
            "stranger" => Some(PathBuf::from("/work/b/dev")),
            "api2" => Some(PathBuf::from("/work/b/dev")),
            "parent" => Some(PathBuf::from("/work/a")),
            _ => None,
        }
    }

    #[test]
    fn outside_project_excludes_local_and_adhoc_daemons() {
        let local = [id("dev", "api")];
        let ids = [
            id("dev", "api"),
            id("dev", "adhoc"),
            id("other", "db"),
            id("global", "dns"),
        ];
        let project = Path::new("/work/a/dev");
        assert_eq!(
            outside_project(&ids, &local, "dev", project, dirs),
            vec![id("global", "dns"), id("other", "db")]
        );
    }

    #[test]
    fn configured_daemon_defined_by_another_project_is_outside() {
        // Same namespace and name as one the current config defines.
        let local = [id("dev", "api2")];
        let project = Path::new("/work/a/dev");
        assert_eq!(
            outside_project(&[id("dev", "api2")], &local, "dev", project, dirs).len(),
            1
        );
    }

    #[test]
    fn config_inherited_from_a_parent_directory_is_inside() {
        let project = Path::new("/work/a/dev");
        let configured = [id("dev", "parent")];
        assert!(outside_project(&configured, &configured, "dev", project, dirs).is_empty());
        // Only configured daemons get this: an ad-hoc daemon that started in a
        // parent directory is not this project's.
        assert_eq!(
            outside_project(&configured, &[], "dev", project, dirs).len(),
            1
        );
    }

    #[test]
    fn same_namespace_in_another_directory_is_outside() {
        let ids = [id("dev", "stranger"), id("dev", "unknown")];
        let project = Path::new("/work/a/dev");
        assert_eq!(outside_project(&ids, &[], "dev", project, dirs).len(), 2);
    }

    #[test]
    fn global_namespace_is_never_a_project() {
        let ids = [id("global", "adhoc"), id("other", "db")];
        let project = Path::new("/work/a/dev");
        assert_eq!(outside_project(&ids, &[], "global", project, dirs).len(), 2);
    }

    #[test]
    fn confirm_passes_without_outside_daemons() {
        assert!(confirm_outside_project(&[]).is_ok());
    }
}