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