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