Skip to main content

pitchfork_cli/supervisor/
lifecycle.rs

1//! Daemon lifecycle management - start/stop operations
2//!
3//! Contains the core `run()`, `run_once()`, and `stop()` methods for daemon process management.
4
5use super::hooks::{self, HookType, fire_hook};
6use super::{SUPERVISOR, Supervisor};
7use crate::config_types::OneshotWait;
8use crate::daemon::RunOptions;
9use crate::daemon_id::DaemonId;
10use crate::daemon_status::DaemonStatus;
11use crate::error::PortError;
12use crate::inherited_fds::CloseInheritedFds;
13use crate::ipc::IpcResponse;
14use crate::log_store::LogStore;
15use crate::log_store::sqlite::LOG_STORE;
16use crate::pitchfork_toml::{ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, RunCommand};
17use crate::procs::PROCS;
18use crate::settings::{resolve_shell, settings};
19use crate::shell::{HideConsoleWindow, Shell, ShellScript, mise_shell_words};
20use crate::supervisor::state::UpsertDaemonOpts;
21use crate::{Result, env};
22use indexmap::IndexMap;
23use miette::IntoDiagnostic;
24use once_cell::sync::Lazy;
25use regex::Regex;
26use std::collections::HashMap;
27#[cfg(unix)]
28use std::ffi::CString;
29use std::sync::{Arc, atomic};
30use std::time::Duration;
31use tokio::select;
32use tokio::sync::oneshot;
33use tokio::time;
34
35/// Cache for compiled regex patterns to avoid recompilation on daemon restarts
36static REGEX_CACHE: Lazy<std::sync::Mutex<HashMap<String, Regex>>> =
37    Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
38
39fn resolve_configured_ready_port(
40    configured_port: u16,
41    expected_ports: &[u16],
42    resolved_ports: &[u16],
43) -> u16 {
44    let bump_offset = resolved_ports
45        .first()
46        .unwrap_or(&0)
47        .saturating_sub(*expected_ports.first().unwrap_or(&0));
48    if expected_ports.contains(&configured_port) && bump_offset > 0 {
49        configured_port
50            .checked_add(bump_offset)
51            .unwrap_or(configured_port)
52    } else {
53        configured_port
54    }
55}
56
57fn active_port_from_ready_port(ready_port: u16, resolved_ports: &[u16]) -> Option<u16> {
58    resolved_ports
59        .first()
60        .copied()
61        .filter(|&primary_port| primary_port == ready_port)
62}
63
64#[cfg(unix)]
65#[derive(Clone, Debug, PartialEq, Eq)]
66enum RunIdentity {
67    Inherit,
68    Switch {
69        uid: nix::unistd::Uid,
70        gid: nix::unistd::Gid,
71        username: Option<CString>,
72        /// Home directory from the user's passwd entry.
73        home: Option<std::path::PathBuf>,
74    },
75}
76
77/// Get or compile a regex pattern, caching the result for future use
78pub(crate) fn get_or_compile_regex(pattern: &str) -> Option<Regex> {
79    let mut cache = REGEX_CACHE.lock().unwrap_or_else(|e| e.into_inner());
80    if let Some(re) = cache.get(pattern) {
81        return Some(re.clone());
82    }
83    match Regex::new(pattern) {
84        Ok(re) => {
85            cache.insert(pattern.to_string(), re.clone());
86            Some(re)
87        }
88        Err(e) => {
89            error!("invalid regex pattern '{pattern}': {e}");
90            None
91        }
92    }
93}
94
95/// Handle for an in-flight readiness command probe.
96///
97/// The spawned task owns the `tokio::process::Child` and waits for either the
98/// process to exit or the cancel signal. Dropping the handle without cancelling
99/// leaves the task running, but the child is started with `kill_on_drop(true)`
100/// so it will still be terminated when the task ends.
101pub(crate) struct CmdProbe {
102    pub(crate) cancel_tx: tokio::sync::oneshot::Sender<()>,
103    pub(crate) result_rx: tokio::sync::oneshot::Receiver<std::io::Result<std::process::ExitStatus>>,
104}
105
106/// Set the environment pitchfork gives a daemon and its `ready_cmd` probe:
107/// the original `PATH`, the daemon's own `env`, `PITCHFORK_DAEMON_ID`,
108/// `PITCHFORK_DAEMON_NAMESPACE`, `PITCHFORK_RETRY_COUNT`, and `PORT` /
109/// `PORT0..N` for its resolved ports.
110fn apply_runtime_env(
111    command: &mut tokio::process::Command,
112    id: &DaemonId,
113    retry_count: u32,
114    daemon_env: Option<&IndexMap<String, String>>,
115    resolved_ports: &[u16],
116) {
117    if let Some(ref path) = *env::ORIGINAL_PATH {
118        command.env("PATH", path);
119    }
120    if let Some(env_vars) = daemon_env {
121        command.envs(env_vars);
122    }
123    command
124        .env("PITCHFORK_DAEMON_ID", id.qualified())
125        .env("PITCHFORK_DAEMON_NAMESPACE", id.namespace())
126        .env("PITCHFORK_RETRY_COUNT", retry_count.to_string());
127    if let Some(port) = resolved_ports.first() {
128        command.env("PORT", port.to_string());
129        for (index, port) in resolved_ports.iter().enumerate() {
130            command.env(format!("PORT{index}"), port.to_string());
131        }
132    }
133}
134
135/// A probe whose result channel is already closed. The caller treats it the
136/// same as a probe that exited non-zero and respawns it after the
137/// ready_check_interval, preserving the existing retry behaviour.
138fn closed_cmd_probe() -> CmdProbe {
139    let (cancel_tx, _) = tokio::sync::oneshot::channel();
140    let (_, result_rx) = tokio::sync::oneshot::channel();
141    CmdProbe {
142        cancel_tx,
143        result_rx,
144    }
145}
146
147/// Spawn a readiness command probe and return a handle that can be used to wait
148/// for the exit status or cancel the probe.
149///
150/// The probe is started with `kill_on_drop(true)` as a cancellation fallback. The
151/// spawned task waits for the process to exit; if cancellation is requested, it
152/// kills the child and waits for it to reap before reporting the result.
153pub(crate) fn spawn_cmd_probe(
154    id: &DaemonId,
155    cmd: &RunCommand,
156    dir: &std::path::Path,
157    retry_count: u32,
158    daemon_env: Option<&IndexMap<String, String>>,
159    resolved_ports: &[u16],
160) -> CmdProbe {
161    let mut command = match cmd {
162        // The argv form: the program and its arguments as written, with no
163        // shell to reinterpret them, as for a `run` array.
164        RunCommand::Argv(argv) => {
165            let Some((program, args)) = argv.split_first().filter(|(p, _)| !p.is_empty()) else {
166                warn!("daemon {id}: ready_cmd array has no program to run");
167                return closed_cmd_probe();
168            };
169            let mut c = tokio::process::Command::new(program);
170            c.args(args);
171            c
172        }
173        // Use the same shell as daemon run and hooks. A probe is not worth
174        // failing the daemon over, so an unparseable setting degrades to the
175        // platform's own shell here rather than propagating; run_once has
176        // already rejected the start by then, so this only fires for a daemon
177        // whose settings changed under it.
178        RunCommand::Shell(cmd) => match resolve_shell() {
179            Ok(parts) => {
180                let (program, args) = parts.split_first().unwrap();
181                let mut c = tokio::process::Command::new(program);
182                c.shell_script(program, args, cmd);
183                c
184            }
185            Err(e) => {
186                warn!("daemon {id}: {e}; using the platform shell for this probe");
187                Shell::default_for_platform().command(cmd)
188            }
189        },
190    };
191    command
192        .current_dir(dir)
193        .stdout(std::process::Stdio::null())
194        .stderr(std::process::Stdio::null())
195        .kill_on_drop(true)
196        .hide_console_window()
197        .close_inherited_fds();
198    apply_runtime_env(&mut command, id, retry_count, daemon_env, resolved_ports);
199    let mut child = match command.spawn() {
200        Ok(child) => child,
201        Err(e) => {
202            warn!("daemon {id}: failed to spawn command probe: {e}");
203            return closed_cmd_probe();
204        }
205    };
206
207    let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
208    let (result_tx, result_rx) = tokio::sync::oneshot::channel();
209
210    tokio::spawn(async move {
211        let status = tokio::select! {
212            status = child.wait() => status,
213            _ = &mut cancel_rx => {
214                let mut child = child;
215                let _ = child.kill().await;
216                child.wait().await
217            }
218        };
219        let _ = result_tx.send(status);
220    });
221
222    CmdProbe {
223        cancel_tx,
224        result_rx,
225    }
226}
227
228/// Cancel an active command probe and clear its handle.
229fn stop_cmd_probe_state(probe: &mut Option<CmdProbe>) {
230    if let Some(p) = probe.take() {
231        let _ = p.cancel_tx.send(());
232    }
233}
234
235/// Spawn a detached task that kills a daemon's process group after its
236/// readiness checks are exhausted, logging a failed kill instead of
237/// discarding it. The returned handle is awaited before the readiness
238/// failure is reported so the process group is down by then.
239fn spawn_ready_fail_kill(
240    id: DaemonId,
241    pid: u32,
242    stop_cfg: crate::config_types::StopConfig,
243) -> tokio::task::JoinHandle<()> {
244    tokio::spawn(async move {
245        if let Err(e) = PROCS
246            .kill_process_group_async(pid, stop_cfg.signal.into(), stop_cfg.timeout)
247            .await
248        {
249            error!("daemon {id}: failed to kill pid {pid} after readiness failure: {e}");
250        }
251    })
252}
253
254/// Returns true if any configured readiness check can still succeed.
255/// A check with no timeout is unbounded; a timed check can still succeed until its
256/// deadline fires. `ready_delay` is only used as a fallback when no other check is
257/// configured, so it is not counted here.
258#[allow(clippy::too_many_arguments)]
259fn any_ready_check_remaining(
260    ready_output: Option<&ReadyOutput>,
261    output_exhausted: bool,
262    ready_port: Option<&ReadyPort>,
263    port_exhausted: bool,
264    ready_http: Option<&ReadyHttp>,
265    http_exhausted: bool,
266    ready_cmd: Option<&ReadyCmd>,
267    cmd_exhausted: bool,
268) -> bool {
269    ready_output.is_some_and(|o| o.timeout.is_none() || !output_exhausted)
270        || ready_port.is_some_and(|p| p.timeout.is_none() || !port_exhausted)
271        || ready_http.is_some_and(|h| h.timeout.is_none() || !http_exhausted)
272        || ready_cmd.is_some_and(|c| c.timeout.is_none() || !cmd_exhausted)
273}
274
275fn delay_readiness_succeeded(
276    ready_notified: bool,
277    has_other_ready_check: bool,
278    process_exited: bool,
279    process_running: bool,
280) -> bool {
281    !ready_notified && !has_other_ready_check && !process_exited && process_running
282}
283
284/// Terminal state recorded for a daemon run that has ended, and whether that
285/// ending counts as a successful exit.
286///
287/// A `oneshot` daemon's whole job is to finish, so a clean exit of its own
288/// accord is `Completed` rather than `Stopped` — that is what makes it
289/// distinguishable from a service that is merely not running, and what lets
290/// `depends` treat it as satisfied. An explicit stop is still a stop: the task
291/// was interrupted, not completed.
292fn terminal_exit_state(
293    exit_reason: &str,
294    oneshot: bool,
295    exit_code: i32,
296    exited_cleanly: bool,
297) -> (DaemonStatus, bool) {
298    match exit_reason {
299        "exit" if oneshot => (DaemonStatus::Completed, true),
300        "stop" | "exit" => (DaemonStatus::Stopped, exited_cleanly),
301        _ => (DaemonStatus::Errored(exit_code), false),
302    }
303}
304
305/// Whether a stop that arrived after a run's process was already gone should
306/// leave the status its monitor settled on alone.
307///
308/// Only a completed task is left alone: it had already done its work, so there
309/// was nothing for the stop to interrupt, and overwriting it would report a
310/// failure to anyone waiting on it. Anything else — a failure above all — is
311/// replaced by the stop, so the retry checker does not carry on with a task
312/// the user has stopped.
313/// Why the argv form of `run` cannot be started, if it cannot.
314///
315/// Config load checks the array as written, but a template can still render
316/// the program to nothing, or to `exec`.
317/// Why a daemon's `ready_cmd` or `health_cmd` array (named by `field`)
318/// cannot be run, if it cannot: its program, after templates are rendered, is
319/// empty or `exec`. Config load rejects both as written, but a template can
320/// still render to them, and a probe that can never run would keep the start
321/// waiting for readiness, or fail every health check.
322fn invalid_probe_program(id: &DaemonId, field: &str, run: Option<&RunCommand>) -> Option<String> {
323    let RunCommand::Argv(argv) = run? else {
324        return None;
325    };
326    match argv.first().map(String::as_str) {
327        None | Some("") => Some(format!(
328            "daemon {id} has no program to run in its {field} array"
329        )),
330        Some("exec") => Some(format!(
331            "daemon {id} starts its {field} array with \"exec\"; a {field} array runs the program directly, so remove \"exec\""
332        )),
333        Some(_) => None,
334    }
335}
336
337fn invalid_argv_program(id: &DaemonId, argv: &[String]) -> Option<String> {
338    match argv.first().map(String::as_str) {
339        None | Some("") => Some(format!(
340            "daemon {id} has no program to run: its run array starts with an empty value"
341        )),
342        Some("exec") => Some(format!(
343            "daemon {id} starts its run array with \"exec\"; a run array starts the program directly, so remove \"exec\""
344        )),
345        Some(_) => None,
346    }
347}
348
349#[cfg(any(windows, test))]
350fn unsupported_windows_options(opts: &RunOptions, supervisor_user: &str) -> Option<String> {
351    if opts.pty == Some(true) {
352        return Some(format!(
353            "daemon {}: pty = true is not supported on Windows; remove pty or set it to false",
354            opts.id
355        ));
356    }
357    let configured_user = opts.user.as_deref().unwrap_or_default().trim();
358    if !configured_user.is_empty() || !supervisor_user.trim().is_empty() {
359        return Some(format!(
360            "daemon {}: user switching is not supported on Windows; remove the daemon's user and settings.supervisor.user, or set them to empty strings",
361            opts.id
362        ));
363    }
364    None
365}
366
367/// Program and arguments to spawn for `words`, run through `mise x` when given.
368/// Each word stays one argument, including a script carried by shell-exec.
369fn launch_command(words: Vec<String>, mise_bin: Option<&std::path::Path>) -> (String, Vec<String>) {
370    match mise_bin {
371        Some(mise_bin) => {
372            let mut args = vec!["x".to_string(), "--".to_string()];
373            args.extend(words);
374            (mise_bin.to_string_lossy().to_string(), args)
375        }
376        None => {
377            let mut words = words.into_iter();
378            // Never empty: a shell resolves to at least its program, and an
379            // empty argv is refused before this is reached.
380            let program = words.next().unwrap_or_default();
381            (program, words.collect())
382        }
383    }
384}
385
386/// Text of one line read from a daemon's output, its line ending removed.
387///
388/// Decoded as the log sink decodes lines, so output that is not UTF-8 is
389/// logged rather than ending the read. A PTY slave's ONLCR turns `\n` into
390/// `\r\n`, so every trailing `\r` goes, as the sink also strips them.
391fn output_line_text(line: &[u8]) -> String {
392    let line = line.strip_suffix(b"\n").unwrap_or(line);
393    crate::cli::log_sink::decode_line(line)
394        .trim_end_matches('\r')
395        .to_string()
396}
397
398/// Send each line of `reader` to `tx` until the output ends or nobody is
399/// listening.
400///
401/// Reading stops only there, never on a line's content: a reader that gave up
402/// would stop draining the daemon's pipe or PTY, and the daemon would block,
403/// or fail, on its next write.
404async fn forward_output_lines<R>(mut reader: R, tx: tokio::sync::mpsc::Sender<super::OutputLine>)
405where
406    R: tokio::io::AsyncBufRead + Unpin,
407{
408    use tokio::io::AsyncBufReadExt;
409    let mut line = Vec::new();
410    loop {
411        line.clear();
412        // A read error ends the output too: a Linux PTY master reports the
413        // slave closing, once the daemon is gone, as EIO rather than end of
414        // file. Whatever of a last, unterminated line arrived before it is
415        // still sent.
416        let last = match reader.read_until(b'\n', &mut line).await {
417            Ok(0) => break,
418            Ok(_) => false,
419            Err(_) if line.is_empty() => break,
420            Err(_) => true,
421        };
422        let sent = tx
423            .send(super::OutputLine {
424                text: output_line_text(&line),
425                source: super::OutputSource::Local,
426            })
427            .await;
428        if sent.is_err() || last {
429            break;
430        }
431    }
432}
433
434fn stop_keeps_finalized_status(status: &DaemonStatus) -> bool {
435    status.is_completed()
436}
437
438/// How long a failed start waits for the daemon's output to become queryable
439/// before reporting. Typically satisfied in a few dozen milliseconds; a daemon
440/// that failed without printing anything waits the whole of it, so keep it
441/// short.
442const SINK_OUTPUT_TIMEOUT: Duration = Duration::from_millis(400);
443
444/// Marks a daemon as having its retries managed by a foreground `run` for as
445/// long as this value lives, so the background checker does not start an
446/// attempt out from under it. Released on every exit from the retry loop,
447/// including the early returns.
448/// Counts a stop of this daemon once the stop is done, while its lock is
449/// still held. See `Supervisor::stop_epochs`.
450struct StopEpochGuard(DaemonId);
451
452impl Drop for StopEpochGuard {
453    fn drop(&mut self) {
454        SUPERVISOR.bump_stop_epoch(&self.0);
455    }
456}
457
458pub(crate) struct RetryingGuard {
459    id: DaemonId,
460    cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
461}
462
463impl RetryingGuard {
464    /// Whether a `stop` or a `disable` has asked this retry sequence to end.
465    fn is_cancelled(&self) -> bool {
466        self.cancel.load(std::sync::atomic::Ordering::Acquire)
467    }
468}
469
470impl Drop for RetryingGuard {
471    fn drop(&mut self) {
472        let mut retrying = SUPERVISOR
473            .retrying
474            .lock()
475            .unwrap_or_else(|e| e.into_inner());
476        // Drop this claim's flag only. Another sequence for the same daemon
477        // may still be running, and it has to stay both protected from the
478        // retry checker and reachable by a stop.
479        if let Some(claims) = retrying.get_mut(&self.id) {
480            claims.retain(|flag| !std::sync::Arc::ptr_eq(flag, &self.cancel));
481            if claims.is_empty() {
482                retrying.remove(&self.id);
483            }
484        }
485    }
486}
487
488impl Supervisor {
489    /// Whether a foreground `run` is already working through this daemon's
490    /// retries.
491    pub(crate) fn is_retrying(&self, id: &DaemonId) -> bool {
492        self.retrying
493            .lock()
494            .unwrap_or_else(|e| e.into_inner())
495            .get(id)
496            .is_some_and(|claims| !claims.is_empty())
497    }
498
499    /// How many times this daemon has been stopped so far.
500    pub(crate) fn stop_epoch(&self, id: &DaemonId) -> u64 {
501        self.stop_epochs
502            .lock()
503            .unwrap_or_else(|e| e.into_inner())
504            .get(id)
505            .copied()
506            .unwrap_or(0)
507    }
508
509    fn bump_stop_epoch(&self, id: &DaemonId) {
510        *self
511            .stop_epochs
512            .lock()
513            .unwrap_or_else(|e| e.into_inner())
514            .entry(id.clone())
515            .or_default() += 1;
516    }
517
518    fn mark_retrying(&self, id: &DaemonId) -> RetryingGuard {
519        let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
520        self.retrying
521            .lock()
522            .unwrap_or_else(|e| e.into_inner())
523            .entry(id.clone())
524            .or_default()
525            .push(cancel.clone());
526        RetryingGuard {
527            id: id.clone(),
528            cancel,
529        }
530    }
531
532    /// Ask a foreground retry sequence for this daemon, if there is one, to
533    /// end. A stop is a decision about the daemon, not about one of its
534    /// attempts, so the attempts left must not go ahead behind it.
535    pub(crate) fn cancel_retrying(&self, id: &DaemonId) {
536        if let Some(claims) = self
537            .retrying
538            .lock()
539            .unwrap_or_else(|e| e.into_inner())
540            .get(id)
541        {
542            // Every claim, not just the newest: a start that is sleeping out a
543            // backoff is as much a sequence the stop has to end as the one that
544            // claimed the daemon last.
545            for cancel in claims {
546                cancel.store(true, std::sync::atomic::Ordering::Release);
547            }
548        }
549    }
550
551    /// Run a daemon, handling retries if configured
552    pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
553        let id = opts.id.clone();
554        let mut restart_mark = None;
555        let result = self.run_inner(opts, None, &mut restart_mark).await;
556        // A forced start records the daemon it replaces as restarting. If no
557        // new process took the record over, the restart did not happen.
558        if let Some(mark) = restart_mark {
559            self.settle_restarting(&id, mark).await;
560        }
561        result
562    }
563
564    /// Record a daemon left `restarting` with no process as `stopped`: its
565    /// restart did not start a new process, and leaving the mark in place
566    /// would have `pitchfork wait` follow a restart that is never coming.
567    ///
568    /// `mark` is the daemon's stop epoch right after the restart's own stop.
569    /// Any stop since (a `pitchfork stop`, or another restart's stop that
570    /// left its own mark) has the last word, so the record is left alone, as
571    /// is one that has moved on (a new process, another status).
572    pub(crate) async fn settle_restarting(&self, id: &DaemonId, mark: u64) {
573        let lock = self.stop_lock(id).await;
574        let _guard = lock.lock().await;
575        if self.stop_epoch(id) != mark {
576            return;
577        }
578        let mut state_file = self.state_file.lock().await;
579        if state_file
580            .daemons
581            .get(id)
582            .is_some_and(|d| d.pid.is_none() && d.status.is_restarting())
583        {
584            debug!("daemon {id} was not started again after its restart; recording it as stopped");
585            state_file.set_status(id, DaemonStatus::Stopped);
586        }
587    }
588
589    /// Run an attempt the retry checker decided on while `stop_epoch` read
590    /// `approved_at`. If the daemon has been stopped since, the attempt is
591    /// abandoned instead of started.
592    ///
593    /// `restart_mark` is set as in [`Self::run_inner`], if a forced attempt
594    /// stopped a running instance.
595    pub(crate) async fn run_retry(
596        &self,
597        opts: RunOptions,
598        approved_at: u64,
599        restart_mark: &mut Option<u64>,
600    ) -> Result<IpcResponse> {
601        self.run_inner(opts, Some(approved_at), restart_mark).await
602    }
603
604    /// Reject unsupported options while the caller holds the daemon's stop lock.
605    #[cfg(windows)]
606    async fn reject_unsupported_windows_options(
607        &self,
608        opts: &RunOptions,
609    ) -> Result<Option<IpcResponse>> {
610        let Some(error) = unsupported_windows_options(opts, &settings().supervisor.user) else {
611            return Ok(None);
612        };
613        // A rejected replacement must leave the running instance alone. A
614        // rejected retry has no process and must become terminal, or the
615        // background checker will keep retrying its old errored record.
616        if self
617            .get_daemon(&opts.id)
618            .await
619            .is_none_or(|d| d.pid.is_none())
620        {
621            self.upsert_daemon(
622                UpsertDaemonOpts::from_run_options(opts, DaemonStatus::Failed(error.clone()))
623                    .build(),
624            )
625            .await?;
626        }
627        Ok(Some(IpcResponse::DaemonFailed { error }))
628    }
629
630    /// `restart_mark` is set to the stop epoch a forced start's own stop of
631    /// the running instance left, if it made one (see
632    /// [`Self::settle_restarting`]).
633    async fn run_inner(
634        &self,
635        opts: RunOptions,
636        approved_at: Option<u64>,
637        restart_mark: &mut Option<u64>,
638    ) -> Result<IpcResponse> {
639        let id = &opts.id;
640        let cmd = opts.cmd.clone();
641
642        // Clear any pending autostop for this daemon since it's being started
643        {
644            let mut pending = self.pending_autostops.lock().await;
645            if pending.remove(id).is_some() {
646                info!("cleared pending autostop for {id} (daemon starting)");
647            }
648        }
649
650        // Serialize against any in-flight stop of this daemon: a stop now
651        // waits for the whole process group to exit, so the Stopping window
652        // can last seconds instead of milliseconds. Starting through that
653        // window would collide with the dying instance (duplicate processes,
654        // port conflicts). Acquiring the stop lock waits the stop out; the
655        // state is re-read afterwards. The guard is owned and handed to
656        // run_once, which holds it until the new daemon's Running state and
657        // PID are persisted — releasing it before that point would let a
658        // concurrent run pass this same check (duplicate processes) or let a
659        // concurrent stop see no PID and return without stopping anything.
660        let mut stop_guard = Some(self.stop_lock(id).await.lock_owned().await);
661        // Checked here, under the daemon's lock, because that is what a stop
662        // takes too: an approval from before the stop cannot slip past it.
663        // Writing `stopped` over the record is not enough on its own, since an
664        // attempt already approved would read that as a daemon free to start.
665        if let Some(approved_at) = approved_at
666            && self.stop_epoch(id) != approved_at
667        {
668            info!("daemon {id} was stopped after this retry was decided on; not starting it");
669            return Ok(IpcResponse::DaemonNotRunning);
670        }
671        // Likewise a disable, for every start the supervisor makes on its own
672        // (retries, the schedule, boot): each read the disabled set before
673        // waiting for this lock, and `disable` takes it too.
674        if (approved_at.is_some() || !opts.requested_by_client)
675            && self.state_file.lock().await.disabled.contains(id)
676        {
677            info!("daemon {id} was disabled before this start; not starting it");
678            return Ok(IpcResponse::DaemonNotRunning);
679        }
680        if let Some(response) = self
681            .claim_or_defer(&opts, &mut stop_guard, restart_mark)
682            .await?
683        {
684            return Ok(response);
685        }
686
687        // If wait_ready is true and retry is configured, implement retry loop
688        if opts.wait_ready && opts.retry.count() > 0 {
689            // Claim this daemon's retries for the duration of the loop. The
690            // backoff between attempts leaves the record errored with no PID,
691            // which is what `check_retry` scans for, and an attempt started
692            // there would leave this call reporting on a run it does not own.
693            let retrying_claim = self.mark_retrying(id);
694            // Use saturating_add to avoid overflow when retry = u32::MAX (infinite)
695            let max_attempts = opts.retry.count().saturating_add(1);
696            for attempt in 0..max_attempts {
697                let mut retry_opts = opts.clone();
698                retry_opts.retry_count = attempt;
699                retry_opts.cmd = cmd.clone();
700
701                // The first attempt starts under the guard held since the
702                // running check above; later attempts re-acquire it so stops
703                // are not locked out during the backoff sleeps.
704                let mut guard = Some(match stop_guard.take() {
705                    Some(guard) => guard,
706                    None => self.stop_lock(id).await.lock_owned().await,
707                });
708                // The background retry checker may have run this attempt for
709                // us and seen it succeed while we slept. Starting again would
710                // repeat a task that has already done its work — for a
711                // migration or a seed, repeating its side effects.
712                //
713                // Only after a backoff, though. A completed record on the first
714                // attempt is the previous run's, and a start is defined to
715                // re-run a completed oneshot; short-circuiting here would make
716                // that true only for oneshots without `retry`.
717                if attempt > 0
718                    && let Some(daemon) = self.get_daemon(id).await
719                    && daemon.status.is_completed()
720                {
721                    info!("daemon {id} completed while waiting to retry; not running it again");
722                    return Ok(IpcResponse::DaemonReady { daemon });
723                }
724                // A disable during the backoff ends the sequence, checked under
725                // the guard `disable` takes. It wakes the backoff the way a stop
726                // does, so it is checked first to report what happened.
727                if attempt > 0 && self.state_file.lock().await.disabled.contains(id) {
728                    info!(
729                        "daemon {id} was disabled while waiting to retry; abandoning its retries"
730                    );
731                    return Ok(IpcResponse::DaemonFailed {
732                        error: "disabled while retrying".to_string(),
733                    });
734                }
735                // A stop that arrived during the backoff ends the sequence.
736                // Without this the loop would start the next attempt on a
737                // daemon the user has just stopped, and the stop would look
738                // like it had done nothing.
739                if retrying_claim.is_cancelled() {
740                    info!("daemon {id} was stopped while waiting to retry; abandoning its retries");
741                    return Ok(IpcResponse::DaemonFailed {
742                        error: "stopped while retrying".to_string(),
743                    });
744                }
745                // Ownership has to be re-checked on every attempt, not just
746                // the first. Another start can claim the daemon during the
747                // backoff, when this attempt no longer holds its stop lock.
748                // Spawning another process here would replace that attempt's
749                // monitor registration and leave its process unmonitored.
750                if let Some(response) = self
751                    .claim_or_defer(&retry_opts, &mut guard, restart_mark)
752                    .await?
753                {
754                    return Ok(response);
755                }
756                let Some(guard) = guard else {
757                    // Only the deferring paths take the guard, and each of
758                    // those returned above.
759                    return Ok(IpcResponse::DaemonAlreadyRunning);
760                };
761                let result = self.run_once(retry_opts, guard).await?;
762
763                match result {
764                    IpcResponse::DaemonReady { daemon } => {
765                        return Ok(IpcResponse::DaemonReady { daemon });
766                    }
767                    IpcResponse::DaemonFailedWithCode {
768                        exit_code,
769                        resolved_ports,
770                    } => {
771                        if attempt < opts.retry.count() {
772                            // `run_once` reports failure the moment the process
773                            // exits, but its monitor finalizes the record only
774                            // after draining the process's remaining output.
775                            // Until then the record still names this attempt's
776                            // PID, and the next attempt's ownership check would
777                            // read its own dead predecessor as a competing run
778                            // and abandon the retries that are left.
779                            let attempt_pid = self.get_daemon(id).await.and_then(|d| d.pid);
780                            self.wait_for_exit_finalized(id, attempt_pid).await;
781                            let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
782                            info!(
783                                "daemon {id} failed (attempt {}/{}), retrying in {}s",
784                                attempt + 1,
785                                max_attempts,
786                                backoff_secs
787                            );
788                            fire_hook(
789                                HookType::OnRetry,
790                                id.clone(),
791                                super::hooks::HookDirs::new(
792                                    opts.dir.0.clone(),
793                                    opts.watch_base_dir.clone(),
794                                ),
795                                attempt + 1,
796                                opts.env.clone(),
797                                resolved_ports,
798                                vec![],
799                            )
800                            .await;
801                            // Slept in slices so a stop arriving during a
802                            // long backoff — they grow to an hour — is acted
803                            // on when it arrives rather than when the sleep
804                            // happens to end.
805                            let backoff_deadline =
806                                tokio::time::Instant::now() + Duration::from_secs(backoff_secs);
807                            while tokio::time::Instant::now() < backoff_deadline
808                                && !retrying_claim.is_cancelled()
809                            {
810                                let remaining = backoff_deadline - tokio::time::Instant::now();
811                                time::sleep(remaining.min(Duration::from_millis(200))).await;
812                            }
813                            continue;
814                        } else {
815                            info!("daemon {id} failed after {max_attempts} attempts");
816                            return Ok(IpcResponse::DaemonFailedWithCode {
817                                exit_code,
818                                resolved_ports,
819                            });
820                        }
821                    }
822                    other => return Ok(other),
823                }
824            }
825        }
826
827        // No retry or wait_ready is false
828        let guard = match stop_guard.take() {
829            Some(guard) => guard,
830            None => self.stop_lock(id).await.lock_owned().await,
831        };
832        self.run_once(opts, guard).await
833    }
834
835    /// Wait for a just-failed attempt's monitor to write its terminal state,
836    /// clearing the PID from the record.
837    ///
838    /// Bounded a little beyond the monitor's own five-second output drain, the
839    /// longest it can hold the record after the process has gone. Giving up
840    /// early is safe: the ownership check that follows simply sees a PID and
841    /// defers, which is what it would have done anyway.
842    ///
843    /// `pid` names the run being waited for, so a record that has moved on to
844    /// another run is not mistaken for this one still finishing.
845    async fn wait_for_exit_finalized(&self, id: &DaemonId, pid: Option<u32>) {
846        let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
847        loop {
848            match self.get_daemon(id).await {
849                Some(daemon) if pid.map_or(daemon.pid.is_some(), |pid| daemon.pid == Some(pid)) => {
850                }
851                _ => return,
852            }
853            if tokio::time::Instant::now() >= deadline {
854                debug!("daemon {id}: previous attempt has not finalized yet; continuing anyway");
855                return;
856            }
857            time::sleep(Duration::from_millis(50)).await;
858        }
859    }
860
861    /// Decide whether this start may take the daemon's record, or must stand
862    /// down because a live run already owns it.
863    ///
864    /// Returns `Some(response)` when the start is rejected or must report an
865    /// existing run's outcome, and `None` when the record is free (including
866    /// after a forced stop of the previous instance).
867    ///
868    /// The caller must hold the daemon's stop lock. Unsupported Windows options
869    /// are rejected before a forced claim can stop an existing instance, even
870    /// when settings changed during a foreground retry's backoff.
871    ///
872    /// `stop_guard` is released before an in-flight oneshot is awaited: that
873    /// wait lasts as long as the task does, and holding the lock would block a
874    /// stop of the very run being waited on.
875    async fn claim_or_defer(
876        &self,
877        opts: &RunOptions,
878        stop_guard: &mut Option<tokio::sync::OwnedMutexGuard<()>>,
879        restart_mark: &mut Option<u64>,
880    ) -> Result<Option<IpcResponse>> {
881        let id = &opts.id;
882        #[cfg(windows)]
883        if let Some(response) = self.reject_unsupported_windows_options(opts).await? {
884            return Ok(Some(response));
885        }
886        let Some(daemon) = self.get_daemon(id).await else {
887            return Ok(None);
888        };
889        // Entering a directory does not re-run a finished task, at any level of
890        // the dependency graph — the layout this exists for reaches the task
891        // through a service's `depends`, not by naming it. Decided here rather
892        // than in the client because this is the authoritative state: the state
893        // file lags it by up to the flush interval, which is exactly the window
894        // a second entry lands in after the task completes.
895        // `opts.oneshot` rather than the record's: the request carries what
896        // config says now, while the stored flag is only refreshed by a run, so
897        // a daemon that used to be a task would otherwise stay skipped forever
898        // after being turned into a service.
899        if opts.on_directory_enter && opts.oneshot && daemon.status.is_completed() {
900            debug!("daemon {id} already completed; directory entry leaves it alone");
901            return Ok(Some(IpcResponse::DaemonReady { daemon }));
902        }
903        // Stopping (or restarting) is treated as "not running": the
904        // monitoring task will clean it up. Only a live PID under a
905        // non-terminal status blocks a start.
906        if daemon.status.is_stopping_or_restarting()
907            || daemon.status.is_stopped()
908            || daemon.status.is_completed()
909        {
910            return Ok(None);
911        }
912        let Some(pid) = daemon.pid else {
913            return Ok(None);
914        };
915        if opts.force {
916            // A forced start replaces the running instance, so the daemon is
917            // recorded as restarting rather than stopped until the new
918            // process is up; `run` settles it if the start does not happen.
919            self.stop_locked_with(id, true).await?;
920            // Read under the daemon's lock, which this start still holds, so
921            // the epoch is the one this stop left.
922            *restart_mark = Some(self.stop_epoch(id));
923            info!("run: stop completed for daemon {id}");
924            return Ok(None);
925        }
926        if daemon.oneshot && opts.wait_ready {
927            // An in-flight oneshot has not done its work yet, so reporting
928            // "already running" would let dependents start against the state
929            // the task is still establishing. Wait for the run already under
930            // way instead.
931            info!("daemon {id} is an in-flight oneshot (pid {pid}); waiting for it to finish");
932            drop(stop_guard.take());
933            return Ok(Some(
934                self.await_running_oneshot(id, opts.oneshot_wait, pid).await,
935            ));
936        }
937        // A record can name a PID that has already exited: `stop` leaves the
938        // terminal state to a monitor that still owns the daemon, and that
939        // monitor writes it only after draining the process's output. Rejecting
940        // a start against a dead PID would fail an ordinary stop-then-start for
941        // the length of that drain, so confirm the process is really there
942        // before refusing. The oneshot branch above deliberately comes first: a
943        // task whose process has exited is about to be recorded as completed,
944        // and starting a second copy of it is exactly what waiting prevents.
945        PROCS.refresh_pids(&[pid]);
946        if !PROCS.is_running(pid) {
947            debug!(
948                "daemon {id}: record still names pid {pid}, which has exited; its monitor has not finalized yet"
949            );
950            return Ok(None);
951        }
952        warn!("daemon {id} already running with pid {pid}");
953        Ok(Some(IpcResponse::DaemonAlreadyRunning))
954    }
955
956    /// Wait for a oneshot that is already running to reach a terminal state,
957    /// and report it as if this call had started the task itself.
958    ///
959    /// Polls the state file because the terminal state is written by the
960    /// monitoring task of the *other* run; this call has no readiness channel
961    /// of its own to await.
962    async fn await_running_oneshot(
963        &self,
964        id: &DaemonId,
965        wait: Option<OneshotWait>,
966        watched_pid: u32,
967    ) -> IpcResponse {
968        let interval = settings().supervisor_ready_check_interval();
969        // The caller resolved this from the project's settings and sent it, so
970        // both processes wait exactly as long. Falling back to this process's
971        // own settings would read the directory the supervisor happens to have
972        // started in, where a project's `oneshot_timeout` is not visible — and
973        // the shorter of the two deadlines would silently win, releasing
974        // dependents while the task was still running.
975        //
976        // `None` here means the setting asked for no limit, so there is no
977        // deadline to reach rather than a distant one.
978        // One deadline for the whole wait, retries and backoffs included.
979        // `oneshot_timeout` is documented as the longest `pitchfork start` will
980        // wait, and the client bounds its own request by the same value without
981        // restarting it, so a per-attempt budget here would both break that
982        // promise — unboundedly, with infinite retries — and put the two sides
983        // back to disagreeing about when one task has gone on too long.
984        let deadline = wait
985            .unwrap_or_else(|| settings().supervisor_oneshot_wait())
986            .duration()
987            .map(|d| tokio::time::Instant::now() + d);
988        // Which run this wait is reporting on. A terminal state is only that
989        // run's while the record still names its PID or names none at all; once
990        // another PID appears, something else has started the task and the
991        // outcome that follows belongs to that run, not this one. Following the
992        // handoff keeps the answer useful to a dependent — it still learns
993        // whether the task succeeded — without quietly attributing an unrelated
994        // run's failure to the one it asked about.
995        let mut watched_pid = watched_pid;
996        loop {
997            let Some(daemon) = self.get_daemon(id).await else {
998                return IpcResponse::DaemonNotFound;
999            };
1000            if let Some(current) = daemon.pid
1001                && current != watched_pid
1002            {
1003                info!(
1004                    "daemon {id}: the run being waited on (pid {watched_pid}) was replaced by pid {current}; following it"
1005                );
1006                watched_pid = current;
1007            }
1008            match &daemon.status {
1009                DaemonStatus::Completed => {
1010                    info!("daemon {id}: the in-flight oneshot completed");
1011                    return IpcResponse::DaemonReady { daemon };
1012                }
1013                DaemonStatus::Errored(code) => {
1014                    // A failed attempt is persisted before the in-flight `run`
1015                    // sleeps out its backoff, so an errored record with
1016                    // attempts left is a gap between tries rather than the
1017                    // result. Same condition `check_retry` uses to decide
1018                    // whether another attempt is still owed. A disabled daemon
1019                    // is owed none: every retry path checks the disabled set,
1020                    // under the lock `disable` takes, before starting one.
1021                    if daemon.retry.count() > 0
1022                        && daemon.retry_count < daemon.retry.count()
1023                        && !self.state_file.lock().await.disabled.contains(id)
1024                    {
1025                        debug!(
1026                            "daemon {id}: in-flight oneshot failed attempt {} of {}; still waiting",
1027                            daemon.retry_count + 1,
1028                            daemon.retry.count() + 1
1029                        );
1030                    } else {
1031                        // -1 records an unobservable exit code; the caller
1032                        // renders `None` as a plain failure rather than
1033                        // "exit code -1".
1034                        let exit_code = Some(*code).filter(|c| *c != -1);
1035                        return IpcResponse::DaemonFailedWithCode {
1036                            exit_code,
1037                            resolved_ports: daemon.resolved_port.clone(),
1038                        };
1039                    }
1040                }
1041                DaemonStatus::Failed(error) => {
1042                    return IpcResponse::DaemonFailed {
1043                        error: error.clone(),
1044                    };
1045                }
1046                DaemonStatus::Stopped => {
1047                    // Stopped, not completed: the task was interrupted, so it
1048                    // never established what its dependents are waiting for.
1049                    warn!("daemon {id}: the in-flight oneshot was stopped before completing");
1050                    return IpcResponse::DaemonFailedWithCode {
1051                        exit_code: None,
1052                        resolved_ports: daemon.resolved_port.clone(),
1053                    };
1054                }
1055                DaemonStatus::Running
1056                | DaemonStatus::Waiting
1057                | DaemonStatus::Stopping
1058                | DaemonStatus::Restarting => {}
1059            }
1060            if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
1061                warn!("daemon {id}: gave up waiting for the in-flight oneshot to finish");
1062                // Reported as a failure rather than as "already running": the
1063                // batch start path only counts a result carrying an exit code
1064                // as failed, so anything else would let dependents start
1065                // against a task that never finished. 124 is the code a
1066                // readiness timeout already uses.
1067                return IpcResponse::DaemonFailedWithCode {
1068                    exit_code: Some(124),
1069                    resolved_ports: Vec::new(),
1070                };
1071            }
1072            time::sleep(interval).await;
1073        }
1074    }
1075
1076    /// Run a daemon once (single attempt).
1077    ///
1078    /// `stop_guard` is this daemon's stop lock, acquired by `run` before the
1079    /// already-running check. It is held through spawning until the Running
1080    /// state and PID are persisted (or an early failure returns), then dropped
1081    /// before the potentially unbounded readiness wait.
1082    pub(crate) async fn run_once(
1083        &self,
1084        opts: RunOptions,
1085        stop_guard: tokio::sync::OwnedMutexGuard<()>,
1086    ) -> Result<IpcResponse> {
1087        let id = &opts.id;
1088        // Checked under the daemon's stop lock, which `close()` waits out
1089        // after setting the flag: a start that took the lock first finishes
1090        // before `close()` lists the daemons to stop, and one that takes it
1091        // later stops here. Otherwise a daemon started during shutdown (an IPC
1092        // start, a cron run, a retry) would be left running once the
1093        // supervisor has gone.
1094        if self
1095            .shutting_down
1096            .load(std::sync::atomic::Ordering::Acquire)
1097        {
1098            info!("not starting daemon {id}: the supervisor is shutting down");
1099            return Ok(IpcResponse::DaemonFailed {
1100                error: "the supervisor is shutting down".to_string(),
1101            });
1102        }
1103        // Settings can change while a foreground start waits between retries.
1104        #[cfg(windows)]
1105        if let Some(response) = self.reject_unsupported_windows_options(&opts).await? {
1106            return Ok(response);
1107        }
1108        let original_cmd = opts.cmd.clone(); // Save original command for persistence
1109
1110        // Create channel for readiness notification if wait_ready is true
1111        let (ready_tx, ready_rx) = if opts.wait_ready {
1112            let (tx, rx) = oneshot::channel();
1113            (Some(tx), Some(rx))
1114        } else {
1115            (None, None)
1116        };
1117
1118        // Check port availability and apply auto-bump if configured
1119        let expected_ports = opts
1120            .port
1121            .as_ref()
1122            .map(|p| p.expect.clone())
1123            .unwrap_or_default();
1124        let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
1125            let port_cfg = opts.port.as_ref().unwrap();
1126            match check_ports_available(
1127                &expected_ports,
1128                port_cfg.auto_bump(),
1129                port_cfg.max_bump_attempts(),
1130            )
1131            .await
1132            {
1133                Ok(resolved) => {
1134                    let ready_port = if let Some(configured_port) =
1135                        opts.ready_port.as_ref().and_then(|p| p.as_port())
1136                    {
1137                        Some(resolve_configured_ready_port(
1138                            configured_port,
1139                            &expected_ports,
1140                            &resolved,
1141                        ))
1142                    } else if opts.ready_output.is_none()
1143                        && opts.ready_http.is_none()
1144                        && opts.ready_cmd.is_none()
1145                        && opts.ready_delay.is_none()
1146                    {
1147                        // No other ready check configured — use the first expected port as a
1148                        // TCP port readiness check so the daemon is considered ready once it
1149                        // starts listening.  Skip port 0 (ephemeral port request).
1150                        resolved.first().copied().filter(|&p| p != 0)
1151                    } else {
1152                        // Another ready check is configured (output/http/cmd/delay).
1153                        // Don't add an implicit TCP port check — it could race and fire
1154                        // before the daemon has produced any output.
1155                        None
1156                    };
1157                    info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
1158                    (resolved, ready_port)
1159                }
1160                Err(e) => {
1161                    error!("daemon {id}: port check failed: {e}");
1162                    // Convert PortError to structured IPC response
1163                    if let Some(port_error) = e.downcast_ref::<PortError>() {
1164                        match port_error {
1165                            PortError::InUse {
1166                                port,
1167                                address,
1168                                process,
1169                                pid,
1170                            } => {
1171                                return Ok(IpcResponse::PortConflict {
1172                                    port: *port,
1173                                    process: process.clone(),
1174                                    pid: *pid,
1175                                    address: address.clone(),
1176                                });
1177                            }
1178                            PortError::NoAvailablePort {
1179                                start_port,
1180                                attempts,
1181                            } => {
1182                                return Ok(IpcResponse::NoAvailablePort {
1183                                    start_port: *start_port,
1184                                    attempts: *attempts,
1185                                });
1186                            }
1187                        }
1188                    }
1189                    return Ok(IpcResponse::DaemonFailed {
1190                        error: e.to_string(),
1191                    });
1192                }
1193            }
1194        } else {
1195            // When ready_port is set without expected_port, check that the port
1196            // is not already occupied.  If another process is listening on it,
1197            // the TCP readiness probe would immediately succeed and pitchfork
1198            // would falsely consider the daemon ready — routing proxy traffic to
1199            // the wrong process.
1200            if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
1201                && port > 0
1202                && let Some((address, pid, process)) = detect_port_conflict(port).await
1203            {
1204                return Ok(IpcResponse::PortConflict {
1205                    port,
1206                    process,
1207                    pid,
1208                    address: Some(address),
1209                });
1210            }
1211            (
1212                Vec::new(),
1213                opts.ready_port.as_ref().and_then(|p| p.as_port()),
1214            )
1215        };
1216
1217        // The program and arguments that start the daemon, before any mise
1218        // wrapping.
1219        // The program and arguments that start the daemon, before any mise
1220        // wrapping, and the script for the shell when `run` is a string.
1221        if let Some(error) = invalid_probe_program(
1222            id,
1223            "ready_cmd",
1224            opts.ready_cmd.as_ref().map(|c| &c.run),
1225        )
1226        .or_else(|| {
1227            invalid_probe_program(id, "health_cmd", opts.health_cmd.as_ref().map(|c| &c.run))
1228        }) {
1229            return Ok(IpcResponse::DaemonFailed { error });
1230        }
1231
1232        let (mut words, script) = if opts.no_shell {
1233            // The argv form of `run`: started as written, with no shell to
1234            // reinterpret quotes, `%`, `&` or anything else in the arguments.
1235            if let Some(error) = invalid_argv_program(id, &original_cmd) {
1236                return Ok(IpcResponse::DaemonFailed { error });
1237            }
1238            (original_cmd.clone(), None)
1239        } else {
1240            // Resolve the shell for this platform into program + args. The run
1241            // script is passed verbatim as the final argument, avoiding the lossy
1242            // split->join round-trip that previously mangled $VAR/glob expansion.
1243            let words = match resolve_shell() {
1244                Ok(parts) => parts,
1245                Err(error) => return Ok(IpcResponse::DaemonFailed { error }),
1246            };
1247            // Use the original run string verbatim; fall back to joining cmd for
1248            // ad-hoc commands (e.g. `pitchfork run -- cmd args`) that have no run string.
1249            // We don't prepend `exec` because it breaks compound commands (e.g. `exec a && b`
1250            // silently drops `b`). Users can add `exec` themselves in the run string.
1251            let script = opts
1252                .run
1253                .clone()
1254                .unwrap_or_else(|| shell_words::join(&original_cmd));
1255            (words, Some(script))
1256        };
1257
1258        let mise_bin = if opts.mise.unwrap_or(settings().general.mise) {
1259            let mise_bin = settings().resolve_daemon_mise_bin(opts.mise_bin.as_deref());
1260            if mise_bin.is_none() {
1261                warn!("daemon {id}: mise=true but mise binary not found, running without mise");
1262            }
1263            mise_bin
1264        } else {
1265            None
1266        };
1267        // A command left unrendered for `mise x` is not runnable without it: the
1268        // shell would see the template tags. Fail here, where the binary is
1269        // actually looked up, rather than guessing at render time.
1270        if mise_bin.is_none() && opts.deferred_template_context.is_some() {
1271            return Ok(IpcResponse::DaemonFailed {
1272                error: format!(
1273                    "daemon {id}: the command uses template variables only mise can render, but mise is not enabled or its binary was not found"
1274                ),
1275            });
1276        }
1277        // Started directly, the shell gets its script from `shell_script`.
1278        // Under mise, cmd scripts go through a bridge that restores the raw
1279        // command line after mise has activated the environment. Deferred
1280        // templates keep cmd as the outer program so mise uses cmd quoting.
1281        let script = match &mise_bin {
1282            Some(mise_bin) => {
1283                info!(
1284                    "daemon {id}: wrapping command with mise ({})",
1285                    mise_bin.display()
1286                );
1287                if let Some(script) = script {
1288                    words =
1289                        mise_shell_words(words, script, opts.deferred_template_context.is_some());
1290                }
1291                None
1292            }
1293            None => script,
1294        };
1295        let (program, args) = launch_command(words, mise_bin.as_deref());
1296        #[cfg(unix)]
1297        let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
1298            Ok(identity) => identity,
1299            Err(e) => {
1300                return Ok(IpcResponse::DaemonFailed {
1301                    error: e.to_string(),
1302                });
1303            }
1304        };
1305        info!("run: spawning daemon {id} with {program} {args:?} {script:?}");
1306
1307        // Allocate PTY if configured
1308        #[cfg(unix)]
1309        let pty_pair = if opts.pty.unwrap_or(false) {
1310            match super::pty::openpty() {
1311                Ok(pair) => {
1312                    info!("daemon {id}: allocated PTY (pty = true)");
1313                    Some(pair)
1314                }
1315                Err(e) => {
1316                    warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
1317                    None
1318                }
1319            }
1320        } else {
1321            None
1322        };
1323
1324        // Output reaches the monitoring task either from readers this process
1325        // owns or, when a sink owns the stream, relayed over IPC. The channel is
1326        // created here rather than in that task so it exists before the sink
1327        // starts: a daemon whose very first line matches its readiness pattern
1328        // would otherwise have the match reported with nowhere to deliver it.
1329        let (output_tx, output_rx) = tokio::sync::mpsc::channel::<super::OutputLine>(256);
1330        let mut output_relay = None;
1331
1332        // Set up out-of-process capture before building the command, so the
1333        // daemon can be handed the pipe's write end directly.
1334        let mut sink_pipe = None;
1335        let mut sink_writer = None;
1336        let mut sink_child = None;
1337        if super::log_sink::is_supported(&opts) {
1338            let log_format = opts
1339                .log_format
1340                .clone()
1341                .unwrap_or_else(|| settings().logs.log_format.clone());
1342            let watch_for = super::log_sink::WatchFor::from_opts(id, &opts);
1343            // The token ties this attempt's sink to this attempt's channel, so
1344            // a sink still draining a previous attempt cannot report into it.
1345            let relay_token = if watch_for.is_empty() {
1346                0
1347            } else {
1348                let relay = super::log_sink::OutputRelay::register(id, output_tx.clone());
1349                let token = relay.token();
1350                output_relay = Some(relay);
1351                token
1352            };
1353            match super::log_sink::SinkPipe::new(log_format, watch_for, relay_token) {
1354                Ok((pipe, writer)) => match pipe.start(id) {
1355                    Ok(child) => {
1356                        sink_child = Some(super::log_sink::PendingSink::new(child));
1357                        sink_pipe = Some(pipe);
1358                        sink_writer = Some(writer);
1359                    }
1360                    Err(e) => {
1361                        warn!("could not start log sink for {id}, capturing in-process: {e}");
1362                    }
1363                },
1364                Err(e) => {
1365                    // Fall back to in-process capture rather than refusing to
1366                    // start the daemon.
1367                    warn!("could not create log pipe for {id}, capturing in-process: {e}");
1368                }
1369            }
1370        }
1371
1372        let mut cmd = tokio::process::Command::new(&program);
1373
1374        #[cfg(unix)]
1375        if let Some(ref pair) = pty_pair {
1376            // PTY mode: connect both stdout and stderr to the slave PTY.
1377            // The child uses the slave for stdin/stdout/stderr, and we read
1378            // output from the master.
1379            let slave_file = std::fs::File::from(
1380                pair.slave
1381                    .try_clone()
1382                    .map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
1383            );
1384            cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
1385                |e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
1386            )?));
1387            cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
1388                |e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
1389            )?));
1390            cmd.stderr(std::process::Stdio::from(slave_file));
1391        } else if let Some(writer) = sink_writer.take() {
1392            // Capture belongs to a sibling sink process, so the daemon writes
1393            // to a pipe this process does not read. See supervisor::log_sink.
1394            let dup = writer
1395                .try_clone()
1396                .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1397            cmd.stdout(std::process::Stdio::from(writer))
1398                .stderr(std::process::Stdio::from(dup));
1399        } else {
1400            cmd.stdout(std::process::Stdio::piped())
1401                .stderr(std::process::Stdio::piped());
1402        }
1403
1404        #[cfg(not(unix))]
1405        if let Some(writer) = sink_writer.take() {
1406            let dup = writer
1407                .try_clone()
1408                .map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
1409            cmd.stdout(std::process::Stdio::from(writer))
1410                .stderr(std::process::Stdio::from(dup));
1411        } else {
1412            cmd.stdout(std::process::Stdio::piped())
1413                .stderr(std::process::Stdio::piped());
1414        }
1415
1416        match &script {
1417            Some(script) => cmd.shell_script(&program, &args, script),
1418            None => cmd.args(&args),
1419        };
1420        cmd.current_dir(&opts.dir)
1421            .hide_console_window()
1422            .close_inherited_fds();
1423
1424        #[cfg(unix)]
1425        if pty_pair.is_none() {
1426            cmd.stdin(std::process::Stdio::null());
1427        }
1428
1429        #[cfg(not(unix))]
1430        cmd.stdin(std::process::Stdio::null());
1431
1432        // Before the runtime env, so a daemon's own `env` entries win.
1433        #[cfg(unix)]
1434        apply_identity_env(&mut cmd, &run_identity);
1435        apply_runtime_env(
1436            &mut cmd,
1437            id,
1438            opts.retry_count,
1439            opts.env.as_ref(),
1440            &resolved_ports,
1441        );
1442        // After the daemon's own env, since `mise x` needs exactly this value.
1443        if let Some(context) = &opts.deferred_template_context {
1444            cmd.env(crate::template::TEMPLATE_CONTEXT_ENV, context);
1445        }
1446
1447        // Inject proxy-related environment variables
1448        inject_proxy_env(&mut cmd, &daemon_proxy_host(&opts).await);
1449
1450        #[cfg(unix)]
1451        {
1452            let run_identity = run_identity.clone();
1453            let use_pty = pty_pair.is_some();
1454            unsafe {
1455                cmd.pre_exec(move || {
1456                    nix::unistd::setsid().map_err(nix_to_io_error)?;
1457
1458                    // When using a PTY, set the slave as the controlling terminal.
1459                    // The slave FD has already been dup'd onto stdin/stdout/stderr
1460                    // by tokio, so we can use stdin (fd 0) for TIOCSCTTY.
1461                    if use_pty {
1462                        let ret = libc::ioctl(0, libc::TIOCSCTTY as _, 0);
1463                        if ret < 0 {
1464                            // Non-fatal: the process can still run without
1465                            // a controlling terminal.
1466                            #[cfg(target_os = "linux")]
1467                            eprintln!(
1468                                "pitchfork: TIOCSCTTY failed: {}",
1469                                std::io::Error::last_os_error()
1470                            );
1471                        }
1472                    }
1473
1474                    apply_run_identity(&run_identity)?;
1475                    Ok(())
1476                });
1477            }
1478        }
1479
1480        // Timestamp the run so a failed start can wait for this attempt's output
1481        // specifically, rather than seeing an earlier attempt's.
1482        let spawn_time = chrono::Local::now();
1483        // A sink is already running at this point. Both bail-outs below have to
1484        // reap it explicitly: dropping the handle only reaps on a best-effort
1485        // basis, and run_once runs once per retry attempt, so a daemon that
1486        // consistently fails to spawn would otherwise accumulate sinks.
1487        // A failed spawn returns here; the sink is terminated by PendingSink.
1488        let mut child = cmd.spawn().into_diagnostic()?;
1489        // In a job of its own, so its whole process tree can be stopped; see
1490        // `win_job`.
1491        #[cfg(windows)]
1492        if let (Some(pid), Some(process)) = (child.id(), child.raw_handle()) {
1493            crate::win_job::contain_spawned(process as _, pid);
1494        }
1495        let spawned_pid = child.id();
1496        // Register the daemon as monitored BEFORE persisting the Running
1497        // state. The orphan reconciler treats any running, unmonitored PID
1498        // as an orphan; if the state became visible first, a concurrent
1499        // reconciliation pass could adopt — or under the kill policy,
1500        // terminate — a daemon that was just legitimately started. The RAII
1501        // guard unregisters on any early-error path below and is otherwise
1502        // handed to the monitoring task. Registered as soon as the process
1503        // exists, so a supervisor forced to exit while this start is still
1504        // on its way to recording it kills it (see `force_exit`).
1505        let monitored_guard =
1506            spawned_pid.map(|pid| super::adopt::MonitoredGuard::register(id.clone(), pid));
1507        // A process now exists, which is exactly what `last_cron_run` records.
1508        // Written here rather than from the watcher's view of the response
1509        // because that view cannot tell a start that failed before spawning
1510        // from one that spawned and exited before its PID could be read: a
1511        // port conflict, an unresolvable shell and an instant exit all report
1512        // `DaemonFailed`. Only the last of those ran, and a cron job that
1513        // fails that fast is precisely the one whose timing a user needs.
1514        // Ordered before the `Running` upsert below, which inherits it.
1515        //
1516        // Written synchronously rather than left to the background flush, for
1517        // the same reason `last_cron_triggered` is: a supervisor that dies in
1518        // the window between the two would come back with no record that this
1519        // run happened, and for a short-lived job that window is as long as
1520        // the job itself. A scheduled spawn is rare enough -- at most one per
1521        // `cron_check_interval` -- for the extra write to cost nothing.
1522        if opts.cron_started {
1523            let mut state_file = self.state_file.lock().await;
1524            if state_file.set_last_cron_run(id, spawn_time)
1525                && let Err(e) = state_file.write()
1526            {
1527                error!("failed to persist last_cron_run for daemon {id}: {e}");
1528            }
1529        }
1530        let (pid, monitored_guard) = match (spawned_pid, monitored_guard) {
1531            (Some(p), Some(guard)) => (p, guard),
1532            _ => {
1533                warn!("Daemon {id} exited before PID could be captured");
1534                // Unlike a daemon that never started, this one ran and may have
1535                // said why it gave up, and its output is the only diagnosis
1536                // available. Its write end is already closed, so the sink is on
1537                // its way to end of file: let it finish writing before reporting,
1538                // then reap whatever is left of it.
1539                if sink_child.is_some() {
1540                    super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
1541                }
1542                return Ok(IpcResponse::DaemonFailed {
1543                    error: "Process exited immediately".to_string(),
1544                });
1545            }
1546        };
1547        info!("started daemon {id} with pid {pid}");
1548        PROCS.refresh_pids(&[pid]);
1549        let monitor_token = monitored_guard.token();
1550
1551        // Hand the retained read end to a sink and keep one running for as long
1552        // as this daemon is monitored.
1553        let using_sink = sink_pipe.is_some();
1554        // Take the sink out of the guard only once there is a pipe to supervise
1555        // it with, so it is never left running unsupervised.
1556        if let Some(pipe) = sink_pipe.take()
1557            && let Some(child) = sink_child.as_mut().and_then(|pending| pending.take())
1558        {
1559            pipe.supervise(id.clone(), monitor_token, child);
1560        }
1561        // The attempt's actual resolved ports, captured before the upsert
1562        // moves them into state. Hooks, readiness probes, and the failure
1563        // response must reflect this attempt: the state merge keeps the
1564        // existing resolved_port when an update is empty, so a no-port
1565        // attempt would otherwise inherit a previous run's stale ports
1566        // through the upserted record.
1567        let attempt_resolved_ports = resolved_ports.clone();
1568        let daemon = self
1569            .upsert_daemon(
1570                UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
1571                    .set(|o| {
1572                        o.pid = Some(pid);
1573                        o.cmd = Some(original_cmd);
1574                        o.ready_port = effective_ready_port.map(|p| ReadyPort {
1575                            port: Some(p),
1576                            template: None,
1577                            timeout: opts.ready_port.as_ref().and_then(|rp| rp.timeout),
1578                        });
1579                        o.port = crate::config_types::PortConfig::from_parts(
1580                            expected_ports,
1581                            opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
1582                        );
1583                        o.resolved_port = Some(resolved_ports);
1584                    })
1585                    .build(),
1586            )
1587            .await?;
1588
1589        // Running state and PID are now persisted: concurrent run/stop calls
1590        // observe a running daemon and behave correctly, so release the stop
1591        // lock rather than holding it through the readiness wait below, which
1592        // can take arbitrarily long.
1593        drop(stop_guard);
1594
1595        let id_clone = id.clone();
1596        // A oneshot is ready only when its process exits 0, so no readiness
1597        // check may run alongside it — one that fired first would report the
1598        // task ready before it had done its work, and would suppress the
1599        // completion notification entirely. Config load rejects explicit
1600        // `ready_*` fields and the client clears CLI overrides, but the
1601        // implicit port check is derived here from `port.expect`, so the
1602        // suppression has to happen here rather than being trusted to callers.
1603        let ready_delay = (!opts.oneshot).then_some(opts.ready_delay).flatten();
1604        let ready_output = (!opts.oneshot).then(|| opts.ready_output.clone()).flatten();
1605        let ready_http = (!opts.oneshot).then(|| opts.ready_http.clone()).flatten();
1606        let ready_port = (!opts.oneshot).then_some(effective_ready_port).flatten();
1607        let implicit_ready_port = ready_port.map(|p| ReadyPort {
1608            port: Some(p),
1609            template: None,
1610            timeout: None,
1611        });
1612        let ready_port_config = (!opts.oneshot)
1613            .then(|| opts.ready_port.clone())
1614            .flatten()
1615            .or(implicit_ready_port);
1616        let ready_cmd = (!opts.oneshot).then(|| opts.ready_cmd.clone()).flatten();
1617        let daemon_dir = opts.dir.0.clone();
1618        let hook_dirs =
1619            super::hooks::HookDirs::new(daemon_dir.clone(), opts.watch_base_dir.clone());
1620        let hook_retry_count = opts.retry_count;
1621        let hook_retry = opts.retry;
1622        let hook_daemon_env = opts.env.clone();
1623        // Ports of THIS attempt, snapshotted before the monitor starts: a retry
1624        // or restart may replace state.resolved_port before a hook task runs.
1625        // Sourced from the attempt's local value, not the upserted record —
1626        // the state merge inherits stale ports for a no-port attempt.
1627        let hook_resolved_ports = attempt_resolved_ports.clone();
1628        let readiness_daemon_env = opts.env.clone();
1629        let readiness_resolved_ports = attempt_resolved_ports.clone();
1630        let on_output_hook = opts.on_output_hook.clone();
1631        // Whether this daemon has any port-related config — used to skip the
1632        // active_port detection task for daemons that never bind a port (e.g. `sleep 60`).
1633        // When the proxy is enabled, only detect active_port for daemons that are
1634        // actually referenced by a registered slug, rather than blanket-polling every
1635        // daemon (which wastes ~7.5 s of listeners::get_all() calls per port-less daemon).
1636        let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
1637            || (settings().proxy.enable && is_daemon_slug_target(id));
1638        // When the ready_port check succeeds on the first resolved port we can
1639        // set active_port directly instead
1640        // of spawning detect_and_store_active_port (which relies on
1641        // listeners::get_all() + process-tree traversal and is unreliable on
1642        // Windows where Git Bash PID mapping can break descendant lookups).
1643        let daemon_pid = pid;
1644
1645        // Prepare output readers before spawning the monitoring task.
1646        // In PTY mode, we read from the PTY master FD.
1647        // In pipe mode, we read from separate stdout/stderr pipes.
1648        #[cfg(unix)]
1649        let pty_reader = pty_pair.map(|p| {
1650            tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
1651        });
1652        #[cfg(not(unix))]
1653        let pty_reader: Option<tokio::io::BufReader<tokio::fs::File>> = None;
1654        let stdout_reader = if pty_reader.is_none() {
1655            child.stdout.take().map(tokio::io::BufReader::new)
1656        } else {
1657            None
1658        };
1659        let stderr_reader = if pty_reader.is_none() {
1660            child.stderr.take().map(tokio::io::BufReader::new)
1661        } else {
1662            None
1663        };
1664
1665        if !using_sink
1666            && pty_reader.is_none()
1667            && (stdout_reader.is_none() || stderr_reader.is_none())
1668        {
1669            error!("Failed to capture stdout/stderr for daemon {id}");
1670        }
1671
1672        tokio::spawn(async move {
1673            let id = id_clone;
1674            // Registered before the Running upsert above; unregisters when
1675            // this monitoring task ends.
1676            let _monitored_guard = monitored_guard;
1677            // Likewise for sink-relayed output: dropping this stops the
1678            // supervisor delivering into a channel nobody is reading. Dropped
1679            // explicitly once the daemon exits, before the drain below.
1680            let output_relay = output_relay;
1681
1682            // Merge all output sources (PTY master OR stdout+stderr, or a
1683            // sink's IPC reports) into a single channel.
1684            let mut output_rx = output_rx;
1685
1686            if let Some(reader) = pty_reader {
1687                // PTY mode: single merged stream from the master.
1688                // output_tx is moved into the spawn; when the reader ends the
1689                // channel closes automatically.
1690                tokio::spawn(forward_output_lines(reader, output_tx));
1691            } else {
1692                // Pipe mode: stdout and stderr are merged into the same channel.
1693                // Both `ready_output` and `on_output_hook` patterns match against
1694                // lines from either stream, which is the expected behavior (a
1695                // "server ready" message may appear on stderr in some tools).
1696                if let Some(stdout) = stdout_reader {
1697                    tokio::spawn(forward_output_lines(stdout, output_tx.clone()));
1698                }
1699                if let Some(stderr) = stderr_reader {
1700                    tokio::spawn(forward_output_lines(stderr, output_tx.clone()));
1701                }
1702                // Drop the last sender so the channel closes when all readers
1703                // finish. The relay holds its own clone, so a sink's reports
1704                // still have somewhere to go after these end.
1705                drop(output_tx);
1706            }
1707            let log_store = Arc::clone(&LOG_STORE);
1708            let log_format = opts
1709                .log_format
1710                .clone()
1711                .unwrap_or_else(|| crate::settings::settings().logs.log_format.clone());
1712            let parse_line = move |line: &str| crate::log_parse::parse(line, &log_format);
1713
1714            const LOG_BATCH_SIZE: usize = 100;
1715            const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
1716            let mut log_buffer: Vec<crate::log_parse::ParsedLog> =
1717                Vec::with_capacity(LOG_BATCH_SIZE);
1718            let mut log_flush_interval = tokio::time::interval(LOG_FLUSH_INTERVAL);
1719            log_flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1720
1721            let flush_logs =
1722                |buffer: &mut Vec<crate::log_parse::ParsedLog>| -> Option<tokio::task::JoinHandle<()>> {
1723                    if buffer.is_empty() {
1724                        return None;
1725                }
1726                let store = Arc::clone(&log_store);
1727                let id = id.clone();
1728                let batch = std::mem::take(buffer);
1729                Some(tokio::task::spawn_blocking(move || {
1730                    if let Err(e) = store.append_structured_batch(&id, &batch) {
1731                        error!("Failed to write batch to log for daemon {id}: {e}");
1732                    }
1733                }))
1734            };
1735
1736            // SQLite WAL mode provides automatic durability; no explicit flush needed.
1737
1738            // Setup readiness checking
1739            let mut ready_notified = false;
1740            // Set when a oneshot's process exits 0. Its readiness *is* its
1741            // completion, so the notification is held back until the
1742            // `completed` state has been persisted — a caller that returns
1743            // from `pitchfork start` must not still see the daemon running.
1744            let mut oneshot_completion_pending = false;
1745            let mut ready_tx = ready_tx;
1746            let ready_pattern = ready_output
1747                .as_ref()
1748                .and_then(|o| get_or_compile_regex(&o.pattern));
1749            // Track whether we've already spawned the active_port detection task
1750            let mut active_port_spawned = false;
1751
1752            // Validate on_output config early; discard the hook on any error so
1753            // a bad regex does not silently fall through to the (None, None) => true
1754            // match arm and fire on every line.
1755            let on_output_hook = match on_output_hook {
1756                Some(ref hook) => match hook.validate(id.name()) {
1757                    Ok(()) => on_output_hook,
1758                    Err(e) => {
1759                        error!("{e}");
1760                        None
1761                    }
1762                },
1763                None => None,
1764            };
1765
1766            // Compile the regex pattern after validation so we only attempt this
1767            // when the hook is known-good (validate() already checked the syntax).
1768            let on_output_pattern: Option<regex::Regex> = on_output_hook
1769                .as_ref()
1770                .and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
1771            let on_output_debounce = on_output_hook
1772                .as_ref()
1773                .map(|h| h.debounce_duration())
1774                .unwrap_or(Duration::from_millis(1000));
1775            // Last time the on_output hook fired; None means it has never fired.
1776            let mut on_output_last_fired: Option<std::time::Instant> = None;
1777
1778            let mut delay_timer =
1779                ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));
1780
1781            // Track exhaustion of timed checks
1782            let mut http_exhausted = false;
1783            let mut cmd_exhausted = false;
1784            let mut port_exhausted = false;
1785            let mut output_exhausted = false;
1786
1787            // Get settings for intervals
1788            let s = settings();
1789            let ready_check_interval = s.supervisor_ready_check_interval();
1790            let http_client_timeout = s.supervisor_http_client_timeout();
1791
1792            // Setup output readiness check deadline
1793            let mut output_deadline = ready_output
1794                .as_ref()
1795                .and_then(|o| o.timeout)
1796                .map(|d| Box::pin(time::sleep(d)));
1797
1798            // Setup HTTP readiness check interval and deadline
1799            let mut http_check_interval = ready_http
1800                .as_ref()
1801                .map(|_| tokio::time::interval(ready_check_interval));
1802            let mut http_deadline = ready_http
1803                .as_ref()
1804                .and_then(|h| h.timeout)
1805                .map(|d| Box::pin(time::sleep(d)));
1806            let http_client = if ready_http.is_some() {
1807                Some(crate::supervisor::health::supervisor_http_client().await)
1808            } else {
1809                None
1810            };
1811
1812            // Setup TCP port readiness check interval and deadline
1813            let mut port_check_interval =
1814                ready_port.map(|_| tokio::time::interval(ready_check_interval));
1815            let mut port_deadline = ready_port_config
1816                .as_ref()
1817                .and_then(|p| p.timeout)
1818                .map(|d| Box::pin(time::sleep(d)));
1819
1820            // Setup command readiness check state. Probes are spawned one at a time;
1821            // a non-zero result triggers a respawn delay, and a timeout stops the probe.
1822            let mut cmd_probe: Option<CmdProbe> = None;
1823            let mut cmd_respawn_delay: Option<_> = None;
1824            let mut cmd_deadline = ready_cmd
1825                .as_ref()
1826                .and_then(|c| c.timeout)
1827                .map(|d| Box::pin(time::sleep(d)));
1828            if let Some(ref cmd) = ready_cmd {
1829                cmd_probe = Some(spawn_cmd_probe(
1830                    &id,
1831                    &cmd.run,
1832                    daemon_dir.as_path(),
1833                    hook_retry_count,
1834                    readiness_daemon_env.as_ref(),
1835                    &readiness_resolved_ports,
1836                ));
1837            }
1838
1839            // Use a channel to communicate process exit status
1840            let (exit_tx, mut exit_rx) =
1841                tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);
1842
1843            // Spawn a task to wait for process exit
1844            let child_pid = child.id().unwrap_or(0);
1845            tokio::spawn(async move {
1846                let result = child.wait().await;
1847                // On non-Linux Unix (e.g. macOS) the zombie reaper may win the
1848                // race and consume the exit status via waitpid(None, WNOHANG)
1849                // before Tokio's child.wait() gets to it. When that happens,
1850                // Tokio returns an ECHILD io::Error. We recover by checking
1851                // REAPED_STATUSES for the stashed exit code.
1852                //
1853                // On Linux this is unnecessary because the reaper uses
1854                // waitid(WNOWAIT) to peek before reaping, which avoids the
1855                // race entirely.
1856                #[cfg(all(unix, not(target_os = "linux")))]
1857                let result = match &result {
1858                    Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
1859                        if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
1860                            warn!(
1861                                "daemon pid {child_pid} wait() got ECHILD; \
1862                                 recovered exit code {code} from zombie reaper"
1863                            );
1864                            // Synthesize an ExitStatus from the stashed code.
1865                            // On Unix we can use `ExitStatus::from_raw()` with
1866                            // a wait-style status word (code << 8 for normal
1867                            // exit, or raw signal number for signal death).
1868                            use std::os::unix::process::ExitStatusExt;
1869                            if code >= 0 {
1870                                Ok(std::process::ExitStatus::from_raw(code << 8))
1871                            } else {
1872                                // Negative code means killed by signal (-sig)
1873                                Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
1874                            }
1875                        } else {
1876                            warn!(
1877                                "daemon pid {child_pid} wait() got ECHILD but no \
1878                                 stashed status found; reporting as error"
1879                            );
1880                            result
1881                        }
1882                    }
1883                    _ => result,
1884                };
1885                debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
1886                let _ = exit_tx.send(result).await;
1887            });
1888
1889            #[allow(unused_assignments)]
1890            // Initial None is a safety net; loop only exits via exit_rx.recv() which sets it
1891            let mut exit_status = None;
1892
1893            // If there is no ready check of any kind and no delay, the daemon is
1894            // considered immediately ready and the active_port detection task would
1895            // never be triggered inside the select loop.  Kick it off right away so
1896            // that daemons without any readiness configuration still get their
1897            // active_port populated (needed for proxy routing).
1898            if has_port_config
1899                && ready_pattern.is_none()
1900                && ready_http.is_none()
1901                && ready_port.is_none()
1902                && ready_cmd.is_none()
1903                && delay_timer.is_none()
1904            {
1905                active_port_spawned = true;
1906                detect_and_store_active_port(id.clone(), daemon_pid);
1907            }
1908
1909            // Set when readiness checks exhaust. The group kill runs as a
1910            // separate task so this loop can exit and the post-loop drain
1911            // keeps consuming output — children logging during SIGTERM
1912            // cleanup would otherwise block on a full pipe and never exit.
1913            // The ready failure is only sent once the kill task completes,
1914            // so the retry loop cannot respawn into the dying group.
1915            let mut ready_fail_kill: Option<tokio::task::JoinHandle<()>> = None;
1916
1917            loop {
1918                // biased: evaluate in exit → output → delay order so that
1919                // process exit pre-empts both buffered output and the delay
1920                // timer, preventing a dead daemon from being marked ready.
1921                select! {
1922                    biased;
1923                    Some(result) = exit_rx.recv() => {
1924                        // Process exited - save exit status and notify if not ready yet
1925                        exit_status = Some(result);
1926                        debug!("daemon {id} process exited, exit_status: {exit_status:?}");
1927                        if !ready_notified {
1928                            // Check if process exited successfully
1929                            let is_success = exit_status.as_ref()
1930                                .and_then(|r| r.as_ref().ok())
1931                                .map(|s| s.success())
1932                                .unwrap_or(false);
1933                            if is_success && opts.oneshot {
1934                                debug!("daemon {id} completed, deferring success notification until the completed state is persisted");
1935                                oneshot_completion_pending = true;
1936                            } else if let Some(tx) = ready_tx.take() {
1937                                if is_success {
1938                                    debug!("daemon {id} exited successfully before ready check, sending success notification");
1939                                    let _ = tx.send(Ok(()));
1940                                } else {
1941                                    let exit_code = exit_status.as_ref()
1942                                        .and_then(|r| r.as_ref().ok())
1943                                        .and_then(|s| s.code());
1944                                    debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
1945                                    let _ = tx.send(Err(exit_code));
1946                                }
1947                            }
1948                        } else {
1949                            debug!("daemon {id} was already marked ready, not sending notification");
1950                        }
1951                        break;
1952                    },
1953                    Some(super::OutputLine { text: line, source }) = output_rx.recv() => {
1954                        // A line relayed by a sink is already in the store —
1955                        // the sink wrote and flushed it before reporting it —
1956                        // so it arrives here only to be acted on.
1957                        if matches!(source, super::OutputSource::Local) {
1958                            let parsed = parse_line(&line);
1959                            log_buffer.push(parsed);
1960                            if log_buffer.len() >= LOG_BATCH_SIZE {
1961                                let _ = flush_logs(&mut log_buffer);
1962                            }
1963                        }
1964                        trace!("output: {id} {line}");
1965
1966                        // Strip ANSI for pattern matching so user-written patterns
1967                        // work regardless of whether the process emits color codes.
1968                        let line_clean = console::strip_ansi_codes(&line).to_string();
1969
1970                        // Check if output matches ready pattern
1971                        if !ready_notified
1972                            && !output_exhausted
1973                            && let Some(ref pattern) = ready_pattern
1974                            && pattern.is_match(&line_clean)
1975                        {
1976                            // Flush buffered logs synchronously before signalling
1977                            // readiness, so collect_startup_logs sees the line
1978                            // that triggered the match (and any co-buffered lines)
1979                            // in SQLite.
1980                            if let Some(handle) = flush_logs(&mut log_buffer) {
1981                                let _ = handle.await;
1982                            }
1983                            info!("daemon {id} ready: output matched pattern");
1984                            ready_notified = true;
1985                            if let Some(tx) = ready_tx.take() {
1986                                let _ = tx.send(Ok(()));
1987                            }
1988                            fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
1989                            stop_cmd_probe_state(&mut cmd_probe);
1990                            http_deadline = None;
1991                            cmd_deadline = None;
1992                            port_deadline = None;
1993                            output_deadline = None;
1994                            if !active_port_spawned && has_port_config {
1995                                active_port_spawned = true;
1996                                detect_and_store_active_port(id.clone(), daemon_pid);
1997                            }
1998                        }
1999
2000                        // Check on_output hook. A sink has already applied the
2001                        // filter, and says so per line: a line reported only
2002                        // because it announced readiness must not fire a hook
2003                        // that filters for something else.
2004                        if let Some(ref hook) = on_output_hook {
2005                            let matched = match source {
2006                                super::OutputSource::Sink { fires_hook } => fires_hook,
2007                                super::OutputSource::Local => match (&hook.filter, &on_output_pattern) {
2008                                    (Some(substr), _) => line_clean.contains(substr.as_str()),
2009                                    (None, Some(re)) => re.is_match(&line_clean),
2010                                    (None, None) => true,
2011                                },
2012                            };
2013                            if matched {
2014                                // The debounce is applied here as well as in the
2015                                // sink. A replacement sink starts with a fresh
2016                                // clock, and would otherwise let the hook fire
2017                                // twice inside one configured window.
2018                                let now = std::time::Instant::now();
2019                                let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
2020                                if elapsed.is_none_or(|e| e >= on_output_debounce) {
2021                                    on_output_last_fired = Some(now);
2022                                    hooks::fire_output_hook(id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), hook.run.clone(), line_clean.clone()).await;
2023                                }
2024                            }
2025                        }
2026                        // Yield briefly so that the output readiness deadline can be
2027                        // evaluated even when output is produced continuously.
2028                        tokio::task::yield_now().await;
2029                    }
2030                    _ = async {
2031                        if let Some(ref mut deadline) = http_deadline {
2032                            deadline.await;
2033                        } else {
2034                            std::future::pending::<()>().await;
2035                        }
2036                    }, if !ready_notified && ready_http.is_some() => {
2037                        http_exhausted = true;
2038                        http_deadline = None;
2039                        http_check_interval = None;
2040                        warn!("daemon {id}: HTTP readiness check timed out");
2041                        let any_remaining = any_ready_check_remaining(
2042                            ready_output.as_ref(),
2043                            output_exhausted,
2044                            ready_port_config.as_ref(),
2045                            port_exhausted,
2046                            ready_http.as_ref(),
2047                            http_exhausted,
2048                            ready_cmd.as_ref(),
2049                            cmd_exhausted,
2050                        );
2051                        if !any_remaining {
2052                            error!("daemon {id}: all readiness checks exhausted, failing");
2053                            stop_cmd_probe_state(&mut cmd_probe);
2054                            ready_fail_kill = Some(spawn_ready_fail_kill(
2055                                id.clone(),
2056                                daemon_pid,
2057                                opts.stop_signal.unwrap_or_default(),
2058                            ));
2059                            break;
2060                        }
2061                    }
2062                    _ = async {
2063                        if let Some(ref mut deadline) = output_deadline {
2064                            deadline.await;
2065                        } else {
2066                            std::future::pending::<()>().await;
2067                        }
2068                    }, if !ready_notified && ready_output.is_some() => {
2069                        output_exhausted = true;
2070                        output_deadline = None;
2071                        warn!("daemon {id}: output readiness check timed out");
2072                        let any_remaining = any_ready_check_remaining(
2073                            ready_output.as_ref(),
2074                            output_exhausted,
2075                            ready_port_config.as_ref(),
2076                            port_exhausted,
2077                            ready_http.as_ref(),
2078                            http_exhausted,
2079                            ready_cmd.as_ref(),
2080                            cmd_exhausted,
2081                        );
2082                        if !any_remaining {
2083                            error!("daemon {id}: all readiness checks exhausted, failing");
2084                            stop_cmd_probe_state(&mut cmd_probe);
2085                            ready_fail_kill = Some(spawn_ready_fail_kill(
2086                                id.clone(),
2087                                daemon_pid,
2088                                opts.stop_signal.unwrap_or_default(),
2089                            ));
2090                            break;
2091                        }
2092                    }
2093                    _ = async {
2094                        if let Some(ref mut interval) = http_check_interval {
2095                            interval.tick().await;
2096                        } else {
2097                            std::future::pending::<()>().await;
2098                        }
2099                    }, if !ready_notified && ready_http.is_some() && !http_exhausted => {
2100                        if let (Some(http), Some(client)) = (&ready_http, &http_client) {
2101                            match client.get(&http.url).timeout(http_client_timeout).send().await {
2102                                Ok(response) if http.accepts_status(response.status().as_u16()) => {
2103                                    info!("daemon {id} ready: HTTP check passed (status {})", response.status());
2104                                    ready_notified = true;
2105                                    if let Some(tx) = ready_tx.take() {
2106                                        let _ = tx.send(Ok(()));
2107                                    }
2108                                    fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2109                                    http_check_interval = None;
2110                                    http_deadline = None;
2111                                    stop_cmd_probe_state(&mut cmd_probe);
2112                                    cmd_deadline = None;
2113                                    port_deadline = None;
2114                                    output_deadline = None;
2115                                    if !active_port_spawned && has_port_config {
2116                                        active_port_spawned = true;
2117                                        detect_and_store_active_port(id.clone(), daemon_pid);
2118                                    }
2119                                }
2120                                Ok(response) => {
2121                                    trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
2122                                }
2123                                Err(e) => {
2124                                    trace!("daemon {id} HTTP check failed: {e}");
2125                                }
2126                            }
2127                        }
2128                    }
2129                    _ = async {
2130                        if let Some(ref mut deadline) = port_deadline {
2131                            deadline.await;
2132                        } else {
2133                            std::future::pending::<()>().await;
2134                        }
2135                    }, if !ready_notified && ready_port.is_some() => {
2136                        port_exhausted = true;
2137                        port_deadline = None;
2138                        port_check_interval = None;
2139                        warn!("daemon {id}: TCP port readiness check timed out");
2140                        let any_remaining = any_ready_check_remaining(
2141                            ready_output.as_ref(),
2142                            output_exhausted,
2143                            ready_port_config.as_ref(),
2144                            port_exhausted,
2145                            ready_http.as_ref(),
2146                            http_exhausted,
2147                            ready_cmd.as_ref(),
2148                            cmd_exhausted,
2149                        );
2150                        if !any_remaining {
2151                            error!("daemon {id}: all readiness checks exhausted, failing");
2152                            stop_cmd_probe_state(&mut cmd_probe);
2153                            ready_fail_kill = Some(spawn_ready_fail_kill(
2154                                id.clone(),
2155                                daemon_pid,
2156                                opts.stop_signal.unwrap_or_default(),
2157                            ));
2158                            break;
2159                        }
2160                    }
2161                    _ = async {
2162                        if let Some(ref mut interval) = port_check_interval {
2163                            interval.tick().await;
2164                        } else {
2165                            std::future::pending::<()>().await;
2166                        }
2167                    }, if !ready_notified && ready_port.is_some() && !port_exhausted => {
2168                        if let Some(port) = ready_port {
2169                            match tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
2170                                Ok(_) => {
2171                                    info!("daemon {id} ready: TCP port {port} is listening");
2172                                    ready_notified = true;
2173                                    if let Some(tx) = ready_tx.take() {
2174                                        let _ = tx.send(Ok(()));
2175                                    }
2176                                    fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2177                                    // Stop checking once ready
2178                                    port_check_interval = None;
2179                                    port_deadline = None;
2180                                    stop_cmd_probe_state(&mut cmd_probe);
2181                                    http_deadline = None;
2182                                    cmd_deadline = None;
2183                                    output_deadline = None;
2184                                    if !active_port_spawned && has_port_config {
2185                                        active_port_spawned = true;
2186                                        // ready_port check just TCP-connected to this
2187                                        // port, so it is definitely listening. If it
2188                                        // matches the first resolved port, write
2189                                        // active_port directly instead of spawning
2190                                        // detect_and_store_active_port, which sleeps
2191                                        // 500 ms then relies on listeners::get_all()
2192                                        // + process-tree traversal — unreliable on
2193                                        // Windows where Git Bash PID mapping can
2194                                        // break descendant lookups.
2195                                        if let Some(active_port) = active_port_from_ready_port(
2196                                            port,
2197                                            &readiness_resolved_ports,
2198                                        ) {
2199                                            let mut state_file =
2200                                                SUPERVISOR.state_file.lock().await;
2201                                            if let Some(d) = state_file.daemons.get(&id)
2202                                                && d.pid == Some(daemon_pid)
2203                                            {
2204                                                state_file.set_active_port(&id, active_port);
2205                                            }
2206                                        } else {
2207                                            detect_and_store_active_port(
2208                                                id.clone(),
2209                                                daemon_pid,
2210                                            );
2211                                        }
2212                                    }
2213                                }
2214                                Err(_) => {
2215                                    trace!("daemon {id} port check: port {port} not listening yet");
2216                                }
2217                            }
2218                        }
2219                    }
2220                    _ = async {
2221                        if let Some(ref mut delay) = cmd_respawn_delay {
2222                            delay.await;
2223                        } else {
2224                            std::future::pending::<()>().await;
2225                        }
2226                    }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted && cmd_probe.is_none() => {
2227                        if let Some(ref cmd) = ready_cmd {
2228                            cmd_probe = Some(spawn_cmd_probe(
2229                                &id,
2230                                &cmd.run,
2231                                daemon_dir.as_path(),
2232                                hook_retry_count,
2233                                readiness_daemon_env.as_ref(),
2234                                &readiness_resolved_ports,
2235                            ));
2236                        }
2237                        cmd_respawn_delay = None;
2238                    }
2239                    result = async {
2240                        if let Some(probe) = cmd_probe.as_mut() {
2241                            std::pin::Pin::new(&mut probe.result_rx).await
2242                        } else {
2243                            std::future::pending::<Result<Result<std::process::ExitStatus, std::io::Error>, tokio::sync::oneshot::error::RecvError>>().await
2244                        }
2245                    }, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted => {
2246                        // The probe task has finished; remove the handle so it is not
2247                        // cancelled or reused. This must happen only after this branch
2248                        // actually wins the select, not while constructing the future.
2249                        let _ = cmd_probe.take();
2250                        match result {
2251                            Ok(Ok(status)) if status.success() => {
2252                                info!("daemon {id} ready: readiness command succeeded");
2253                                ready_notified = true;
2254                                if let Some(tx) = ready_tx.take() {
2255                                    let _ = tx.send(Ok(()));
2256                                }
2257                                fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2258                                cmd_respawn_delay = None;
2259                                cmd_deadline = None;
2260                                http_deadline = None;
2261                                port_deadline = None;
2262                                output_deadline = None;
2263                                if !active_port_spawned && has_port_config {
2264                                    active_port_spawned = true;
2265                                    detect_and_store_active_port(id.clone(), daemon_pid);
2266                                }
2267                            }
2268                            Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {
2269                                trace!("daemon {id} cmd check: command not ready, will respawn");
2270                                cmd_respawn_delay = Some(Box::pin(time::sleep(ready_check_interval)));
2271                            }
2272                        }
2273                    }
2274                    _ = async {
2275                        if let Some(ref mut deadline) = cmd_deadline {
2276                            deadline.await;
2277                        } else {
2278                            std::future::pending::<()>().await;
2279                        }
2280                    }, if !ready_notified && ready_cmd.is_some() => {
2281                        cmd_exhausted = true;
2282                        cmd_deadline = None;
2283                        stop_cmd_probe_state(&mut cmd_probe);
2284                        cmd_respawn_delay = None;
2285                        warn!("daemon {id}: command readiness check timed out");
2286                        let any_remaining = any_ready_check_remaining(
2287                            ready_output.as_ref(),
2288                            output_exhausted,
2289                            ready_port_config.as_ref(),
2290                            port_exhausted,
2291                            ready_http.as_ref(),
2292                            http_exhausted,
2293                            ready_cmd.as_ref(),
2294                            cmd_exhausted,
2295                        );
2296                        if !any_remaining {
2297                            error!("daemon {id}: all readiness checks exhausted, failing");
2298                            ready_fail_kill = Some(spawn_ready_fail_kill(
2299                                id.clone(),
2300                                daemon_pid,
2301                                opts.stop_signal.unwrap_or_default(),
2302                            ));
2303                            break;
2304                        }
2305                    }
2306                    _ = async {
2307                        if let Some(ref mut timer) = delay_timer {
2308                            timer.await;
2309                        } else {
2310                            std::future::pending::<()>().await;
2311                        }
2312                    } => {
2313                        let has_other_ready_check = ready_pattern.is_some()
2314                            || ready_http.is_some()
2315                            || ready_port.is_some()
2316                            || ready_cmd.is_some();
2317                        let delay_is_only_readiness = !ready_notified && !has_other_ready_check;
2318                        let process_exited = exit_status.is_some();
2319                        let process_running = if delay_is_only_readiness && !process_exited {
2320                            // Force-refresh sysinfo for this PID before checking.
2321                            // On Windows, the cached process list may be stale.
2322                            PROCS.refresh_pids(&[daemon_pid]);
2323                            PROCS.is_running(daemon_pid)
2324                        } else {
2325                            false
2326                        };
2327
2328                        if delay_readiness_succeeded(
2329                            ready_notified,
2330                            has_other_ready_check,
2331                            process_exited,
2332                            process_running,
2333                        ) {
2334                            info!("daemon {id} ready: delay elapsed");
2335                            ready_notified = true;
2336                            if let Some(tx) = ready_tx.take() {
2337                                let _ = tx.send(Ok(()));
2338                            }
2339                            fire_hook(HookType::OnReady, id.clone(), hook_dirs.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
2340                            if !active_port_spawned && has_port_config {
2341                                active_port_spawned = true;
2342                                detect_and_store_active_port(id.clone(), daemon_pid);
2343                            }
2344                        } else if delay_is_only_readiness {
2345                            if process_exited {
2346                                debug!("daemon {id} exited during ready_delay, not marking as ready");
2347                            } else {
2348                                debug!("daemon {id} pid {daemon_pid} not running during ready_delay, deferring to exit handler");
2349                            }
2350                        }
2351
2352                        if delay_is_only_readiness {
2353                            // Clear all deadlines — no other checks are configured
2354                            // when delay fires as readiness, but clear defensively.
2355                            output_deadline = None;
2356                            http_deadline = None;
2357                            cmd_deadline = None;
2358                            port_deadline = None;
2359                            stop_cmd_probe_state(&mut cmd_probe);
2360                        }
2361                        // Disable timer after it fires
2362                        delay_timer = None;
2363                    }
2364                    _ = log_flush_interval.tick() => {
2365                        let _ = flush_logs(&mut log_buffer);
2366                    }
2367                }
2368            }
2369
2370            // Snapshot the daemon state BEFORE draining output.
2371            //
2372            // The drain can take up to 5s (e.g. when child processes keep the
2373            // stdout pipe open). During that time, a subsequent start() call
2374            // (e.g. from `pitchfork restart`) can upsert the daemon with a new
2375            // PID and Running status. If we only checked state AFTER the drain,
2376            // the monitoring task would see d.pid != Some(old_pid) && !is_stopped()
2377            // && !is_stopping() and return early without firing on_stop/on_exit
2378            // hooks.
2379            //
2380            // By snapshotting is_stopping before the drain, we preserve the
2381            // knowledge that stop() was called, so hooks fire correctly even
2382            // if start() has since changed the state.
2383            let pre_drain_daemon = SUPERVISOR.get_daemon(&id).await;
2384            let pre_drain_is_stopping = pre_drain_daemon
2385                .as_ref()
2386                .is_some_and(|d| d.status.is_stopped() || d.status.is_stopping_or_restarting());
2387
2388            // Drain any in-flight output lines that were still in the mpsc
2389            // channel or the OS pipe buffer when the child exited. Without
2390            // this, trailing log lines from short-lived daemons get dropped.
2391            // The reader tasks drop their senders on EOF, so recv() returns
2392            // None when all data has been consumed. A total deadline of 5 s
2393            // guards against a stuck reader (e.g. PTY master FD not closing)
2394            // while ensuring drain doesn't block post-exit cleanup indefinitely.
2395            //
2396            // Stop accepting relayed output first: the relay holds a sender of
2397            // its own, so leaving it registered would keep the channel open and
2398            // make every drain wait out the whole deadline. Readiness is moot
2399            // now anyway — the process has exited.
2400            drop(output_relay);
2401            let drain_deadline = tokio::time::Instant::now() + super::EXIT_OUTPUT_DRAIN_TIMEOUT;
2402            loop {
2403                let now = tokio::time::Instant::now();
2404                if now >= drain_deadline {
2405                    break;
2406                }
2407                let Ok(Some(line)) =
2408                    tokio::time::timeout(drain_deadline - now, output_rx.recv()).await
2409                else {
2410                    break;
2411                };
2412                // Sink-relayed lines are already stored; see the select loop.
2413                if matches!(line.source, super::OutputSource::Local) {
2414                    log_buffer.push(parse_line(&line.text));
2415                }
2416            }
2417            // Flush any remaining log lines (including drained) before the process exits.
2418            // Await the flush to guarantee all buffered logs are persisted before cleanup.
2419            if let Some(handle) = flush_logs(&mut log_buffer) {
2420                let _ = handle.await;
2421            }
2422
2423            // Clear active_port since the process is no longer running
2424            {
2425                let mut state_file = SUPERVISOR.state_file.lock().await;
2426                state_file.clear_active_port(&id);
2427            }
2428
2429            // Get the final exit status
2430            let exit_status = if let Some(status) = exit_status {
2431                status
2432            } else {
2433                // Streams closed but process hasn't exited yet, wait for it
2434                match exit_rx.recv().await {
2435                    Some(status) => status,
2436                    None => {
2437                        warn!("daemon {id} exit channel closed without receiving status");
2438                        Err(std::io::Error::other("exit channel closed"))
2439                    }
2440                }
2441            };
2442
2443            // If the loop exited via readiness exhaustion, wait for the group
2444            // kill to finish before reporting the failure so the retry loop
2445            // (or a waiting client) cannot start a replacement while the old
2446            // process group is still terminating.
2447            if let Some(kill) = ready_fail_kill {
2448                let _ = kill.await;
2449                if let Some(tx) = ready_tx.take() {
2450                    let _ = tx.send(Err(Some(124)));
2451                }
2452            }
2453
2454            let current_daemon = SUPERVISOR.get_daemon(&id).await;
2455
2456            // Signal that this monitoring task is processing its exit path.
2457            // The RAII guard will decrement the counter and notify close()
2458            // when the task finishes (including all fire_hook registrations),
2459            // regardless of which return path is taken.
2460            SUPERVISOR
2461                .active_monitors
2462                .fetch_add(1, atomic::Ordering::Release);
2463            struct MonitorGuard;
2464            impl Drop for MonitorGuard {
2465                fn drop(&mut self) {
2466                    SUPERVISOR
2467                        .active_monitors
2468                        .fetch_sub(1, atomic::Ordering::Release);
2469                    SUPERVISOR.monitor_done.notify_waiters();
2470                }
2471            }
2472            let _monitor_guard = MonitorGuard;
2473            // Check if this monitoring task is for the current daemon process.
2474            // If the daemon was intentionally stopped (pre_drain_is_stopping),
2475            // skip this check — we must still fire on_stop/on_exit hooks even
2476            // if start() has since changed the PID and status.
2477            if !pre_drain_is_stopping
2478                && (current_daemon.is_none()
2479                    || current_daemon.as_ref().is_some_and(|d| {
2480                        d.pid != Some(pid)
2481                            && !d.status.is_stopped()
2482                            && !d.status.is_stopping_or_restarting()
2483                    }))
2484            {
2485                // Another process has taken over, don't update status. The
2486                // task itself did finish, so a caller waiting on it is still
2487                // told so rather than left to time out.
2488                if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2489                    let _ = tx.send(Ok(()));
2490                }
2491                return;
2492            }
2493            // Capture the intentional-stop flag. Combine pre-drain and
2494            // post-drain state to handle both race orders:
2495            //  - stop() set Stopping before drain → pre_drain_is_stopping
2496            //  - stop() set Stopped during drain → current_daemon.is_stopped()
2497            let already_stopped = current_daemon
2498                .as_ref()
2499                .is_some_and(|d| d.status.is_stopped());
2500            let is_stopping = already_stopped
2501                || pre_drain_is_stopping
2502                || current_daemon
2503                    .as_ref()
2504                    .is_some_and(|d| d.status.is_stopping_or_restarting());
2505
2506            // --- Phase 1: Determine exit_code, exit_reason, and update daemon state ---
2507            let (exit_code, exit_reason) = match (&exit_status, is_stopping) {
2508                (Ok(status), true) => {
2509                    // Intentional stop (by pitchfork). status.code() returns None
2510                    // on Unix when killed by signal (e.g. SIGTERM); use -1 to
2511                    // distinguish from a clean exit code 0.
2512                    (status.code().unwrap_or(-1), "stop")
2513                }
2514                (Ok(status), false) if status.success() => (status.code().unwrap_or(-1), "exit"),
2515                (Ok(status), false) => (status.code().unwrap_or(-1), "fail"),
2516                (Err(_), true) => {
2517                    // child.wait() error while stopping (e.g. sysinfo reaped the process)
2518                    (-1, "stop")
2519                }
2520                (Err(_), false) => (-1, "fail"),
2521            };
2522            // A stop that arrived while this monitor was draining did not get
2523            // to write anything, so it is applied here. A run that had already
2524            // succeeded keeps that outcome — there was nothing left to
2525            // interrupt — but a failed one is recorded as stopped, so the
2526            // retry checker leaves it alone.
2527
2528            // Update daemon state unless stop() already did it (won the race),
2529            // OR the daemon was intentionally stopped before the drain
2530            // (pre_drain_is_stopping). In the latter case, start() may have
2531            // upserted Running during the 5s drain, and we must NOT overwrite
2532            // it with Stopped — that would undo the restart.
2533            if !already_stopped && !pre_drain_is_stopping {
2534                if let Ok(status) = &exit_status {
2535                    info!("daemon {id} exited with status {status}");
2536                }
2537                let (new_status, last_exit_success) = terminal_exit_state(
2538                    exit_reason,
2539                    opts.oneshot,
2540                    exit_code,
2541                    exit_status.as_ref().map(|s| s.success()).unwrap_or(true),
2542                );
2543                // Revalidate ownership inside the same state-lock section that
2544                // performs the write. The snapshot above was taken without
2545                // holding the lock, so a restart running on another thread can
2546                // install a successor in between; overwriting its record would
2547                // clear a live daemon's PID and undo the restart.
2548                if !SUPERVISOR
2549                    .finalize_monitored_exit(
2550                        &id,
2551                        pid,
2552                        monitor_token,
2553                        new_status,
2554                        Some(last_exit_success),
2555                    )
2556                    .await
2557                {
2558                    debug!("daemon {id} exit state was not written; a successor owns the record");
2559                }
2560            }
2561
2562            // The terminal state is now visible, so a caller waiting on this
2563            // oneshot can return and see it. A task that was stopped partway
2564            // never did its work, so it does not satisfy anything waiting on
2565            // it — even when the process caught the signal and exited 0.
2566            if oneshot_completion_pending && let Some(tx) = ready_tx.take() {
2567                if exit_reason == "exit" {
2568                    let _ = tx.send(Ok(()));
2569                } else {
2570                    warn!("daemon {id}: oneshot was stopped before completing");
2571                    let _ = tx.send(Err(None));
2572                }
2573            }
2574
2575            // --- Phase 2: Fire hooks ---
2576            let hook_extra_env = vec![
2577                ("PITCHFORK_EXIT_CODE".to_string(), exit_code.to_string()),
2578                ("PITCHFORK_EXIT_REASON".to_string(), exit_reason.to_string()),
2579            ];
2580
2581            // Determine which hooks to fire based on exit reason
2582            let hooks_to_fire: Vec<HookType> = match exit_reason {
2583                "stop" => vec![HookType::OnStop, HookType::OnExit],
2584                "exit" => vec![HookType::OnExit],
2585                // "fail": fire on_fail + on_exit only when retries are exhausted
2586                _ if hook_retry_count >= hook_retry.count() => {
2587                    vec![HookType::OnFail, HookType::OnExit]
2588                }
2589                _ => vec![],
2590            };
2591
2592            for hook_type in hooks_to_fire {
2593                fire_hook(
2594                    hook_type,
2595                    id.clone(),
2596                    hook_dirs.clone(),
2597                    hook_retry_count,
2598                    hook_daemon_env.clone(),
2599                    hook_resolved_ports.clone(),
2600                    hook_extra_env.clone(),
2601                )
2602                .await;
2603            }
2604        });
2605
2606        // If wait_ready is true, wait for readiness notification
2607        if let Some(ready_rx) = ready_rx {
2608            match ready_rx.await {
2609                Ok(Ok(())) => {
2610                    info!("daemon {id} is ready");
2611                    // Re-read rather than returning the snapshot taken at
2612                    // spawn: a completed oneshot has since been finalized, and
2613                    // the snapshot would tell the caller it is still running
2614                    // under a PID that has exited.
2615                    //
2616                    // Only when the record still describes this run, though. A
2617                    // successor that claimed it carries its own PID and start
2618                    // time, and reporting those as the outcome of the process
2619                    // this call spawned would misattribute them.
2620                    let daemon = match self.get_daemon(id).await {
2621                        Some(current) if current.pid.is_none() || current.pid == Some(pid) => {
2622                            current
2623                        }
2624                        // A successor owns the record, so neither it nor the
2625                        // spawn snapshot describes this run: one carries
2626                        // another process's identity, the other still says
2627                        // running under a PID that has exited. A oneshot that
2628                        // reported ready did finish, so report that outcome
2629                        // directly rather than either misleading record.
2630                        _ if opts.oneshot => crate::daemon::Daemon {
2631                            status: DaemonStatus::Completed,
2632                            pid: None,
2633                            start_time: None,
2634                            boot_time: None,
2635                            last_exit_success: Some(true),
2636                            ..daemon
2637                        },
2638                        _ => daemon,
2639                    };
2640                    Ok(IpcResponse::DaemonReady { daemon })
2641                }
2642                Ok(Err(exit_code)) => {
2643                    error!("daemon {id} failed before becoming ready");
2644                    // The caller reports this by querying the log store for
2645                    // what the daemon printed, so wait for the sink's final
2646                    // write first. The in-process path got this ordering by
2647                    // flushing synchronously before signalling.
2648                    //
2649                    // Only on the attempt that gives up: `run` retries inline,
2650                    // and waiting after every attempt would both delay the
2651                    // backoff and widen the window in which the daemon looks
2652                    // errored and idle — long enough for the background retry
2653                    // checker to start an attempt of its own alongside it.
2654                    let last_attempt = opts.retry_count >= opts.retry.count();
2655                    if using_sink && last_attempt {
2656                        super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
2657                    }
2658                    Ok(IpcResponse::DaemonFailedWithCode {
2659                        exit_code,
2660                        resolved_ports: attempt_resolved_ports,
2661                    })
2662                }
2663                Err(_) => {
2664                    error!("readiness channel closed unexpectedly for daemon {id}");
2665                    Ok(IpcResponse::DaemonStart { daemon })
2666                }
2667            }
2668        } else {
2669            Ok(IpcResponse::DaemonStart { daemon })
2670        }
2671    }
2672
2673    /// Stop a running daemon
2674    pub async fn stop(&self, id: &DaemonId) -> Result<IpcResponse> {
2675        // Hold the daemon's stop lock for the whole stop (including the
2676        // whole-group termination wait) so starts and concurrent stops of the
2677        // same daemon serialize against it instead of racing the Stopping window.
2678        let lock = self.stop_lock(id).await;
2679        let _guard = lock.lock().await;
2680        self.stop_locked(id).await
2681    }
2682
2683    /// Stop a running daemon that is about to be started again (a file-watch
2684    /// restart). Same as [`Self::stop`], except the daemon is recorded as
2685    /// `restarting` rather than `stopping`/`stopped`, so anything following it
2686    /// (`pitchfork wait`) does not mistake the stop for the end of its run.
2687    /// The caller must start the daemon again, or settle the record with
2688    /// [`Self::settle_restarting`] if it cannot.
2689    pub(crate) async fn stop_for_restart(&self, id: &DaemonId) -> Result<IpcResponse> {
2690        let lock = self.stop_lock(id).await;
2691        let _guard = lock.lock().await;
2692        self.stop_locked_with(id, true).await
2693    }
2694
2695    /// Stop implementation. Caller must hold the daemon's stop lock.
2696    pub(super) async fn stop_locked(&self, id: &DaemonId) -> Result<IpcResponse> {
2697        self.stop_locked_with(id, false).await
2698    }
2699
2700    /// Stop implementation. Caller must hold the daemon's stop lock.
2701    ///
2702    /// With `restarting`, every status this would record as `stopping` or
2703    /// `stopped` is recorded as `restarting` instead: the daemon is on its way
2704    /// back, and recording it as stopped, even briefly, would tell anything
2705    /// watching the record that its run is over.
2706    pub(super) async fn stop_locked_with(
2707        &self,
2708        id: &DaemonId,
2709        restarting: bool,
2710    ) -> Result<IpcResponse> {
2711        let (stopping_status, stopped_status) = if restarting {
2712            (DaemonStatus::Restarting, DaemonStatus::Restarting)
2713        } else {
2714            (DaemonStatus::Stopping, DaemonStatus::Stopped)
2715        };
2716        let pitchfork_id = DaemonId::pitchfork();
2717        if *id == pitchfork_id {
2718            return Ok(IpcResponse::Error(
2719                "Cannot stop supervisor via stop command".into(),
2720            ));
2721        }
2722        info!("stopping daemon: {id}");
2723        // A foreground `start` may be working through this daemon's retries,
2724        // sleeping out a backoff with no process of its own to kill. Tell it to
2725        // give up, or it would start the next attempt once the stop has
2726        // returned.
2727        self.cancel_retrying(id);
2728        // ...and the retry checker may already have decided on an attempt it
2729        // has not started yet. The count is raised when this stop is done
2730        // rather than now, and while its lock is still held, so a checker that
2731        // reads the count while the stop is still recording itself reads the
2732        // old value and stands down when it reaches the lock. Raising it up
2733        // front would hand that reader a value that still matches once the
2734        // stop has finished.
2735        let _stop_epoch_bump = StopEpochGuard(id.clone());
2736        if let Some(daemon) = self.get_daemon(id).await {
2737            trace!("daemon to stop: {daemon}");
2738            if let Some(pid) = daemon.pid {
2739                trace!("killing pid: {pid}");
2740                if PROCS.is_running(pid) {
2741                    // Something is alive on that PID, but the kill below signals
2742                    // the entire process group: if the PID was recycled while
2743                    // this record sat unsupervised, that group belongs to an
2744                    // unrelated process tree. The daemon itself is gone either
2745                    // way, so report it as not running and clear the record.
2746                    if !super::signalling_pid_is_authorized(
2747                        daemon.start_time,
2748                        PROCS.start_time(pid),
2749                    ) {
2750                        warn!(
2751                            "pid {pid} recorded for daemon {id} belongs to another process now; not signalling it"
2752                        );
2753                        self.upsert_daemon(
2754                            UpsertDaemonOpts::builder(id.clone())
2755                                .set(|o| {
2756                                    o.pid = None;
2757                                    o.status = stopped_status.clone();
2758                                })
2759                                .build(),
2760                        )
2761                        .await?;
2762                        return Ok(IpcResponse::DaemonWasNotRunning);
2763                    }
2764
2765                    // First set status to Stopping (preserve PID for monitoring task)
2766                    self.upsert_daemon(
2767                        UpsertDaemonOpts::builder(id.clone())
2768                            .set(|o| {
2769                                o.pid = Some(pid);
2770                                o.status = stopping_status.clone();
2771                            })
2772                            .build(),
2773                    )
2774                    .await?;
2775
2776                    // Kill the entire process group atomically (daemon PID == PGID
2777                    // because we called setsid() at spawn time)
2778                    let stop_cfg = daemon.stop_signal.unwrap_or_default();
2779                    let stop_signal: i32 = stop_cfg.signal.into();
2780                    if let Err(e) = PROCS
2781                        .kill_process_group_async(pid, stop_signal, stop_cfg.timeout)
2782                        .await
2783                    {
2784                        debug!("failed to kill pid {pid}: {e}");
2785                        // Check if the process group is actually gone despite the
2786                        // error. Checking only the leader here would mark the daemon
2787                        // Stopped while surviving group members (e.g. one stuck in
2788                        // uninterruptible sleep) are still alive — letting a restart
2789                        // collide with them.
2790                        if PROCS.process_group_alive(pid) {
2791                            // Group still has live members - set back to Running
2792                            debug!(
2793                                "failed to stop pid {pid}: process group still alive after kill"
2794                            );
2795                            self.upsert_daemon(
2796                                UpsertDaemonOpts::builder(id.clone())
2797                                    .set(|o| {
2798                                        o.pid = Some(pid); // Preserve PID to avoid orphaning the process
2799                                        o.status = DaemonStatus::Running;
2800                                    })
2801                                    .build(),
2802                            )
2803                            .await?;
2804                            return Ok(IpcResponse::DaemonStopFailed {
2805                                error: format!(
2806                                    "process group of {pid} still alive after kill attempt: {e}"
2807                                ),
2808                            });
2809                        }
2810                        // On Windows the daemon can be gone while processes of
2811                        // its job remain (see `procs`), which the PID check above
2812                        // cannot see. The daemon is recorded as stopped, since
2813                        // it is, but the stop is reported as failed.
2814                        #[cfg(windows)]
2815                        {
2816                            self.upsert_daemon(
2817                                UpsertDaemonOpts::builder(id.clone())
2818                                    .set(|o| {
2819                                        o.pid = None;
2820                                        o.status = stopped_status.clone();
2821                                        o.last_exit_success = Some(true);
2822                                    })
2823                                    .build(),
2824                            )
2825                            .await?;
2826                            return Ok(IpcResponse::DaemonStopFailed {
2827                                error: format!("{e}"),
2828                            });
2829                        }
2830                    }
2831
2832                    // Process successfully stopped
2833                    // Note: kill_process_group_async waits for the ENTIRE process
2834                    // group to exit (stop signal -> stop_timeout -> SIGKILL, then a
2835                    // bounded verification), so a replacement daemon can be started
2836                    // without colliding with a still-terminating instance. The only
2837                    // exception is a member stuck in uninterruptible sleep, which is
2838                    // logged with a warning.
2839                    self.upsert_daemon(
2840                        UpsertDaemonOpts::builder(id.clone())
2841                            .set(|o| {
2842                                o.pid = None;
2843                                o.status = stopped_status.clone();
2844                                o.last_exit_success = Some(true);
2845                            })
2846                            .build(),
2847                    )
2848                    .await?;
2849                } else if daemon.oneshot && self.is_monitored(id, pid) {
2850                    // The task's process is gone but its monitor is still
2851                    // running, so the run's real outcome has not been written
2852                    // yet — and for a task that finished on its own that
2853                    // outcome is `completed`. Writing `stopped` straight over
2854                    // it would discard a success the task actually achieved
2855                    // and report failure to anyone waiting on it, purely
2856                    // because a stop arrived a moment late.
2857                    //
2858                    // So wait for whoever is monitoring this run — the native
2859                    // monitor or an adopted one — to finish, then decide from
2860                    // what it wrote. Waiting rather than leaving a note for
2861                    // the monitor to find means there is no window in which
2862                    // the note lands too late to be read, and nothing left
2863                    // behind if it is never read at all. The wait is bounded,
2864                    // as is the monitor's own five-second output drain.
2865                    //
2866                    // Only oneshots take this path. A service has no
2867                    // successful exit to preserve, so it falls through to the
2868                    // arm below, which records the stop immediately.
2869                    debug!(
2870                        "pid {pid} not running but daemon {id} is still monitored; waiting for its monitor to settle the outcome"
2871                    );
2872                    self.wait_for_exit_finalized(id, Some(pid)).await;
2873                    let finished = self.get_daemon(id).await;
2874                    if finished
2875                        .as_ref()
2876                        .is_some_and(|d| stop_keeps_finalized_status(&d.status))
2877                    {
2878                        return Ok(IpcResponse::DaemonWasNotRunning);
2879                    }
2880                    // The run did not finish its work, so record the stop. A
2881                    // failure left in place would be picked up by the retry
2882                    // checker, which would start a task the user just stopped.
2883                    self.upsert_daemon(
2884                        UpsertDaemonOpts::builder(id.clone())
2885                            .set(|o| {
2886                                o.pid = None;
2887                                o.status = stopped_status.clone();
2888                            })
2889                            .build(),
2890                    )
2891                    .await?;
2892                    return Ok(IpcResponse::DaemonWasNotRunning);
2893                } else {
2894                    debug!("pid {pid} not running, process may have exited unexpectedly");
2895                    // Process already dead and unmonitored, so nothing else
2896                    // will record an outcome — transition to Stopped so the
2897                    // retry checker sees a terminal state and stops
2898                    // scheduling new attempts. This is important for an
2899                    // explicit `pitchfork stop` on an Errored daemon: the
2900                    // user wants to abort retries.
2901                    self.upsert_daemon(
2902                        UpsertDaemonOpts::builder(id.clone())
2903                            .set(|o| {
2904                                o.pid = None;
2905                                o.status = stopped_status.clone();
2906                            })
2907                            .build(),
2908                    )
2909                    .await?;
2910                    return Ok(IpcResponse::DaemonWasNotRunning);
2911                }
2912                Ok(IpcResponse::Ok)
2913            } else {
2914                debug!("daemon {id} not running");
2915                // Between a restart's stop and its start there is no process,
2916                // but the daemon is on its way back. Stopping it now cancels
2917                // the restart: the restart sees the record has moved on and
2918                // does not start it again.
2919                if !restarting && daemon.status.is_restarting() {
2920                    self.upsert_daemon(
2921                        UpsertDaemonOpts::builder(id.clone())
2922                            .set(|o| {
2923                                o.pid = None;
2924                                o.status = DaemonStatus::Stopped;
2925                            })
2926                            .build(),
2927                    )
2928                    .await?;
2929                    return Ok(IpcResponse::Ok);
2930                }
2931                // No process to signal, but a failed record with retries left
2932                // is not inert: `check_retry` starts the next attempt from it,
2933                // whether or not a foreground start is also working through
2934                // them. Record the stop so nothing picks the daemon back up.
2935                if daemon.status.is_errored() && daemon.retry_count < daemon.retry.count() {
2936                    self.upsert_daemon(
2937                        UpsertDaemonOpts::builder(id.clone())
2938                            .set(|o| {
2939                                o.pid = None;
2940                                o.status = stopped_status.clone();
2941                            })
2942                            .build(),
2943                    )
2944                    .await?;
2945                    return Ok(IpcResponse::DaemonWasNotRunning);
2946                }
2947                Ok(IpcResponse::DaemonNotRunning)
2948            }
2949        } else {
2950            debug!("daemon {id} not found");
2951            Ok(IpcResponse::DaemonNotFound)
2952        }
2953    }
2954}
2955
2956#[cfg(unix)]
2957fn resolve_effective_run_identity(daemon_user: Option<&str>) -> Result<RunIdentity> {
2958    let s = settings();
2959    let settings_user = s.supervisor.user.trim();
2960    let daemon_user = daemon_user.map(str::trim).filter(|user| !user.is_empty());
2961    let settings_user = (!settings_user.is_empty()).then_some(settings_user);
2962    let configured = daemon_user.or(settings_user);
2963    let current_uid = nix::unistd::Uid::effective().as_raw();
2964    let current_gid = nix::unistd::Gid::effective().as_raw();
2965    // The recorded invoking user of a boot service stands in for the sudo
2966    // environment that launchd and systemd do not provide.
2967    let invoking = env::invoking_user_ids().map(|(uid, gid)| (uid.to_string(), gid.to_string()));
2968    resolve_run_identity(
2969        configured,
2970        current_uid,
2971        current_gid,
2972        invoking.as_ref().map(|(uid, _)| uid.as_str()),
2973        invoking.as_ref().map(|(_, gid)| gid.as_str()),
2974    )
2975}
2976
2977#[cfg(unix)]
2978fn resolve_run_identity(
2979    configured: Option<&str>,
2980    current_uid: u32,
2981    current_gid: u32,
2982    sudo_uid: Option<&str>,
2983    sudo_gid: Option<&str>,
2984) -> Result<RunIdentity> {
2985    let current_uid = nix::unistd::Uid::from_raw(current_uid);
2986    let current_gid = nix::unistd::Gid::from_raw(current_gid);
2987    if let Some(user) = configured {
2988        let identity = resolve_configured_user(user)?;
2989        ensure_can_use_identity(user, &identity, current_uid, current_gid)?;
2990        if identity.matches(current_uid, current_gid) {
2991            return Ok(RunIdentity::Inherit);
2992        }
2993        return Ok(identity);
2994    }
2995
2996    if current_uid.is_root()
2997        && let Some(identity) = resolve_sudo_identity(sudo_uid, sudo_gid)
2998    {
2999        if identity.matches(current_uid, current_gid) {
3000            return Ok(RunIdentity::Inherit);
3001        }
3002        return Ok(identity);
3003    }
3004
3005    Ok(RunIdentity::Inherit)
3006}
3007
3008#[cfg(unix)]
3009fn resolve_configured_user(user: &str) -> Result<RunIdentity> {
3010    if user.chars().all(|c| c.is_ascii_digit()) {
3011        let uid = user
3012            .parse::<u32>()
3013            .map_err(|e| miette::miette!("invalid run user UID '{}': {}", user, e))?;
3014        let user_record = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3015            .into_diagnostic()?
3016            .ok_or_else(|| miette::miette!("run user UID '{}' does not exist", user))?;
3017        return run_identity_from_user_record(user_record);
3018    }
3019
3020    let user_record = nix::unistd::User::from_name(user)
3021        .into_diagnostic()?
3022        .ok_or_else(|| miette::miette!("run user '{}' does not exist", user))?;
3023    run_identity_from_user_record(user_record)
3024}
3025
3026#[cfg(unix)]
3027fn run_identity_from_user_record(user: nix::unistd::User) -> Result<RunIdentity> {
3028    let username = CString::new(user.name)
3029        .map_err(|e| miette::miette!("run user name contains an interior nul byte: {}", e))?;
3030    Ok(RunIdentity::Switch {
3031        uid: user.uid,
3032        gid: user.gid,
3033        username: Some(username),
3034        home: Some(user.dir),
3035    })
3036}
3037
3038#[cfg(unix)]
3039fn resolve_sudo_identity(sudo_uid: Option<&str>, sudo_gid: Option<&str>) -> Option<RunIdentity> {
3040    let uid = sudo_uid?.parse::<u32>().ok()?;
3041    let gid = sudo_gid?.parse::<u32>().ok()?;
3042    let user = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
3043        .ok()
3044        .flatten();
3045    let (username, home) = match user {
3046        Some(user) => (CString::new(user.name).ok(), Some(user.dir)),
3047        None => (None, None),
3048    };
3049    Some(RunIdentity::Switch {
3050        uid: nix::unistd::Uid::from_raw(uid),
3051        gid: nix::unistd::Gid::from_raw(gid),
3052        username,
3053        home,
3054    })
3055}
3056
3057#[cfg(unix)]
3058fn ensure_can_use_identity(
3059    configured_user: &str,
3060    identity: &RunIdentity,
3061    current_uid: nix::unistd::Uid,
3062    current_gid: nix::unistd::Gid,
3063) -> Result<()> {
3064    let RunIdentity::Switch { uid, gid, .. } = identity else {
3065        return Ok(());
3066    };
3067    if *uid == current_uid && *gid == current_gid {
3068        return Ok(());
3069    }
3070    if current_uid.is_root() {
3071        return Ok(());
3072    }
3073    Err(miette::miette!(
3074        "daemon is configured to run as '{}', but the supervisor is running as uid={} gid={}. Restart the supervisor with sudo to switch to uid={} gid={}, or choose a user matching the supervisor.",
3075        configured_user,
3076        current_uid.as_raw(),
3077        current_gid.as_raw(),
3078        uid.as_raw(),
3079        gid.as_raw()
3080    ))
3081}
3082
3083/// Point HOME, USER and LOGNAME at the user a daemon switches to.
3084///
3085/// The supervisor's environment describes the supervisor's own user (usually
3086/// root), so without this a daemon run as another user would read and write
3087/// root's home. A value the passwd entry cannot supply is removed rather than
3088/// left describing root.
3089#[cfg(unix)]
3090fn apply_identity_env(command: &mut tokio::process::Command, identity: &RunIdentity) {
3091    let RunIdentity::Switch { username, home, .. } = identity else {
3092        return;
3093    };
3094    match home.as_ref().filter(|home| !home.as_os_str().is_empty()) {
3095        Some(home) => command.env("HOME", home),
3096        None => command.env_remove("HOME"),
3097    };
3098    match username.as_ref().and_then(|name| name.to_str().ok()) {
3099        Some(name) => command.env("USER", name).env("LOGNAME", name),
3100        None => command.env_remove("USER").env_remove("LOGNAME"),
3101    };
3102}
3103
3104#[cfg(unix)]
3105fn apply_run_identity(identity: &RunIdentity) -> std::io::Result<()> {
3106    let RunIdentity::Switch {
3107        uid, gid, username, ..
3108    } = identity
3109    else {
3110        return Ok(());
3111    };
3112    if let Some(username) = username {
3113        initgroups_for_user(username, *gid)?;
3114    } else {
3115        setgroups_to_primary(*gid)?;
3116    }
3117    nix::unistd::setgid(*gid).map_err(nix_to_io_error)?;
3118    nix::unistd::setuid(*uid).map_err(nix_to_io_error)?;
3119    Ok(())
3120}
3121
3122#[cfg(unix)]
3123impl RunIdentity {
3124    fn matches(&self, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> bool {
3125        matches!(self, RunIdentity::Switch { uid: u, gid: g, .. } if *u == uid && *g == gid)
3126    }
3127}
3128
3129#[cfg(unix)]
3130fn setgroups_to_primary(gid: nix::unistd::Gid) -> std::io::Result<()> {
3131    let groups = [gid.as_raw() as libc::gid_t];
3132    #[cfg(any(target_os = "linux", target_os = "android"))]
3133    let group_count = groups.len();
3134    #[cfg(not(any(target_os = "linux", target_os = "android")))]
3135    let group_count = groups.len() as libc::c_int;
3136    let rc = unsafe { libc::setgroups(group_count, groups.as_ptr()) };
3137    if rc == -1 {
3138        Err(std::io::Error::last_os_error())
3139    } else {
3140        Ok(())
3141    }
3142}
3143
3144#[cfg(unix)]
3145fn initgroups_for_user(username: &CString, gid: nix::unistd::Gid) -> std::io::Result<()> {
3146    let gid = gid.as_raw();
3147    #[cfg(any(
3148        target_os = "macos",
3149        target_os = "ios",
3150        target_os = "tvos",
3151        target_os = "watchos"
3152    ))]
3153    let base_gid = i32::try_from(gid)
3154        .map_err(|_| std::io::Error::other(format!("gid {gid} is out of range")))?;
3155
3156    #[cfg(not(any(
3157        target_os = "macos",
3158        target_os = "ios",
3159        target_os = "tvos",
3160        target_os = "watchos"
3161    )))]
3162    let base_gid = gid as libc::gid_t;
3163
3164    // SAFETY: `username` is a valid nul-terminated C string and `base_gid`
3165    // is derived from a resolved system account or sudo-provided gid.
3166    let rc = unsafe { libc::initgroups(username.as_ptr(), base_gid) };
3167    if rc == -1 {
3168        Err(std::io::Error::last_os_error())
3169    } else {
3170        Ok(())
3171    }
3172}
3173
3174#[cfg(unix)]
3175fn nix_to_io_error(err: nix::errno::Errno) -> std::io::Error {
3176    std::io::Error::from_raw_os_error(err as i32)
3177}
3178
3179/// Check if multiple ports are available and optionally auto-bump to find available ports.
3180///
3181/// All ports are bumped by the same offset to maintain relative port spacing.
3182/// Returns the resolved ports (either the original or bumped ones).
3183/// Returns an error if any port is in use and auto_bump is disabled,
3184/// or if no available ports can be found after max attempts.
3185async fn check_ports_available(
3186    expected_ports: &[u16],
3187    auto_bump: bool,
3188    max_attempts: u32,
3189) -> Result<Vec<u16>> {
3190    if expected_ports.is_empty() {
3191        return Ok(Vec::new());
3192    }
3193
3194    for bump_offset in 0..=max_attempts {
3195        // Use wrapping_add to handle overflow correctly - ports wrap around at 65535
3196        let candidate_ports: Vec<u16> = expected_ports
3197            .iter()
3198            .map(|&p| p.wrapping_add(bump_offset as u16))
3199            .collect();
3200
3201        // Check if all ports in this set are available
3202        let mut all_available = true;
3203        let mut conflicting_port = None;
3204
3205        for &port in &candidate_ports {
3206            // Port 0 is a special case - it requests an ephemeral port from the OS.
3207            // Skip the availability check for port 0 since binding to it always succeeds.
3208            if port == 0 {
3209                continue;
3210            }
3211
3212            // Use spawn_blocking to avoid blocking the async runtime during TCP bind checks.
3213            //
3214            // We check multiple addresses to avoid false-negatives caused by SO_REUSEADDR.
3215            // On macOS/BSD, the probe sets SO_REUSEADDR (see `bind_probe`), which
3216            // allows binding 0.0.0.0:port even when 127.0.0.1:port is already in use
3217            // (because 0.0.0.0 is technically a different address).  Most daemons bind
3218            // to localhost, so checking 127.0.0.1 is essential to detect real conflicts.
3219            // We also check [::1] to cover IPv6 loopback listeners.
3220            //
3221            // NOTE: This check has a time-of-check-to-time-of-use (TOCTOU) race condition.
3222            // Another process could grab the port between our check and the daemon actually
3223            // binding. This is inherent to the approach and acceptable for our use case
3224            // since we're primarily detecting conflicts with already-running daemons.
3225            if let Some(address) = port_bind_conflict(port).await {
3226                all_available = false;
3227                conflicting_port = Some((port, address));
3228                break;
3229            }
3230        }
3231
3232        if all_available {
3233            // Check for overflow (port wrapped around to 0 due to wrapping_add)
3234            // If any candidate port is 0 but the original expected port wasn't 0,
3235            // it means we've wrapped around and should stop
3236            if candidate_ports.contains(&0) && !expected_ports.contains(&0) {
3237                return Err(PortError::NoAvailablePort {
3238                    start_port: expected_ports[0],
3239                    attempts: bump_offset + 1,
3240                }
3241                .into());
3242            }
3243            if bump_offset > 0 {
3244                info!("ports {expected_ports:?} bumped by {bump_offset} to {candidate_ports:?}");
3245            }
3246            return Ok(candidate_ports);
3247        }
3248
3249        // Port is in use
3250        if bump_offset == 0
3251            && !auto_bump
3252            && let Some((port, address)) = conflicting_port
3253        {
3254            let (pid, process) = identify_port_owner(port, address).await;
3255            return Err(PortError::InUse {
3256                port,
3257                address: Some(shown_address(address)),
3258                process,
3259                pid,
3260            }
3261            .into());
3262        }
3263    }
3264
3265    // No available ports found after max attempts
3266    Err(PortError::NoAvailablePort {
3267        start_port: expected_ports[0],
3268        attempts: max_attempts + 1,
3269    }
3270    .into())
3271}
3272
3273/// Check whether a port is currently in use by attempting to bind on multiple addresses.
3274///
3275/// Returns the address of the first bind that gets `AddrInUse`, meaning another socket
3276/// holds the port there. Other errors (e.g. `AddrNotAvailable` on an address family
3277/// the OS doesn't support) are ignored so they don't produce false positives.
3278async fn port_bind_conflict(port: u16) -> Option<std::net::IpAddr> {
3279    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3280    tokio::task::spawn_blocking(move || {
3281        for addr in [
3282            IpAddr::V4(Ipv4Addr::UNSPECIFIED),
3283            IpAddr::V4(Ipv4Addr::LOCALHOST),
3284            IpAddr::V6(Ipv6Addr::LOCALHOST),
3285        ] {
3286            match bind_probe((addr, port).into()) {
3287                Ok(socket) => drop(socket),
3288                Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Some(addr),
3289                Err(_) => continue,
3290            }
3291        }
3292        None
3293    })
3294    .await
3295    .unwrap_or(None)
3296}
3297
3298/// Bind a TCP socket to `addr` for [`port_bind_conflict`].
3299///
3300/// The socket never listens. A child forked by another thread while the socket
3301/// is open keeps a copy until the child execs, so the copy can still be bound
3302/// when the next address is probed. On Linux, a listening copy would make that
3303/// bind fail even with `SO_REUSEADDR`, and the port would look taken. A copy
3304/// that doesn't listen doesn't, because Linux lets sockets that set
3305/// `SO_REUSEADDR` and don't listen share a port. A copy that doesn't listen
3306/// can't accept connections either, so a `ready_port` check can't pass on it.
3307/// A socket listening on the same address and port still makes the bind fail.
3308#[cfg(unix)]
3309fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<tokio::net::TcpSocket> {
3310    let socket = if addr.is_ipv4() {
3311        tokio::net::TcpSocket::new_v4()?
3312    } else {
3313        tokio::net::TcpSocket::new_v6()?
3314    };
3315    socket.set_reuseaddr(true)?;
3316    socket.bind(addr)?;
3317    Ok(socket)
3318}
3319
3320/// Bind a TCP listener to `addr` for [`port_bind_conflict`].
3321///
3322/// Unlike on Unix, the probe listens: Windows may report that a wildcard bind
3323/// conflicts only when the socket listens. Children don't inherit std's
3324/// sockets there, so no child can hold a copy of it.
3325#[cfg(not(unix))]
3326fn bind_probe(addr: std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
3327    std::net::TcpListener::bind(addr)
3328}
3329
3330/// An address as a message shows it: IPv6 in brackets, as in `[::1]`.
3331fn shown_address(addr: std::net::IpAddr) -> String {
3332    match addr {
3333        std::net::IpAddr::V4(v4) => v4.to_string(),
3334        std::net::IpAddr::V6(v6) => format!("[{v6}]"),
3335    }
3336}
3337
3338/// How well a socket listening on `listening` accounts for a bind to
3339/// `conflict` failing on the same port, best first, or `None` when it cannot:
3340/// the same address; a wildcard and a specific address of one family, which
3341/// conflict with each other; then `[::]`, which also takes IPv4 unless it is
3342/// IPv6-only. An IPv4-mapped IPv6 address, as a dual-stack socket shows an
3343/// IPv4 connection, counts as the IPv4 address.
3344fn listener_match(listening: std::net::IpAddr, conflict: std::net::IpAddr) -> Option<u8> {
3345    use std::net::IpAddr;
3346    let listening = listening.to_canonical();
3347    if listening == conflict {
3348        return Some(0);
3349    }
3350    match (listening, conflict) {
3351        (IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
3352            if listening.is_unspecified() || conflict.is_unspecified() =>
3353        {
3354            Some(1)
3355        }
3356        (IpAddr::V6(v6), IpAddr::V4(_)) if v6.is_unspecified() => Some(2),
3357        _ => None,
3358    }
3359}
3360
3361/// A TCP socket on this machine, as the port owner lookup sees it.
3362struct TcpSocket {
3363    addr: std::net::SocketAddr,
3364    listening: bool,
3365    pid: u32,
3366    process: String,
3367}
3368
3369/// The process whose TCP socket on `port` best accounts for the bind to
3370/// `conflict` failing (see [`listener_match`]), among `sockets`. A listening
3371/// socket comes first; one that is not listening but is bound to the port,
3372/// such as a connection a listener accepted, can hold it too. `None` when
3373/// none can.
3374///
3375/// A `[::]` socket holds an IPv4 port only if it is not IPv6-only, which the
3376/// socket list does not tell, so it is named for an IPv4 conflict only when no
3377/// IPv4 socket, listening or not, could account for it.
3378fn pick_port_owner(
3379    sockets: impl IntoIterator<Item = TcpSocket>,
3380    port: u16,
3381    conflict: std::net::IpAddr,
3382) -> Option<(u32, String)> {
3383    sockets
3384        .into_iter()
3385        .filter(|s| s.addr.port() == port)
3386        .filter_map(|s| {
3387            let matched = listener_match(s.addr.ip(), conflict)?;
3388            let rank = (matched == 2, !s.listening, matched);
3389            Some((rank, s.pid, s.process))
3390        })
3391        .min_by_key(|(rank, _, _)| *rank)
3392        .map(|(_, pid, process)| (pid, process))
3393}
3394
3395/// Best-effort lookup of the process occupying a port via `listeners::get_all()`.
3396///
3397/// Only a TCP socket on an address that conflicts with `conflict`, the address
3398/// whose bind found the port taken, is taken as the holder: another process
3399/// may listen on the same port on an address that does not. A listening
3400/// socket is preferred (see [`pick_port_owner`]).
3401///
3402/// Returns `(pid, process_name)`.  Falls back to `(0, "unknown")` when no such
3403/// socket is found or the system call fails (permission error, unsupported OS, etc.).
3404async fn identify_port_owner(port: u16, conflict: std::net::IpAddr) -> (u32, String) {
3405    tokio::task::spawn_blocking(move || {
3406        listeners::get_all()
3407            .ok()
3408            .and_then(|list| {
3409                // UDP sockets share port numbers with TCP but never block a
3410                // TCP bind.
3411                let tcp = list
3412                    .into_iter()
3413                    .filter(|l| l.protocol == listeners::Protocol::TCP)
3414                    .map(|l| TcpSocket {
3415                        addr: l.socket,
3416                        listening: l.state == listeners::SocketState::Listen,
3417                        pid: l.process.pid,
3418                        process: l.process.name,
3419                    });
3420                pick_port_owner(tcp, port, conflict)
3421            })
3422            .unwrap_or((0, "unknown".to_string()))
3423    })
3424    .await
3425    .unwrap_or((0, "unknown".to_string()))
3426}
3427
3428/// Detect whether a port is in use, and if so, where and by which process.
3429///
3430/// Combines `port_bind_conflict` (reliable bind probe) with `identify_port_owner`
3431/// (best-effort process lookup).  Returns `None` when the port is free.
3432async fn detect_port_conflict(port: u16) -> Option<(String, u32, String)> {
3433    let address = port_bind_conflict(port).await?;
3434    let (pid, process) = identify_port_owner(port, address).await;
3435    Some((shown_address(address), pid, process))
3436}
3437
3438#[derive(Debug, PartialEq, Eq)]
3439enum ActivePortSelection {
3440    NoCandidates,
3441    Selected(u16),
3442    Ambiguous(Vec<u16>),
3443}
3444
3445fn discovery_preferred_port(daemon: &crate::daemon::Daemon) -> Option<u16> {
3446    daemon
3447        .resolved_port
3448        .first()
3449        .copied()
3450        .or_else(|| {
3451            daemon
3452                .port
3453                .as_ref()
3454                .and_then(|port| port.expect.first().copied())
3455        })
3456        .filter(|&port| port > 0)
3457}
3458
3459fn select_active_port(
3460    listeners: impl IntoIterator<Item = listeners::Listener>,
3461    descendant_pids: &std::collections::HashSet<u32>,
3462    preferred_port: Option<u16>,
3463) -> ActivePortSelection {
3464    let process_ports: std::collections::BTreeSet<u16> = listeners
3465        .into_iter()
3466        .filter(|listener| {
3467            listener.protocol == listeners::Protocol::TCP
3468                && listener.state == listeners::SocketState::Listen
3469                && descendant_pids.contains(&listener.process.pid)
3470        })
3471        .map(|listener| listener.socket.port())
3472        .filter(|&port| port > 0)
3473        .collect();
3474
3475    if let Some(port) = preferred_port
3476        && process_ports.contains(&port)
3477    {
3478        return ActivePortSelection::Selected(port);
3479    }
3480
3481    match process_ports.len() {
3482        0 => ActivePortSelection::NoCandidates,
3483        1 => ActivePortSelection::Selected(*process_ports.first().unwrap()),
3484        _ => ActivePortSelection::Ambiguous(process_ports.into_iter().collect()),
3485    }
3486}
3487
3488/// Spawn a background task that detects the daemon process's active listening port
3489/// and stores it in the state file as `active_port`.
3490///
3491/// This is called once when the daemon becomes ready. The port is cleared when the daemon stops.
3492///
3493/// Port selection strategy:
3494/// 1. Consider only TCP listening sockets owned by the daemon or its descendants.
3495/// 2. Prefer the first resolved port, falling back to the first expected port for
3496///    legacy state without resolved ports.
3497/// 3. Select a sole distinct candidate; leave `active_port` unset when ambiguous.
3498fn detect_and_store_active_port(id: DaemonId, pid: u32) {
3499    tokio::spawn(async move {
3500        // Retry with exponential backoff so that slow-starting daemons (JVM,
3501        // Node.js, Python, etc.) that take more than 500 ms to bind their port
3502        // are still detected.  Total wait budget: 500+1000+2000+4000 = 7.5 s.
3503        for delay_ms in [500u64, 1000, 2000, 4000] {
3504            tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
3505
3506            // Read daemon state atomically: check if still alive and get the preferred port
3507            // in a single lock acquisition to avoid TOCTOU and unnecessary lock overhead.
3508            let preferred_port: Option<u16> = {
3509                let state_file = SUPERVISOR.state_file.lock().await;
3510                match state_file.daemons.get(&id) {
3511                    Some(d) if d.pid.is_none() => {
3512                        debug!("daemon {id}: aborting active_port detection — process exited");
3513                        return;
3514                    }
3515                    Some(d) => discovery_preferred_port(d),
3516                    None => None,
3517                }
3518            };
3519
3520            let selection = tokio::task::spawn_blocking(move || {
3521                let listeners = listeners::get_all().ok()?;
3522
3523                // Refresh process tree so all_children sees current descendants.
3524                PROCS.refresh_processes();
3525
3526                let descendant_pids: std::collections::HashSet<u32> = PROCS
3527                    .all_children(pid)
3528                    .into_iter()
3529                    .chain(std::iter::once(pid))
3530                    .collect();
3531
3532                Some(select_active_port(
3533                    listeners,
3534                    &descendant_pids,
3535                    preferred_port,
3536                ))
3537            })
3538            .await
3539            .ok()
3540            .flatten()
3541            .unwrap_or(ActivePortSelection::NoCandidates);
3542
3543            let port = match selection {
3544                ActivePortSelection::Selected(port) => port,
3545                ActivePortSelection::Ambiguous(ports) => {
3546                    debug!(
3547                        "daemon {id}: ambiguous active_port candidates {ports:?} for pid {pid} \
3548                         and its descendants; leaving active_port unset (will retry)"
3549                    );
3550                    continue;
3551                }
3552                ActivePortSelection::NoCandidates => {
3553                    debug!(
3554                        "daemon {id}: no active port detected for pid {pid} or its descendants \
3555                         (will retry)"
3556                    );
3557                    continue;
3558                }
3559            };
3560
3561            debug!("daemon {id} active_port detected: {port}");
3562            let mut state_file = SUPERVISOR.state_file.lock().await;
3563            if let Some(d) = state_file.daemons.get(&id) {
3564                // Guard against PID reuse: if the original process exited and the OS
3565                // assigned the same PID to an unrelated process that happens to bind
3566                // a port, we must not route proxy traffic to that unrelated service.
3567                if d.pid == Some(pid) {
3568                    state_file.set_active_port(&id, port);
3569                } else {
3570                    debug!(
3571                        "daemon {id}: skipping active_port write — PID mismatch \
3572                         (expected {pid}, current {:?})",
3573                        d.pid
3574                    );
3575                }
3576            }
3577            return;
3578        }
3579
3580        debug!(
3581            "daemon {id}: active port detection exhausted all retries for pid {pid} and its descendants"
3582        );
3583    });
3584}
3585
3586#[cfg(test)]
3587mod port_conflict_tests {
3588    use super::{
3589        TcpSocket, check_ports_available, listener_match, pick_port_owner, port_bind_conflict,
3590        shown_address,
3591    };
3592    use crate::error::PortError;
3593    use std::net::{IpAddr, SocketAddr};
3594
3595    /// Held by a test that forks continuously, and by any test whose sockets
3596    /// a forked child must not keep after the test drops them.
3597    static FORKS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
3598
3599    #[tokio::test]
3600    async fn a_taken_port_is_reported_with_its_address_and_holder() {
3601        let _forks = FORKS.lock().await;
3602        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
3603        let port = listener.local_addr().unwrap().port();
3604
3605        // Which bind finds it taken depends on the OS: Linux refuses the
3606        // wildcard bind as well, macOS only the 127.0.0.1 one.
3607        let address = shown_address(port_bind_conflict(port).await.unwrap());
3608        assert!(
3609            ["0.0.0.0", "127.0.0.1"].contains(&address.as_str()),
3610            "{address}"
3611        );
3612
3613        let err = check_ports_available(&[port], false, 0).await.unwrap_err();
3614        match err.downcast_ref::<PortError>() {
3615            Some(PortError::InUse {
3616                port: p,
3617                address: Some(a),
3618                pid,
3619                ..
3620            }) => {
3621                assert_eq!(*p, port);
3622                assert_eq!(*a, address);
3623                // The holder is this test process, which lists its own sockets.
3624                assert_eq!(*pid, std::process::id());
3625            }
3626            other => panic!("unexpected error: {other:?}"),
3627        }
3628        drop(listener);
3629        assert_eq!(port_bind_conflict(port).await, None);
3630    }
3631
3632    #[cfg(unix)]
3633    #[test]
3634    fn a_copy_of_a_probe_socket_does_not_look_like_a_listener() {
3635        use super::bind_probe;
3636        // A child forked while the probe of 0.0.0.0 is open still holds it
3637        // when the probe of 127.0.0.1 binds.
3638        let copy = bind_probe(SocketAddr::from(([0, 0, 0, 0], 0))).unwrap();
3639        let port = copy.local_addr().unwrap().port();
3640        let addr = SocketAddr::from(([127, 0, 0, 1], port));
3641        bind_probe(addr).unwrap();
3642        // Nor can a ready_port check connect to it: Linux refuses the
3643        // connection, and macOS lets it time out.
3644        let timeout = std::time::Duration::from_millis(200);
3645        assert!(std::net::TcpStream::connect_timeout(&addr, timeout).is_err());
3646        drop(copy);
3647    }
3648
3649    /// While another thread forks, each child holds copies of the probe sockets
3650    /// open at that moment until it execs. The copies must not make a free
3651    /// port look taken. Where the forks land is up to the scheduler, so the
3652    /// test repeats the check many times.
3653    ///
3654    /// Linux only: macOS refuses a bind to an address and port while a copy of
3655    /// an earlier socket bound there is open, even when neither listens. This
3656    /// test's back-to-back checks of one port would fail on such copies.
3657    #[cfg(target_os = "linux")]
3658    #[tokio::test]
3659    async fn a_free_port_stays_free_while_another_thread_forks() {
3660        use crate::inherited_fds::CloseInheritedFds;
3661        use std::sync::Arc;
3662        use std::sync::atomic::{AtomicBool, Ordering};
3663
3664        let _forks = FORKS.lock().await;
3665        let port = std::net::TcpListener::bind("127.0.0.1:0")
3666            .unwrap()
3667            .local_addr()
3668            .unwrap()
3669            .port();
3670        let stop = Arc::new(AtomicBool::new(false));
3671        let forker = std::thread::spawn({
3672            let stop = stop.clone();
3673            move || {
3674                while !stop.load(Ordering::Relaxed) {
3675                    // close_inherited_fds makes std fork and exec, as the
3676                    // supervisor's spawns do, instead of using posix_spawn.
3677                    std::process::Command::new("true")
3678                        .close_inherited_fds()
3679                        .status()
3680                        .unwrap();
3681                }
3682            }
3683        });
3684        let mut conflicts = Vec::new();
3685        for _ in 0..500 {
3686            conflicts.extend(port_bind_conflict(port).await);
3687        }
3688        stop.store(true, Ordering::Relaxed);
3689        forker.join().unwrap();
3690        assert!(
3691            conflicts.is_empty(),
3692            "free port looked taken on {conflicts:?}"
3693        );
3694    }
3695
3696    fn ip(s: &str) -> IpAddr {
3697        s.parse().unwrap()
3698    }
3699
3700    fn socket(addr: &str, listening: bool, pid: u32) -> TcpSocket {
3701        TcpSocket {
3702            addr: addr.parse::<SocketAddr>().unwrap(),
3703            listening,
3704            pid,
3705            process: format!("p{pid}"),
3706        }
3707    }
3708
3709    #[test]
3710    fn only_a_listener_whose_address_conflicts_is_named() {
3711        let all = || {
3712            [
3713                socket("192.0.2.1:3000", true, 1),
3714                socket("127.0.0.1:3000", true, 2),
3715                socket("[::1]:3000", true, 3),
3716                socket("127.0.0.1:4000", true, 4),
3717            ]
3718        };
3719        // The exact address wins over a wildcard or another address.
3720        assert_eq!(
3721            pick_port_owner(all(), 3000, ip("127.0.0.1")),
3722            Some((2, "p2".into()))
3723        );
3724        assert_eq!(
3725            pick_port_owner(all(), 3000, ip("::1")),
3726            Some((3, "p3".into()))
3727        );
3728        // A wildcard bind conflicts with any listener of its family.
3729        let v4 = pick_port_owner(all(), 3000, ip("0.0.0.0")).unwrap().0;
3730        assert!([1, 2].contains(&v4));
3731        // No socket on a conflicting address: nobody is named.
3732        assert_eq!(
3733            pick_port_owner([socket("[::1]:3000", true, 3)], 3000, ip("127.0.0.1")),
3734            None
3735        );
3736        assert_eq!(pick_port_owner(all(), 5000, ip("127.0.0.1")), None);
3737
3738        // A listener comes before a socket that is not listening, which is
3739        // named when it is all there is.
3740        let both = [
3741            socket("127.0.0.1:3000", false, 5),
3742            socket("0.0.0.0:3000", true, 6),
3743        ];
3744        assert_eq!(
3745            pick_port_owner(both, 3000, ip("127.0.0.1")),
3746            Some((6, "p6".into()))
3747        );
3748        assert_eq!(
3749            pick_port_owner([socket("127.0.0.1:3000", false, 5)], 3000, ip("127.0.0.1")),
3750            Some((5, "p5".into()))
3751        );
3752
3753        // `[::]` may be IPv6-only, so an IPv4 socket, even one that is not
3754        // listening, is named before it for an IPv4 conflict.
3755        let v6_wildcard = || {
3756            [
3757                socket("[::]:3000", true, 7),
3758                socket("127.0.0.1:3000", false, 8),
3759            ]
3760        };
3761        assert_eq!(
3762            pick_port_owner(v6_wildcard(), 3000, ip("127.0.0.1")),
3763            Some((8, "p8".into()))
3764        );
3765        assert_eq!(
3766            pick_port_owner(v6_wildcard(), 3000, ip("0.0.0.0")),
3767            Some((8, "p8".into()))
3768        );
3769        // With no IPv4 socket, it is the only one that can hold the port.
3770        assert_eq!(
3771            pick_port_owner([socket("[::]:3000", true, 7)], 3000, ip("127.0.0.1")),
3772            Some((7, "p7".into()))
3773        );
3774        // A dual-stack socket shows an IPv4 connection as IPv4-mapped.
3775        assert_eq!(
3776            pick_port_owner(
3777                [socket("[::ffff:127.0.0.1]:3000", false, 9)],
3778                3000,
3779                ip("127.0.0.1")
3780            ),
3781            Some((9, "p9".into()))
3782        );
3783
3784        assert_eq!(listener_match(ip("0.0.0.0"), ip("127.0.0.1")), Some(1));
3785        assert_eq!(listener_match(ip("::"), ip("127.0.0.1")), Some(2));
3786        assert_eq!(listener_match(ip("::1"), ip("127.0.0.1")), None);
3787        assert_eq!(listener_match(ip("192.0.2.1"), ip("127.0.0.1")), None);
3788        assert_eq!(shown_address(ip("::1")), "[::1]");
3789    }
3790}
3791
3792#[cfg(test)]
3793mod active_port_tests {
3794    use super::*;
3795    use crate::config_types::PortConfig;
3796    use listeners::{Listener, Process, Protocol, SocketState};
3797    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
3798
3799    fn listener(pid: u32, port: u16, protocol: Protocol, state: SocketState) -> Listener {
3800        Listener {
3801            process: Process {
3802                pid,
3803                name: "test".to_string(),
3804                path: "/test".to_string(),
3805            },
3806            socket: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
3807            protocol,
3808            state,
3809        }
3810    }
3811
3812    #[test]
3813    fn active_port_candidates_exclude_outbound_tcp_and_udp_sockets() {
3814        let daemon_pid = 100;
3815        let child_pid = 101;
3816        let descendant_pids = [daemon_pid, child_pid].into_iter().collect();
3817        let listeners = vec![
3818            listener(child_pid, 3004, Protocol::TCP, SocketState::Listen),
3819            listener(daemon_pid, 47082, Protocol::TCP, SocketState::Established),
3820            listener(daemon_pid, 5353, Protocol::UDP, SocketState::Unknown),
3821            listener(999, 9000, Protocol::TCP, SocketState::Listen),
3822        ];
3823
3824        assert_eq!(
3825            select_active_port(listeners, &descendant_pids, None),
3826            ActivePortSelection::Selected(3004)
3827        );
3828    }
3829
3830    #[test]
3831    fn bumped_cmd_readiness_prefers_resolved_primary_port() {
3832        let daemon = crate::daemon::Daemon {
3833            resolved_port: vec![3004],
3834            port: Some(PortConfig {
3835                expect: vec![3000],
3836                ..PortConfig::default()
3837            }),
3838            ..crate::daemon::Daemon::default()
3839        };
3840        let descendant_pids = [100].into_iter().collect();
3841        let listeners = vec![
3842            listener(100, 9000, Protocol::TCP, SocketState::Listen),
3843            listener(100, 3004, Protocol::TCP, SocketState::Listen),
3844        ];
3845
3846        assert_eq!(discovery_preferred_port(&daemon), Some(3004));
3847        assert_eq!(
3848            select_active_port(
3849                listeners,
3850                &descendant_pids,
3851                discovery_preferred_port(&daemon),
3852            ),
3853            ActivePortSelection::Selected(3004)
3854        );
3855    }
3856
3857    #[test]
3858    fn legacy_state_uses_expected_primary_port_for_discovery() {
3859        let daemon = crate::daemon::Daemon {
3860            port: Some(PortConfig {
3861                expect: vec![3000],
3862                ..PortConfig::default()
3863            }),
3864            ..crate::daemon::Daemon::default()
3865        };
3866
3867        assert_eq!(discovery_preferred_port(&daemon), Some(3000));
3868    }
3869
3870    #[test]
3871    fn ambiguous_candidates_leave_active_port_unset() {
3872        let descendant_pids = [100].into_iter().collect();
3873        let listeners = vec![
3874            listener(100, 9000, Protocol::TCP, SocketState::Listen),
3875            listener(100, 3000, Protocol::TCP, SocketState::Listen),
3876        ];
3877
3878        assert_eq!(
3879            select_active_port(listeners, &descendant_pids, None),
3880            ActivePortSelection::Ambiguous(vec![3000, 9000])
3881        );
3882    }
3883
3884    #[test]
3885    fn bumped_ready_port_sets_only_the_resolved_primary_without_scanning() {
3886        assert_eq!(active_port_from_ready_port(3004, &[3004]), Some(3004));
3887        assert_eq!(active_port_from_ready_port(4003, &[3003, 4003]), None);
3888    }
3889
3890    #[test]
3891    fn delay_readiness_requires_delay_only_and_a_running_process() {
3892        assert!(delay_readiness_succeeded(false, false, false, true));
3893        assert!(!delay_readiness_succeeded(false, true, false, true));
3894        assert!(!delay_readiness_succeeded(false, false, true, false));
3895        assert!(!delay_readiness_succeeded(false, false, false, false));
3896        assert!(!delay_readiness_succeeded(true, false, false, true));
3897    }
3898}
3899
3900/// Check whether a daemon (by its qualified ID) is the target of any registered
3901/// slug in the global config.  This is used to decide whether to run the
3902/// `detect_and_store_active_port` polling task — only slug-targeted daemons need
3903/// it, avoiding wasted `listeners::get_all()` calls for port-less daemons.
3904///
3905/// Delegates to `proxy::server::is_slug_target()` which uses the same in-memory
3906/// slug cache as the proxy hot path, so this check is cheap.
3907fn is_daemon_slug_target(id: &DaemonId) -> bool {
3908    // read_global_slugs is called once per daemon start — acceptable cost.
3909    // We intentionally avoid making this async to keep has_port_config evaluation
3910    // simple and synchronous in run_once().
3911    let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
3912    slugs.iter().any(|(slug, entry)| {
3913        let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
3914        id.name() == daemon_name
3915    })
3916}
3917
3918#[cfg(test)]
3919mod oneshot_tests {
3920    use super::*;
3921
3922    #[test]
3923    fn oneshot_clean_exit_is_completed() {
3924        let (status, success) = terminal_exit_state("exit", true, 0, true);
3925        assert!(matches!(status, DaemonStatus::Completed));
3926        assert!(success);
3927    }
3928
3929    #[test]
3930    fn service_clean_exit_is_still_stopped() {
3931        let (status, success) = terminal_exit_state("exit", false, 0, true);
3932        assert!(matches!(status, DaemonStatus::Stopped));
3933        assert!(success);
3934    }
3935
3936    #[test]
3937    fn oneshot_failure_is_errored_so_retry_applies() {
3938        // check_retry() only picks up errored daemons, so a non-zero exit must
3939        // not be recorded as completed.
3940        let (status, success) = terminal_exit_state("fail", true, 3, false);
3941        assert!(matches!(status, DaemonStatus::Errored(3)));
3942        assert!(!success);
3943    }
3944
3945    #[test]
3946    fn a_stop_cancels_the_retry_sequence_it_finds() {
3947        let id = DaemonId::new("retry-cancel-test", "task");
3948        let claim = SUPERVISOR.mark_retrying(&id);
3949        assert!(!claim.is_cancelled());
3950        assert!(SUPERVISOR.is_retrying(&id));
3951        SUPERVISOR.cancel_retrying(&id);
3952        assert!(claim.is_cancelled());
3953        drop(claim);
3954        assert!(!SUPERVISOR.is_retrying(&id));
3955    }
3956
3957    #[test]
3958    fn a_stop_cancels_every_sequence_for_the_daemon() {
3959        // Two starts can be working through the same daemon's retries: the
3960        // first releases the daemon's lock while it sleeps out a backoff. A
3961        // stop has to end both, not just whichever claimed it last.
3962        let id = DaemonId::new("retry-cancel-test", "concurrent");
3963        let first = SUPERVISOR.mark_retrying(&id);
3964        let second = SUPERVISOR.mark_retrying(&id);
3965        SUPERVISOR.cancel_retrying(&id);
3966        assert!(first.is_cancelled());
3967        assert!(second.is_cancelled());
3968        drop(second);
3969        // The first is still going, so the retry checker must still stand off.
3970        assert!(SUPERVISOR.is_retrying(&id));
3971        drop(first);
3972        assert!(!SUPERVISOR.is_retrying(&id));
3973    }
3974
3975    #[test]
3976    fn a_stop_invalidates_an_attempt_decided_on_before_it() {
3977        // The retry checker reads the epoch when it decides on an attempt and
3978        // `run_retry` compares it under the daemon's lock, so an approval from
3979        // before a stop cannot slip past that stop.
3980        let id = DaemonId::new("stop-epoch-test", "task");
3981        let approved_at = SUPERVISOR.stop_epoch(&id);
3982        assert_eq!(SUPERVISOR.stop_epoch(&id), approved_at);
3983        SUPERVISOR.bump_stop_epoch(&id);
3984        assert_ne!(SUPERVISOR.stop_epoch(&id), approved_at);
3985        // An attempt decided on after the stop is still fine to start.
3986        let approved_after = SUPERVISOR.stop_epoch(&id);
3987        assert_eq!(SUPERVISOR.stop_epoch(&id), approved_after);
3988    }
3989
3990    #[test]
3991    fn stop_epochs_are_tracked_per_daemon() {
3992        let stopped = DaemonId::new("stop-epoch-test", "stopped");
3993        let untouched = DaemonId::new("stop-epoch-test", "untouched");
3994        let approved_at = SUPERVISOR.stop_epoch(&untouched);
3995        SUPERVISOR.bump_stop_epoch(&stopped);
3996        assert_eq!(SUPERVISOR.stop_epoch(&untouched), approved_at);
3997    }
3998
3999    #[test]
4000    fn a_stop_leaves_a_completed_task_alone() {
4001        // It had already done its work, so the stop had nothing to interrupt.
4002        assert!(stop_keeps_finalized_status(&DaemonStatus::Completed));
4003    }
4004
4005    #[test]
4006    fn a_stop_replaces_a_failure_so_retries_do_not_resume() {
4007        // check_retry() picks up errored daemons, so a stop has to overwrite
4008        // one or it will start the task again.
4009        assert!(!stop_keeps_finalized_status(&DaemonStatus::Errored(1)));
4010        assert!(!stop_keeps_finalized_status(&DaemonStatus::Running));
4011        assert!(!stop_keeps_finalized_status(&DaemonStatus::Stopped));
4012    }
4013
4014    #[test]
4015    fn stopped_oneshot_did_not_complete() {
4016        let (status, _) = terminal_exit_state("stop", true, 0, true);
4017        assert!(matches!(status, DaemonStatus::Stopped));
4018    }
4019}
4020
4021#[cfg(all(test, unix))]
4022mod tests {
4023    use super::*;
4024
4025    #[test]
4026    fn test_resolve_run_identity_empty_without_sudo() {
4027        let identity = resolve_run_identity(None, 501, 20, None, None).unwrap();
4028        assert_eq!(identity, RunIdentity::Inherit);
4029    }
4030
4031    #[test]
4032    fn test_resolve_run_identity_sudo_fallback() {
4033        let identity = resolve_run_identity(None, 0, 0, Some("501"), Some("20")).unwrap();
4034        let RunIdentity::Switch { uid, gid, .. } = identity else {
4035            panic!("expected identity switch");
4036        };
4037        assert_eq!(uid.as_raw(), 501);
4038        assert_eq!(gid.as_raw(), 20);
4039    }
4040
4041    #[test]
4042    fn test_resolve_run_identity_ignores_stale_sudo_when_not_root() {
4043        let identity = resolve_run_identity(None, 501, 20, Some("0"), Some("0")).unwrap();
4044        assert_eq!(identity, RunIdentity::Inherit);
4045    }
4046
4047    #[test]
4048    fn test_resolve_configured_user_root_name() {
4049        let identity = resolve_configured_user("root").unwrap();
4050        let RunIdentity::Switch { uid, username, .. } = identity else {
4051            panic!("expected identity switch");
4052        };
4053        assert_eq!(uid.as_raw(), 0);
4054        assert_eq!(
4055            username.as_deref().and_then(|s| s.to_str().ok()),
4056            Some("root")
4057        );
4058    }
4059
4060    #[test]
4061    fn test_resolve_configured_user_root_uid() {
4062        let identity = resolve_configured_user("0").unwrap();
4063        let RunIdentity::Switch { uid, username, .. } = identity else {
4064            panic!("expected identity switch");
4065        };
4066        assert_eq!(uid.as_raw(), 0);
4067        assert_eq!(
4068            username.as_deref().and_then(|s| s.to_str().ok()),
4069            Some("root")
4070        );
4071    }
4072
4073    #[test]
4074    fn test_resolve_configured_user_missing_user_fails() {
4075        let err = resolve_configured_user("pitchfork-user-that-should-not-exist")
4076            .unwrap_err()
4077            .to_string();
4078        assert!(err.contains("does not exist"));
4079    }
4080
4081    #[test]
4082    fn test_resolve_run_identity_requires_root_for_user_switch() {
4083        let err = resolve_run_identity(Some("root"), 501, 20, None, None)
4084            .unwrap_err()
4085            .to_string();
4086        assert!(err.contains("Restart the supervisor with sudo"));
4087    }
4088
4089    #[test]
4090    fn test_resolve_run_identity_same_user_is_noop() {
4091        let identity = resolve_run_identity(Some("root"), 0, 0, Some("501"), Some("20")).unwrap();
4092        assert_eq!(identity, RunIdentity::Inherit);
4093    }
4094
4095    #[test]
4096    fn test_resolve_configured_user_records_home() {
4097        let identity = resolve_configured_user("root").unwrap();
4098        let RunIdentity::Switch { home, .. } = identity else {
4099            panic!("expected identity switch");
4100        };
4101        let expected = nix::unistd::User::from_name("root").unwrap().unwrap().dir;
4102        assert_eq!(home, Some(expected));
4103    }
4104
4105    fn switch_to(name: Option<&str>, home: Option<&str>) -> RunIdentity {
4106        RunIdentity::Switch {
4107            uid: nix::unistd::Uid::from_raw(501),
4108            gid: nix::unistd::Gid::from_raw(20),
4109            username: name.map(|n| CString::new(n).unwrap()),
4110            home: home.map(std::path::PathBuf::from),
4111        }
4112    }
4113
4114    /// The env a command will run with, as set on the command itself:
4115    /// `Some(None)` is an explicit removal, `None` means inherited.
4116    fn command_env(
4117        command: &tokio::process::Command,
4118        key: &str,
4119    ) -> Option<Option<std::ffi::OsString>> {
4120        command
4121            .as_std()
4122            .get_envs()
4123            .find(|(k, _)| *k == key)
4124            .map(|(_, v)| v.map(ToOwned::to_owned))
4125    }
4126
4127    /// Mirrors the order run_once applies them in.
4128    fn daemon_command(
4129        identity: &RunIdentity,
4130        daemon_env: Option<&IndexMap<String, String>>,
4131    ) -> tokio::process::Command {
4132        let mut command = tokio::process::Command::new("true");
4133        apply_identity_env(&mut command, identity);
4134        apply_runtime_env(
4135            &mut command,
4136            &DaemonId::new("identity-env-test", "api"),
4137            0,
4138            daemon_env,
4139            &[],
4140        );
4141        command
4142    }
4143
4144    #[test]
4145    fn test_identity_env_describes_the_switched_user() {
4146        let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), None);
4147        assert_eq!(
4148            command_env(&command, "HOME"),
4149            Some(Some("/home/alice".into()))
4150        );
4151        assert_eq!(command_env(&command, "USER"), Some(Some("alice".into())));
4152        assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4153    }
4154
4155    #[test]
4156    fn test_identity_env_leaves_inherited_env_alone() {
4157        let command = daemon_command(&RunIdentity::Inherit, None);
4158        assert_eq!(command_env(&command, "HOME"), None);
4159        assert_eq!(command_env(&command, "USER"), None);
4160        assert_eq!(command_env(&command, "LOGNAME"), None);
4161    }
4162
4163    #[test]
4164    fn test_root_sudo_to_root_preserves_environment() {
4165        let identity = resolve_run_identity(None, 0, 0, Some("0"), Some("0")).unwrap();
4166        assert_eq!(identity, RunIdentity::Inherit);
4167        let command = daemon_command(&identity, None);
4168        for key in ["HOME", "USER", "LOGNAME"] {
4169            assert_eq!(command_env(&command, key), None);
4170        }
4171    }
4172
4173    #[test]
4174    fn test_daemon_env_overrides_identity_env() {
4175        let mut env = IndexMap::new();
4176        env.insert("HOME".to_string(), "/srv/app".to_string());
4177        env.insert("USER".to_string(), "app".to_string());
4178        let command = daemon_command(&switch_to(Some("alice"), Some("/home/alice")), Some(&env));
4179        assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4180        assert_eq!(command_env(&command, "USER"), Some(Some("app".into())));
4181        assert_eq!(command_env(&command, "LOGNAME"), Some(Some("alice".into())));
4182    }
4183
4184    #[test]
4185    fn test_identity_env_drops_values_without_a_passwd_entry() {
4186        // A sudo uid with no passwd entry: the supervisor's values would still
4187        // describe root, so they are removed instead.
4188        let command = daemon_command(&switch_to(None, None), None);
4189        assert_eq!(command_env(&command, "HOME"), Some(None));
4190        assert_eq!(command_env(&command, "USER"), Some(None));
4191        assert_eq!(command_env(&command, "LOGNAME"), Some(None));
4192    }
4193
4194    #[test]
4195    fn test_daemon_env_restores_values_without_a_passwd_entry() {
4196        let mut env = IndexMap::new();
4197        env.insert("HOME".to_string(), "/srv/app".to_string());
4198        let command = daemon_command(&switch_to(None, None), Some(&env));
4199        assert_eq!(command_env(&command, "HOME"), Some(Some("/srv/app".into())));
4200    }
4201}
4202
4203/// Inject proxy-related environment variables into a daemon's command.
4204///
4205/// Adds:
4206/// - `HOST` — the address the daemon should bind to (`127.0.0.1`, omitted in LAN mode)
4207/// - `PITCHFORK_URL` — the public proxy URL for this daemon (if it has a slug)
4208/// - `PITCHFORK_CA_FILE` / `NODE_EXTRA_CA_CERTS` — path to the pitchfork CA cert (if HTTPS enabled)
4209/// - `__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS` — `.<tld>` for Vite host allowlisting
4210/// - `PITCHFORK_LAN` — set to `"1"` when LAN mode is active
4211fn inject_proxy_env(cmd: &mut tokio::process::Command, host: &Option<String>) {
4212    let s = crate::settings::settings();
4213    let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
4214
4215    if s.proxy.enable && host.is_some() && !lan_enabled {
4216        // Only force loopback binding for daemons the proxy actually routes to.
4217        // In LAN mode, daemons need to bind to 0.0.0.0 to be reachable from the network.
4218        cmd.env("HOST", "127.0.0.1");
4219    }
4220
4221    // PITCHFORK_URL: the daemon's public proxy URL (only if it is routed and proxy is enabled)
4222    if let Some(url) = build_pitchfork_url(host, &s) {
4223        cmd.env("PITCHFORK_URL", &url);
4224    }
4225
4226    // PITCHFORK_CA_FILE / NODE_EXTRA_CA_CERTS: let daemons verify TLS to each
4227    // other through the proxy.  `PITCHFORK_CA_FILE` is the runtime-agnostic
4228    // name; most TLS libraries take a CA bundle path from configuration, and
4229    // several read one straight out of the environment (for example
4230    // `SSL_CERT_FILE` for OpenSSL or `REQUESTS_CA_BUNDLE` for Python).
4231    if s.proxy.enable && s.proxy.https {
4232        let ca_path = if s.proxy.tls_cert.is_empty() {
4233            crate::env::PITCHFORK_STATE_DIR.join("proxy").join("ca.pem")
4234        } else {
4235            std::path::PathBuf::from(&s.proxy.tls_cert)
4236        };
4237        if ca_path.exists() {
4238            let ca_path = ca_path.to_string_lossy().to_string();
4239            cmd.env("PITCHFORK_CA_FILE", &ca_path);
4240            cmd.env("NODE_EXTRA_CA_CERTS", &ca_path);
4241        }
4242    }
4243
4244    // __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: Vite host allowlisting
4245    if s.proxy.enable {
4246        let tld = if lan_enabled { "local" } else { &s.proxy.tld };
4247        cmd.env("__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS", format!(".{tld}"));
4248    }
4249
4250    // PITCHFORK_LAN: signal to daemons that LAN mode is active
4251    if lan_enabled {
4252        cmd.env("PITCHFORK_LAN", "1");
4253    }
4254}
4255
4256/// The hostname the proxy routes to this daemon, without the TLD.
4257///
4258/// A daemon registered under a legacy `[slugs]` entry keeps that spelling,
4259/// because the proxy resolves slugs first. Otherwise the hostname is derived
4260/// from where the daemon's configuration lives.
4261async fn daemon_proxy_host(opts: &RunOptions) -> Option<String> {
4262    // Nothing consumes a hostname while the proxy is off, and deriving one
4263    // reads configuration and walks the project, so daemon starts skip it.
4264    if !crate::settings::settings().proxy.enable {
4265        return None;
4266    }
4267    // A slug carried on the run options skips the lookup below, so it needs the
4268    // same length check that lookup applies; otherwise the daemon is told a URL
4269    // the proxy refuses to route.
4270    if let Some(slug) = opts.slug.as_deref()
4271        && crate::proxy::hostname::hostname_fits(slug)
4272    {
4273        return opts.slug.clone();
4274    }
4275    // The daemon's own `dir` can point outside its project, so look the config
4276    // up from where it was defined.
4277    let config_dir = opts
4278        .watch_base_dir
4279        .clone()
4280        .unwrap_or_else(|| opts.dir.0.clone());
4281    let id = opts.id.clone();
4282    // Reading the config, the slug registry and the project's checkouts is all
4283    // file I/O, so it happens together on a blocking worker rather than on the
4284    // supervisor's executor. The lookup is the one the CLI and the proxy use,
4285    // so the daemon is told the address they advertise for it — a registered
4286    // slug when it has one, otherwise its automatic hostname.
4287    tokio::task::spawn_blocking(move || {
4288        let pt = crate::pitchfork_toml::PitchforkToml::all_merged_from(&config_dir).ok()?;
4289        let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
4290        crate::proxy::hostname::host_for_daemon(&id, pt.daemons.get(&id), &slugs)
4291    })
4292    .await
4293    .unwrap_or_default()
4294}
4295
4296/// Compute the public proxy URL for a daemon.
4297///
4298/// Returns `None` if the daemon has no hostname or the proxy is not enabled.
4299fn build_pitchfork_url(host: &Option<String>, s: &crate::settings::Settings) -> Option<String> {
4300    crate::proxy::build_proxy_url(host.as_deref(), s)
4301}
4302
4303#[cfg(test)]
4304mod ready_check_tests {
4305    use super::*;
4306    use std::time::Duration;
4307
4308    #[test]
4309    fn any_ready_check_remaining_prefers_unbounded_checks() {
4310        let http = ReadyHttp::new("http://localhost/health");
4311        let cmd = ReadyCmd::new("true");
4312
4313        assert!(any_ready_check_remaining(
4314            None,
4315            false,
4316            None,
4317            false,
4318            Some(&http),
4319            false,
4320            None,
4321            false
4322        ));
4323        assert!(any_ready_check_remaining(
4324            None,
4325            false,
4326            None,
4327            false,
4328            None,
4329            false,
4330            Some(&cmd),
4331            false
4332        ));
4333        assert!(any_ready_check_remaining(
4334            None,
4335            false,
4336            Some(&ReadyPort::new(8080)),
4337            false,
4338            Some(&http),
4339            true,
4340            Some(&cmd),
4341            true
4342        ));
4343    }
4344
4345    #[test]
4346    fn any_ready_check_remaining_exhausted_timed_checks() {
4347        let http = ReadyHttp {
4348            url: "http://localhost/health".to_string(),
4349            status: vec![],
4350            timeout: Some(Duration::from_secs(5)),
4351        };
4352        let cmd = ReadyCmd {
4353            run: "true".into(),
4354            timeout: Some(Duration::from_secs(5)),
4355        };
4356
4357        assert!(any_ready_check_remaining(
4358            None,
4359            false,
4360            None,
4361            false,
4362            Some(&http),
4363            false,
4364            Some(&cmd),
4365            false
4366        ));
4367        assert!(!any_ready_check_remaining(
4368            None,
4369            false,
4370            None,
4371            false,
4372            Some(&http),
4373            true,
4374            Some(&cmd),
4375            true
4376        ));
4377    }
4378
4379    #[tokio::test]
4380    async fn spawn_cmd_probe_reports_success() {
4381        let id = DaemonId::new("global", "probe-test");
4382        let probe = spawn_cmd_probe(&id, &"true".into(), &std::env::temp_dir(), 0, None, &[]);
4383        let status = probe.result_rx.await.unwrap().unwrap();
4384        assert!(status.success());
4385    }
4386
4387    /// The argv form runs the program with each argument exactly as written:
4388    /// the probe passes only if the program sees a single argument containing
4389    /// a space and characters a shell would expand.
4390    #[cfg(unix)]
4391    #[tokio::test]
4392    async fn spawn_cmd_probe_runs_an_argv_without_a_shell() {
4393        let id = DaemonId::new("global", "probe-test");
4394        let argv = |arg: &str| -> RunCommand {
4395            RunCommand::Argv(
4396                ["test", arg, "=", "a b $HOME %PATH% &"]
4397                    .map(str::to_string)
4398                    .to_vec(),
4399            )
4400        };
4401        let probe = spawn_cmd_probe(
4402            &id,
4403            &argv("a b $HOME %PATH% &"),
4404            &std::env::temp_dir(),
4405            0,
4406            None,
4407            &[],
4408        );
4409        assert!(probe.result_rx.await.unwrap().unwrap().success());
4410        // Through a shell, the unquoted string would split and expand, and fail.
4411        let probe = spawn_cmd_probe(
4412            &id,
4413            &"test a b $HOME %PATH% & = 'a b $HOME %PATH% &'".into(),
4414            &std::env::temp_dir(),
4415            0,
4416            None,
4417            &[],
4418        );
4419        assert!(!probe.result_rx.await.unwrap().unwrap().success());
4420        let probe = spawn_cmd_probe(&id, &argv("different"), &std::env::temp_dir(), 0, None, &[]);
4421        assert!(!probe.result_rx.await.unwrap().unwrap().success());
4422    }
4423
4424    #[tokio::test]
4425    async fn spawn_cmd_probe_stops_on_request() {
4426        let id = DaemonId::new("global", "probe-test");
4427        let probe = spawn_cmd_probe(&id, &"sleep 30".into(), &std::env::temp_dir(), 0, None, &[]);
4428        let CmdProbe {
4429            cancel_tx,
4430            result_rx,
4431        } = probe;
4432        let _ = cancel_tx.send(());
4433        let status = result_rx.await.unwrap().unwrap();
4434        assert!(!status.success());
4435    }
4436
4437    #[tokio::test]
4438    async fn spawn_cmd_probe_receives_daemon_and_resolved_port_environment() {
4439        let id = DaemonId::new("worktree", "api");
4440        let daemon_env = IndexMap::from([("CUSTOM_VALUE".to_string(), "yes".to_string())]);
4441        // Written for the platform's default shell: cmd.exe reads the probe
4442        // as written, so it needs cmd's own `%VAR%` syntax there.
4443        let check = if cfg!(windows) {
4444            r#"(if "%CUSTOM_VALUE%"=="yes" if "%PORT%"=="4100" if "%PORT0%"=="4100" if "%PORT1%"=="5100" if "%PITCHFORK_DAEMON_ID%"=="worktree/api" if "%PITCHFORK_RETRY_COUNT%"=="2" exit 0) & exit 1"#
4445        } else {
4446            r#"test "$CUSTOM_VALUE" = yes && test "$PORT" = 4100 && test "$PORT0" = 4100 && test "$PORT1" = 5100 && test "$PITCHFORK_DAEMON_ID" = worktree/api && test "$PITCHFORK_RETRY_COUNT" = 2"#
4447        };
4448        let probe = spawn_cmd_probe(
4449            &id,
4450            &check.into(),
4451            &std::env::temp_dir(),
4452            2,
4453            Some(&daemon_env),
4454            &[4100, 5100],
4455        );
4456        let status = probe.result_rx.await.unwrap().unwrap();
4457        assert!(status.success());
4458    }
4459
4460    #[test]
4461    fn configured_ready_port_follows_expected_port_bump() {
4462        assert_eq!(resolve_configured_ready_port(3000, &[3000], &[3004]), 3004);
4463        assert_eq!(
4464            resolve_configured_ready_port(4000, &[3000, 4000], &[3003, 4003]),
4465            4003
4466        );
4467        assert_eq!(resolve_configured_ready_port(8080, &[3000], &[3004]), 8080);
4468    }
4469}
4470
4471#[cfg(test)]
4472mod launch_command_tests {
4473    use super::{invalid_argv_program, launch_command};
4474    use crate::daemon_id::DaemonId;
4475
4476    #[test]
4477    fn refuses_an_argv_whose_program_rendered_empty_or_to_exec() {
4478        let id = DaemonId::new("proj", "api");
4479        assert!(invalid_argv_program(&id, &[]).is_some());
4480        assert!(invalid_argv_program(&id, &words(&["", "server.js"])).is_some());
4481        assert!(invalid_argv_program(&id, &words(&["exec", "node"])).is_some());
4482        assert_eq!(invalid_argv_program(&id, &words(&["node", ""])), None);
4483    }
4484
4485    #[test]
4486    fn refuses_a_probe_array_whose_program_rendered_empty_or_to_exec() {
4487        use super::invalid_probe_program;
4488        use crate::pitchfork_toml::RunCommand;
4489        let id = DaemonId::new("proj", "api");
4490        for field in ["ready_cmd", "health_cmd"] {
4491            let check =
4492                |run: Vec<String>| invalid_probe_program(&id, field, Some(&RunCommand::Argv(run)));
4493            assert!(check(vec![]).unwrap().contains(field));
4494            assert!(check(words(&["", "-h"])).is_some());
4495            assert!(check(words(&["exec", "pg_isready"])).is_some());
4496            assert_eq!(check(words(&["pg_isready", ""])), None);
4497        }
4498        // The string form goes through the shell, and no command is fine.
4499        assert_eq!(
4500            invalid_probe_program(&id, "health_cmd", Some(&RunCommand::Shell(String::new()))),
4501            None
4502        );
4503        assert_eq!(invalid_probe_program(&id, "health_cmd", None), None);
4504    }
4505
4506    fn words(words: &[&str]) -> Vec<String> {
4507        words.iter().map(|w| w.to_string()).collect()
4508    }
4509
4510    #[test]
4511    fn windows_rejects_only_enabled_unsupported_options() {
4512        let mut opts = crate::daemon::RunOptions::default();
4513        assert_eq!(super::unsupported_windows_options(&opts, ""), None);
4514        opts.pty = Some(false);
4515        opts.user = Some(" \t".into());
4516        assert_eq!(super::unsupported_windows_options(&opts, " \t"), None);
4517        opts.pty = Some(true);
4518        assert!(
4519            super::unsupported_windows_options(&opts, "")
4520                .unwrap()
4521                .contains("pty = true")
4522        );
4523        opts.pty = Some(false);
4524        opts.user = Some("postgres".into());
4525        assert!(
4526            super::unsupported_windows_options(&opts, "")
4527                .unwrap()
4528                .contains("user switching")
4529        );
4530        opts.user = None;
4531        assert!(
4532            super::unsupported_windows_options(&opts, "postgres")
4533                .unwrap()
4534                .contains("settings.supervisor.user")
4535        );
4536    }
4537
4538    #[test]
4539    fn starts_the_first_word_with_the_rest_as_arguments() {
4540        let argv = words(&["node", "my server.js", "--name=\"a b\"", "&", "%PATH%"]);
4541        assert_eq!(
4542            launch_command(argv, None),
4543            (
4544                "node".to_string(),
4545                words(&["my server.js", "--name=\"a b\"", "&", "%PATH%"])
4546            )
4547        );
4548    }
4549
4550    #[test]
4551    fn mise_receives_every_word_after_the_separator() {
4552        let argv = words(&["node", "my server.js", "'single'"]);
4553        let mise = std::path::Path::new("/opt/mise/bin/mise");
4554        let (program, args) = launch_command(argv, Some(mise));
4555        assert_eq!(program, mise.to_string_lossy());
4556        assert_eq!(
4557            args,
4558            words(&["x", "--", "node", "my server.js", "'single'"])
4559        );
4560    }
4561}
4562
4563#[cfg(all(test, windows))]
4564mod windows_retry_tests {
4565    use super::*;
4566    use crate::config_types::{Dir, Retry};
4567    use crate::settings::reload_settings;
4568    use std::process::Stdio;
4569    use tokio::io::AsyncBufReadExt;
4570
4571    #[tokio::test]
4572    async fn forced_retry_claim_revalidates_settings_before_stopping_a_live_instance() {
4573        const CHILD_ENV: &str = "PITCHFORK_TEST_WINDOWS_RETRY_CLAIM";
4574        const CHILD_SENTINEL: &str = "windows-retry-claim-child-ran";
4575        if std::env::var_os(CHILD_ENV).is_none() {
4576            // Settings and supervisor state are process globals. Give their
4577            // reload and persistence private directories in an isolated test.
4578            let temp = tempfile::tempdir().unwrap();
4579            std::fs::create_dir(temp.path().join("config")).unwrap();
4580            std::fs::write(
4581                temp.path().join("pitchfork.toml"),
4582                "[settings.supervisor]\nuser = ''\n",
4583            )
4584            .unwrap();
4585            let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());
4586            for (name, _) in std::env::vars_os() {
4587                if name
4588                    .to_string_lossy()
4589                    .to_ascii_uppercase()
4590                    .starts_with("PITCHFORK_")
4591                {
4592                    command.env_remove(name);
4593                }
4594            }
4595            command
4596                .args([
4597                    "--exact",
4598                    "supervisor::lifecycle::windows_retry_tests::forced_retry_claim_revalidates_settings_before_stopping_a_live_instance",
4599                    "--nocapture",
4600                ])
4601                .current_dir(temp.path())
4602                .env(CHILD_ENV, "1")
4603                .env("PITCHFORK_CONFIG_DIR", temp.path().join("config"))
4604                .env("PITCHFORK_STATE_DIR", temp.path().join("state"))
4605                .env("PITCHFORK_LOGS_DIR", temp.path().join("logs"))
4606                .env("PITCHFORK_BOOT_EXECUTABLE", temp.path().join("missing.exe"))
4607                .hide_console_window()
4608                .kill_on_drop(true);
4609            let output = time::timeout(Duration::from_secs(30), command.output())
4610                .await
4611                .expect("isolated retry claim test timed out")
4612                .unwrap();
4613            assert!(
4614                output.status.success(),
4615                "isolated retry claim test failed:\nstdout:\n{}\nstderr:\n{}",
4616                String::from_utf8_lossy(&output.stdout),
4617                String::from_utf8_lossy(&output.stderr)
4618            );
4619            assert!(String::from_utf8_lossy(&output.stderr).contains(CHILD_SENTINEL));
4620            return;
4621        }
4622        eprintln!("{CHILD_SENTINEL}");
4623
4624        let mut opts = RunOptions {
4625            id: DaemonId::new("windows-retry", "live"),
4626            force: true,
4627            wait_ready: true,
4628            retry: Retry(2),
4629            dir: Dir(env::CWD.clone()),
4630            ..RunOptions::default()
4631        };
4632        let mut restart_mark = None;
4633        let mut guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
4634        assert!(
4635            SUPERVISOR
4636                .claim_or_defer(&opts, &mut guard, &mut restart_mark)
4637                .await
4638                .unwrap()
4639                .is_none()
4640        );
4641        drop(guard.take());
4642        let retrying_claim = SUPERVISOR.mark_retrying(&opts.id);
4643
4644        // Model another start taking the record during the foreground retry's
4645        // backoff. Keep its process handle open to pin the PID. On a panic,
4646        // kill_on_drop terminates it; if the isolated test itself is killed,
4647        // closing its stdin also releases the waiting PowerShell process.
4648        let powershell = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
4649            .join("System32/WindowsPowerShell/v1.0/powershell.exe");
4650        let mut child = tokio::process::Command::new(powershell)
4651            .args([
4652                "-NoLogo",
4653                "-NoProfile",
4654                "-NonInteractive",
4655                "-Command",
4656                "[Console]::Out.WriteLine('READY'); [Console]::In.ReadToEnd() | Out-Null",
4657            ])
4658            .current_dir(std::env::var_os("SystemRoot").unwrap())
4659            .stdin(Stdio::piped())
4660            .stdout(Stdio::piped())
4661            .stderr(Stdio::null())
4662            .kill_on_drop(true)
4663            .hide_console_window()
4664            .spawn()
4665            .unwrap();
4666        let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap());
4667        let mut ready = String::new();
4668        stdout.read_line(&mut ready).await.unwrap();
4669        assert_eq!(ready.trim_end(), "READY");
4670        let pid = child.id().unwrap();
4671        PROCS.refresh_pids(&[pid]);
4672        assert!(PROCS.is_running(pid));
4673        assert!(child.try_wait().unwrap().is_none());
4674        guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
4675        let running = SUPERVISOR
4676            .upsert_daemon(
4677                UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
4678                    .set(|o| o.pid = Some(pid))
4679                    .build(),
4680            )
4681            .await
4682            .unwrap();
4683        assert!(running.start_time.is_some());
4684        assert_eq!(running.start_time, PROCS.start_time(pid));
4685        let stop_epoch = SUPERVISOR.stop_epoch(&opts.id);
4686
4687        std::fs::write(
4688            env::CWD.join("pitchfork.toml"),
4689            "[settings.supervisor]\nuser = 'unsupported-account'\n",
4690        )
4691        .unwrap();
4692        reload_settings();
4693        assert_eq!(settings().supervisor.user, "unsupported-account");
4694        opts.retry_count = 1;
4695        let response = SUPERVISOR
4696            .claim_or_defer(&opts, &mut guard, &mut restart_mark)
4697            .await
4698            .unwrap();
4699
4700        // Check the destructive boundary's effects, not just its diagnostic.
4701        assert!(
4702            child.try_wait().unwrap().is_none(),
4703            "the live instance was stopped"
4704        );
4705        let preserved = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
4706        assert_eq!(preserved.pid, Some(pid));
4707        assert!(preserved.status.is_running());
4708        assert_eq!(
4709            serde_json::to_value(&preserved).unwrap(),
4710            serde_json::to_value(&running).unwrap()
4711        );
4712        assert_eq!(SUPERVISOR.stop_epoch(&opts.id), stop_epoch);
4713        assert!(!retrying_claim.is_cancelled());
4714        assert!(restart_mark.is_none());
4715        assert!(matches!(response, Some(IpcResponse::DaemonFailed { .. })));
4716        drop(guard.take());
4717        child.kill().await.unwrap();
4718        child.wait().await.unwrap();
4719
4720        // The same rejection must settle a retry without a process, so the
4721        // background checker cannot keep picking up its old errored record.
4722        opts.id = DaemonId::new("windows-retry", "pidless");
4723        guard = Some(SUPERVISOR.stop_lock(&opts.id).await.lock_owned().await);
4724        SUPERVISOR
4725            .upsert_daemon(
4726                UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Errored(7)).build(),
4727            )
4728            .await
4729            .unwrap();
4730        assert!(matches!(
4731            SUPERVISOR
4732                .claim_or_defer(&opts, &mut guard, &mut restart_mark)
4733                .await
4734                .unwrap(),
4735            Some(IpcResponse::DaemonFailed { .. })
4736        ));
4737        let failed = SUPERVISOR.get_daemon(&opts.id).await.unwrap();
4738        assert!(failed.status.is_failed());
4739        assert!(failed.pid.is_none());
4740        assert_eq!(failed.retry_count, 1);
4741        assert_eq!(failed.retry, Retry(2));
4742    }
4743}
4744
4745#[cfg(test)]
4746mod output_reader_tests {
4747    use super::{forward_output_lines, output_line_text};
4748
4749    #[test]
4750    fn line_endings_are_removed() {
4751        assert_eq!(output_line_text(b"ready\n"), "ready");
4752        // A PTY's ONLCR, and a program that already wrote `\r\n` through it.
4753        assert_eq!(output_line_text(b"ready\r\n"), "ready");
4754        assert_eq!(output_line_text(b"ready\r\r\n"), "ready");
4755        // The last line of the output may have no newline at all.
4756        assert_eq!(output_line_text(b"ready"), "ready");
4757    }
4758
4759    #[tokio::test]
4760    async fn a_line_that_is_not_utf8_does_not_end_the_read() {
4761        // What cut the output off before: `next_line` fails on the second
4762        // line, and nothing after it was read.
4763        let output: &[u8] = b"before\nbad \xff\xfe bytes\nafter 1\nafter 2\nlast";
4764        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
4765        forward_output_lines(tokio::io::BufReader::new(output), tx).await;
4766
4767        let mut lines = Vec::new();
4768        while let Some(line) = rx.recv().await {
4769            lines.push(line.text);
4770        }
4771        assert_eq!(lines.len(), 5, "{lines:?}");
4772        assert_eq!(lines[0], "before");
4773        assert!(lines[1].starts_with("bad "), "{:?}", lines[1]);
4774        assert_eq!(&lines[2..], ["after 1", "after 2", "last"]);
4775    }
4776}
4777
4778#[cfg(test)]
4779mod output_reader_eio_tests {
4780    use super::forward_output_lines;
4781    use std::pin::Pin;
4782    use std::task::{Context, Poll};
4783
4784    /// Output that ends as a Linux PTY master does once the slave closes:
4785    /// the last bytes, with no newline, then `EIO` instead of end of file.
4786    struct EndsWithEio(Option<&'static [u8]>);
4787
4788    impl tokio::io::AsyncRead for EndsWithEio {
4789        fn poll_read(
4790            mut self: Pin<&mut Self>,
4791            _cx: &mut Context<'_>,
4792            buf: &mut tokio::io::ReadBuf<'_>,
4793        ) -> Poll<std::io::Result<()>> {
4794            match self.0.take() {
4795                Some(bytes) => {
4796                    buf.put_slice(bytes);
4797                    Poll::Ready(Ok(()))
4798                }
4799                None => Poll::Ready(Err(std::io::Error::from_raw_os_error(5))),
4800            }
4801        }
4802    }
4803
4804    #[tokio::test]
4805    async fn a_last_line_cut_off_by_eio_is_still_forwarded() {
4806        let reader = tokio::io::BufReader::new(EndsWithEio(Some(b"first\nlast without newline")));
4807        let (tx, mut rx) = tokio::sync::mpsc::channel(16);
4808        forward_output_lines(reader, tx).await;
4809
4810        let mut lines = Vec::new();
4811        while let Some(line) = rx.recv().await {
4812            lines.push(line.text);
4813        }
4814        assert_eq!(lines, ["first", "last without newline"]);
4815    }
4816}