Skip to main content

pitchfork_cli/supervisor/
mod.rs

1//! Supervisor module - daemon process supervisor
2//!
3//! This module is split into focused submodules:
4//! - `state`: State access layer (get/set operations)
5//! - `lifecycle`: Daemon start/stop operations
6//! - `adopt`: Re-adoption of orphaned daemons after a supervisor crash
7//! - `log_sink`: Out-of-process capture of daemon output
8//! - `autostop`: Autostop logic and boot daemon startup
9//! - `retry`: Retry logic with backoff
10//! - `watchers`: Background tasks (interval, cron, file watching)
11//! - `ipc_handlers`: IPC request dispatch
12
13mod adopt;
14mod autostop;
15mod health;
16mod hooks;
17mod idle;
18mod ipc_handlers;
19mod lifecycle;
20mod log_sink;
21#[cfg(unix)]
22mod pty;
23mod retry;
24mod state;
25mod watchers;
26
27use crate::daemon_id::DaemonId;
28use crate::daemon_status::DaemonStatus;
29use crate::deps::reverse_stop_order;
30use crate::ipc::server::{IpcServer, IpcServerHandle, StartupLock};
31
32use crate::procs::PROCS;
33use crate::settings::settings;
34use crate::state_file::StateFile;
35use crate::{Result, env};
36#[cfg(unix)]
37use duct::cmd;
38#[cfg(unix)]
39use miette::IntoDiagnostic;
40use once_cell::sync::Lazy;
41use std::collections::HashMap;
42use std::collections::HashSet;
43use std::fs;
44#[cfg(unix)]
45use std::os::unix::fs::PermissionsExt;
46use std::path::PathBuf;
47use std::process::exit;
48use std::sync::atomic;
49use std::sync::atomic::{AtomicBool, AtomicU32};
50use std::time::Duration;
51#[cfg(unix)]
52use tokio::signal::unix::SignalKind;
53use tokio::sync::{Mutex, Notify};
54use tokio::task::JoinHandle;
55use tokio::{signal, time};
56
57/// Exit statuses reaped by the container-mode zombie reaper for managed daemon
58/// PIDs. On non-Linux Unix platforms where `waitid(WNOWAIT)` is unavailable,
59/// `waitpid(None, WNOHANG)` may race with Tokio's `child.wait()`. When the
60/// zombie reaper wins, the exit status is stashed here so the monitoring task
61/// in lifecycle.rs can recover it instead of treating the ECHILD as a failure.
62///
63/// On Linux this map is unused because the reaper uses `waitid` with `WNOWAIT`
64/// to peek before reaping, which avoids the race entirely.
65#[cfg(all(unix, not(target_os = "linux")))]
66pub(crate) static REAPED_STATUSES: Lazy<Mutex<HashMap<u32, i32>>> =
67    Lazy::new(|| Mutex::new(HashMap::new()));
68
69// Re-export types needed by other modules
70pub(crate) use state::UpsertDaemonOpts;
71
72pub struct Supervisor {
73    pub(crate) state_file: Mutex<StateFile>,
74    pub(crate) pending_notifications: Mutex<Vec<(log::LevelFilter, String)>>,
75    pub(crate) last_refreshed_at: Mutex<time::Instant>,
76    /// Daemons whose retry sequence a foreground `run` is already working
77    /// through, each with the flag that asks it to stop. The backoff between
78    /// its attempts leaves the record errored with no PID, which is exactly
79    /// what `check_retry` looks for, so without this the background checker
80    /// would start the next attempt itself and the foreground call would be
81    /// left reporting on a run it does not own. `stop` raises the flag, so the
82    /// sequence ends rather than starting another attempt behind the user's
83    /// back.
84    /// One flag per claim: two starts can be working through the same
85    /// daemon's retries at once, and a stop has to reach all of them.
86    pub(crate) retrying:
87        std::sync::Mutex<HashMap<DaemonId, Vec<std::sync::Arc<std::sync::atomic::AtomicBool>>>>,
88    /// How many times each daemon has been stopped. The retry checker reads
89    /// this when it decides to run an attempt and again when it is about to
90    /// start one, holding the daemon's lock: a stop in between means the
91    /// attempt it approved is one the user has since called off.
92    pub(crate) stop_epochs: std::sync::Mutex<HashMap<DaemonId, u64>>,
93    /// Map of daemon ID to scheduled autostop time
94    pub(crate) pending_autostops: Mutex<HashMap<DaemonId, time::Instant>>,
95    /// Autostop stops that have been spawned as detached tasks but have not
96    /// yet begun stopping. `cancel_pending_autostops_for_dir` flips the flag
97    /// to call off the stop when a shell re-enters the directory while the
98    /// stop task is still in flight.
99    pub(crate) in_flight_autostops:
100        Mutex<HashMap<DaemonId, std::sync::Arc<std::sync::atomic::AtomicBool>>>,
101    /// Handle for graceful IPC server shutdown
102    pub(crate) ipc_shutdown: Mutex<Option<IpcServerHandle>>,
103    /// Tracks in-flight hook tasks so shutdown can wait for them to complete
104    pub(crate) hook_tasks: Mutex<Vec<JoinHandle<()>>>,
105    /// Number of monitoring tasks that are still running (between process exit
106    /// and hook registration completion). Used by `close()` to know when it is
107    /// safe to drain `hook_tasks`.
108    pub(crate) active_monitors: AtomicU32,
109    /// Signalled by each monitoring task after it finishes registering hooks
110    /// (or decides it has nothing to register). `close()` waits on this.
111    pub(crate) monitor_done: Notify,
112    /// Cancellation token for the proxy server — cancelled on shutdown to
113    /// stop accepting new connections and drain in-flight ones.
114    pub(crate) proxy_cancel: Mutex<Option<tokio_util::sync::CancellationToken>>,
115    /// Join handle for the proxy task so shutdown can wait for cleanup.
116    pub(crate) proxy_task: Mutex<Option<JoinHandle<()>>>,
117    /// Join handle for the loopback DNS resolver, cancelled by `proxy_cancel`.
118    pub(crate) dns_task: Mutex<Option<JoinHandle<()>>>,
119    /// mDNS publisher for LAN mode (None if LAN mode is disabled).
120    /// Shared with the LAN IP monitor task so it can re-publish on IP change.
121    pub(crate) mdns_publisher:
122        Mutex<Option<std::sync::Arc<tokio::sync::Mutex<crate::proxy::mdns::MdnsPublisher>>>>,
123    /// Join handle for the LAN IP monitor task.
124    pub(crate) lan_monitor_task: Mutex<Option<JoinHandle<()>>>,
125    /// Cancellation token for the background state flush task.
126    pub(crate) flush_cancel: std::sync::Mutex<Option<tokio_util::sync::CancellationToken>>,
127    /// Daemons that currently have a live monitoring task (child `wait()`
128    /// monitor or adopted-orphan poll monitor), keyed to the PID being
129    /// monitored plus a unique registration token. Lets orphan
130    /// reconciliation tell a supervised daemon from one whose monitor died
131    /// with a previous supervisor process.
132    pub(crate) monitored: std::sync::Mutex<HashMap<DaemonId, adopt::MonitorEntry>>,
133    /// Where to deliver output a log sink reports over IPC.
134    ///
135    /// A daemon whose output is captured by a sink writes nothing this process
136    /// reads, so the sink evaluates the daemon's readiness pattern itself and
137    /// sends back the line that matched. The monitoring task registers here
138    /// before the sink starts and unregisters when it ends, so a line arriving
139    /// from a sink that outlived its daemon has nowhere to go and is dropped.
140    pub(crate) sink_output: std::sync::Mutex<HashMap<DaemonId, log_sink::Relay>>,
141    /// Per-daemon stop locks. A stop holds the daemon's lock for its whole
142    /// duration (which now includes waiting for the entire process group to
143    /// exit), and starts/orphan-cleanup acquire it first — serializing them
144    /// against in-flight stops instead of racing the Stopping window.
145    pub(crate) stop_locks: Mutex<HashMap<DaemonId, std::sync::Arc<tokio::sync::Mutex<()>>>>,
146    /// Set when `close()` begins. From then on this supervisor's own
147    /// state-file record is on its way out and must not be restored.
148    pub(crate) shutting_down: AtomicBool,
149    /// Set once the starts under way when shutdown began have finished (see
150    /// `freeze_starts`). Everyone who needs the final list of daemons waits
151    /// on the same freeze.
152    starts_frozen: tokio::sync::OnceCell<()>,
153}
154
155/// A line of daemon output on its way to the monitoring task.
156#[derive(Debug, Clone)]
157pub(crate) struct OutputLine {
158    pub(crate) text: String,
159    pub(crate) source: OutputSource,
160}
161
162/// Where a line of daemon output came from, which decides what is left to do
163/// with it.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub(crate) enum OutputSource {
166    /// Read by this process from the daemon's stdout, stderr or PTY master.
167    /// Nothing has been done with it yet.
168    Local,
169    /// Reported by the daemon's log sink, which has already written the line to
170    /// the store — storing it again here would duplicate it.
171    ///
172    /// `fires_hook` is the sink's answer to whether this line passed the
173    /// `on_output` hook's filter and debounce. It is carried rather than
174    /// re-derived because a line can be reported for readiness alone, and
175    /// firing a hook that filters for something else would be wrong.
176    Sink { fires_hook: bool },
177}
178
179pub(crate) fn interval_duration() -> Duration {
180    settings().general_interval()
181}
182
183pub static SUPERVISOR: Lazy<Supervisor> =
184    Lazy::new(|| Supervisor::new().expect("Error creating supervisor"));
185
186pub async fn start_if_not_running() -> Result<()> {
187    let sf = StateFile::get();
188    if let Some(d) = sf.daemons.get(&DaemonId::pitchfork())
189        && supervisor_record_is_live(d)
190    {
191        return Ok(());
192    }
193    // The record can be missing or stale while a supervisor keeps serving
194    // IPC, e.g. when state.toml was replaced or rewritten by another tool.
195    // Starting another one would take over the socket and leave the running
196    // supervisor, and every daemon it manages, unreachable.
197    if crate::ipc::supervisor_listening().await {
198        debug!("supervisor is listening on the IPC socket but not recorded in the state file");
199        return Ok(());
200    }
201    start_in_background()
202}
203
204/// How long `supervisor start/run --force` waits for the supervisor it
205/// replaces to stop serving IPC. A supervisor being stopped keeps its socket until its daemons
206/// have stopped, which can take a while.
207pub(crate) const IPC_SOCKET_RELEASE_TIMEOUT: Duration = Duration::from_secs(30);
208
209/// How long a daemon's monitor keeps reading output left in its pipe after
210/// the process exits, before it records the exit. A child that inherited the
211/// pipe can hold it open for all of that.
212pub(crate) const EXIT_OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
213/// How often changes to the state are written to the state file.
214pub(crate) const STATE_FLUSH_INTERVAL: Duration = Duration::from_secs(1);
215
216/// How long `close()` waits for the LAN IP monitor to stop on its own.
217const LAN_MONITOR_STOP_WAIT: Duration = Duration::from_secs(1);
218/// How long `close()` waits for the DNS resolver to stop on its own.
219const DNS_STOP_WAIT: Duration = Duration::from_secs(5);
220/// How long `close()` waits for the proxy: longer than its own drain budget,
221/// so it finishes on its own terms rather than being cut off mid-drain.
222const PROXY_STOP_WAIT: Duration =
223    Duration::from_secs(crate::proxy::server::SHUTDOWN_DRAIN_BUDGET.as_secs() + 2);
224/// The longest `close()` can spend before it starts stopping daemons.
225const SHUTDOWN_PRE_STOP_BUDGET: Duration = Duration::from_secs(
226    LAN_MONITOR_STOP_WAIT.as_secs() + DNS_STOP_WAIT.as_secs() + PROXY_STOP_WAIT.as_secs(),
227);
228/// How long `close()` waits, once the daemons are stopped, for their
229/// monitoring tasks to register the hooks they fire.
230const MONITOR_DRAIN_WAIT: Duration = Duration::from_secs(5);
231/// How long `close()` then waits for those hooks to finish, all together.
232const HOOK_DRAIN_WAIT: Duration = Duration::from_secs(30);
233/// The longest `close()` can spend after stopping daemons.
234const SHUTDOWN_POST_STOP_BUDGET: Duration =
235    Duration::from_secs(MONITOR_DRAIN_WAIT.as_secs() + HOOK_DRAIN_WAIT.as_secs());
236
237/// Wait until no supervisor is listening on the IPC socket, failing if one
238/// still is after [`IPC_SOCKET_RELEASE_TIMEOUT`].
239///
240/// Used when replacing a supervisor: the old one keeps serving IPC while it
241/// shuts down, and binding the socket before it lets go would leave clients
242/// talking to whichever supervisor they happen to reach.
243pub(crate) async fn wait_for_ipc_socket_release() -> Result<()> {
244    let deadline = time::Instant::now() + IPC_SOCKET_RELEASE_TIMEOUT;
245    let mut waiting = false;
246    while crate::ipc::supervisor_listening().await {
247        if time::Instant::now() >= deadline {
248            return Err(miette::miette!(
249                "another pitchfork supervisor is still listening on {} after {}s; \
250                 stop it with `pitchfork supervisor stop` before starting a new one",
251                crate::ipc::socket_display(),
252                IPC_SOCKET_RELEASE_TIMEOUT.as_secs()
253            ));
254        }
255        if !waiting {
256            info!(
257                "waiting for the supervisor listening on {} to shut down",
258                crate::ipc::socket_display()
259            );
260            waiting = true;
261        }
262        time::sleep(Duration::from_millis(100)).await;
263    }
264    Ok(())
265}
266
267/// Whether the supervisor's own state-file record still describes a live
268/// pitchfork supervisor, rather than a stale entry whose PID the OS has since
269/// handed to an unrelated process.
270///
271/// The record survives crashes and reboots, so a bare liveness probe on its
272/// PID is not enough: after a reboot low PIDs go to early system daemons, and
273/// a `kill(pid, 0)` on one of those says "alive". The check therefore also
274/// requires the identity the supervisor recorded about itself at startup to
275/// match the live process — see [`supervisor_identity_matches`]. When the
276/// PID is alive but the identity does not match, the record is stale; callers
277/// are free to overwrite it and must never signal that PID.
278pub(crate) fn supervisor_record_is_live(record: &crate::daemon::Daemon) -> bool {
279    let Some(pid) = record.pid else {
280        return false;
281    };
282    if !PROCS.is_running(pid) {
283        return false;
284    }
285    if record.start_time.is_none() && record.boot_time.is_none() {
286        // A record from a supervisor older than v2.18.0 carries no identity
287        // at all, so nothing can contradict it. Rather than trust any live
288        // PID, require the process to at least be a pitchfork binary: that
289        // rejects the reboot case (an unrelated system daemon on the PID)
290        // while a still-running old supervisor stays recognisable.
291        PROCS.refresh_pids(&[pid]);
292        let title = PROCS.title(pid);
293        if legacy_supervisor_title_matches(title.as_deref()) {
294            return true;
295        }
296        warn!(
297            "pid {pid} recorded for the supervisor by an older pitchfork is now {title:?}, not a pitchfork process; treating the record as stale"
298        );
299        return false;
300    }
301    if supervisor_identity_matches(
302        record.start_time,
303        PROCS.start_time(pid),
304        record.boot_time,
305        PROCS.boot_time(),
306    ) {
307        return true;
308    }
309    warn!(
310        "pid {pid} recorded for the supervisor belongs to another process now (recorded start_time {:?} boot_time {:?}, live start_time {:?} boot_time {}); treating the record as stale",
311        record.start_time,
312        record.boot_time,
313        PROCS.start_time(pid),
314        PROCS.boot_time()
315    );
316    false
317}
318
319/// Whether a live process name can be a pitchfork supervisor. Only used for
320/// legacy records that carry no start or boot time (see
321/// [`supervisor_record_is_live`]); an unreadable name is not accepted, since
322/// the record has nothing else vouching for it.
323pub(crate) fn legacy_supervisor_title_matches(title: Option<&str>) -> bool {
324    title.is_some_and(|t| t.to_ascii_lowercase().starts_with("pitchfork"))
325}
326
327/// Whether a live process can be the supervisor a state-file record describes.
328///
329/// The kernel start token is the identity, as in [`process_identity_matches`]:
330/// when both the recorded and the live token can be read, they alone decide.
331/// Equal tokens mean the same process generation; different tokens mean the
332/// PID was recycled, within this boot or across a reboot.
333///
334/// The recorded boot time is only consulted when a token is missing on either
335/// side. It must not veto matching tokens: on Linux and macOS the reported
336/// boot time is derived from the realtime clock, so an NTP step or a
337/// sleep/resume moves it while the supervisor keeps running, and treating that
338/// as a reboot would spawn a second supervisor and orphan the first. Without
339/// tokens, though, a boot time from a previous boot is the one thing that can
340/// still prove the record stale, and a record predating both fields is not
341/// contradicted by anything (callers apply a weaker check to those).
342pub(crate) fn supervisor_identity_matches(
343    recorded_start_time: Option<u64>,
344    current_start_time: Option<u64>,
345    recorded_boot_time: Option<u64>,
346    current_boot_time: u64,
347) -> bool {
348    match (recorded_start_time, current_start_time) {
349        (Some(recorded), Some(current)) => recorded == current,
350        _ => recorded_boot_time.is_none_or(|recorded| {
351            recorded.abs_diff(current_boot_time) <= BOOT_TIME_TOLERANCE_SECS
352        }),
353    }
354}
355
356/// Start the supervisor as a detached background process (`pitchfork
357/// supervisor run`). Returns once the process is spawned, not once it is
358/// ready.
359///
360/// On Unix its stderr is appended to the pitchfork log file, it leaves the
361/// caller's session, and it inherits none of the CLI's descriptors beyond
362/// stdio. On Windows it is created without inheriting any handles.
363pub fn start_in_background() -> Result<()> {
364    debug!("starting supervisor in background");
365    // Ensure the log directory exists so we can redirect stderr there.
366    // Panics and other fatal errors from the background supervisor process
367    // would otherwise be silently swallowed.
368    let log_file = &*env::PITCHFORK_LOG_FILE;
369    if let Some(parent) = log_file.parent() {
370        let _ = fs::create_dir_all(parent);
371    }
372    #[cfg(unix)]
373    fix_state_dir_permissions();
374
375    // On Unix, use duct with stderr redirected to the log file.
376    #[cfg(unix)]
377    {
378        let stderr_file = fs::OpenOptions::new()
379            .create(true)
380            .append(true)
381            .open(log_file)
382            .into_diagnostic()?;
383        cmd!(&*env::PITCHFORK_BIN, "supervisor", "run")
384            .env_remove("PITCHFORK_CONFIG")
385            .stdin_null()
386            .stdout_null()
387            .stderr_file(stderr_file)
388            .before_spawn(move |cmd| {
389                use crate::inherited_fds::CloseInheritedFds;
390                use std::os::unix::process::CommandExt;
391                // Descriptors the CLI inherited from its caller must not stay
392                // open in the long-lived supervisor; see crate::inherited_fds.
393                cmd.close_inherited_fds();
394                // SAFETY: the hook only issues the setsid syscall, which is
395                // async-signal-safe, and does not allocate.
396                unsafe {
397                    cmd.pre_exec(move || {
398                        // Leave the caller's session and process group. Left in
399                        // them, the supervisor would receive the SIGHUP the
400                        // kernel sends the foreground process group when the
401                        // controlling terminal hangs up (an ssh logout, a closed
402                        // terminal), and SIGHUP makes it stop every daemon.
403                        // The result is deliberately ignored. In a freshly forked
404                        // child setsid() fails only if a sandbox (seccomp, ...)
405                        // denies it, or the child is already a process group
406                        // leader, which duct never arranges. Failing the spawn
407                        // would stop pitchfork working at all there, which is
408                        // worse than a supervisor that is merely not detached:
409                        // that is how it behaved before. This hook cannot log
410                        // (async-signal-safe only), so it cannot warn either.
411                        let _ = libc::setsid();
412                        Ok(())
413                    });
414                }
415                Ok(())
416            })
417            .start()
418            .into_diagnostic()?;
419    }
420
421    // On Windows, use CreateProcessW directly with bInheritHandles=FALSE.
422    // std::process::Command always sets bInheritHandles=TRUE when any stdio
423    // handle is configured (even Stdio::null()), which causes the background
424    // supervisor to inherit ALL inheritable handles from the parent —
425    // including bats' stdout capture pipe. The supervisor keeps the pipe
426    // open after the CLI exits, and bats hangs forever waiting for EOF.
427    //
428    // CreateProcessW with bInheritHandles=FALSE prevents any handle
429    // inheritance. We pass NUL device handles for stdin/stdout/stderr
430    // via STARTUPINFO without inheriting any parent handles.
431    #[cfg(windows)]
432    {
433        use windows_sys::Win32::Foundation::{CloseHandle, FALSE};
434        use windows_sys::Win32::System::Threading::{
435            CREATE_NO_WINDOW, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DETACHED_PROCESS,
436            PROCESS_INFORMATION, STARTUPINFOW,
437        };
438
439        // With bInheritHandles=FALSE, the child inherits NO parent handles.
440        // The supervisor uses its own internal file-based logger
441        // (PITCHFORK_LOG_FILE), so it doesn't need stdio from the parent.
442        // We don't set STARTF_USESTDHANDLES because that flag requires
443        // bInheritHandles=TRUE to function correctly per Microsoft docs.
444        // Without stdio handles, the detached process gets null stdio by
445        // default, which is exactly what we want.
446        let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() };
447        si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
448
449        let bin_path = &*env::PITCHFORK_BIN;
450        let mut cmd_line: Vec<u16> = format!("\"{}\" supervisor run\0", bin_path.to_string_lossy())
451            .encode_utf16()
452            .collect();
453
454        use std::os::windows::ffi::OsStrExt;
455        let mut vars: Vec<_> = std::env::vars_os()
456            .filter(|(k, _)| !k.to_string_lossy().eq_ignore_ascii_case("PITCHFORK_CONFIG"))
457            .collect();
458        vars.sort_by_key(|(k, _)| k.to_string_lossy().to_uppercase());
459        let mut environment = Vec::<u16>::new();
460        for (key, value) in vars {
461            environment.extend(key.encode_wide());
462            environment.push(b'=' as u16);
463            environment.extend(value.encode_wide());
464            environment.push(0);
465        }
466        environment.extend([0, 0]);
467        let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
468        let ok = unsafe {
469            CreateProcessW(
470                std::ptr::null(),
471                cmd_line.as_mut_ptr(),
472                std::ptr::null(),
473                std::ptr::null(),
474                FALSE, // bInheritHandles = FALSE — the whole point
475                DETACHED_PROCESS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
476                environment.as_ptr().cast(),
477                std::ptr::null(),
478                &si,
479                &mut pi,
480            )
481        };
482
483        if ok == 0 {
484            return Err(miette::miette!(
485                "CreateProcessW failed for supervisor: {}",
486                std::io::Error::last_os_error()
487            ));
488        }
489
490        // Close process/thread handles — we don't need them (detached process).
491        unsafe {
492            CloseHandle(pi.hProcess);
493            CloseHandle(pi.hThread);
494        }
495    }
496
497    Ok(())
498}
499
500/// Decide whether a project session should be removed during refresh.
501///
502/// `recorded_title` is the title snapshot taken at the start of refresh.
503/// `session` is the current state entry re-read under the lock. If the state
504/// has been updated since the snapshot (e.g., re-entered with the same
505/// PID/dir but a new title), we must skip removal to avoid deleting the new
506/// session. The host PID lives in the session key now, so there is no
507/// `liveness_pid` field to compare against.
508#[cfg(any(unix, test))]
509fn should_remove_liveness_session(
510    session: &crate::state_file::ProjectSession,
511    recorded_title: &Option<String>,
512    current_title: Option<&str>,
513    is_running: bool,
514) -> bool {
515    // If the state was updated since the snapshot (e.g., re-entered with the
516    // same PID/dir but a new title), skip removal to avoid deleting the new
517    // session.
518    if session.liveness_title.as_ref() != recorded_title.as_ref() {
519        return false;
520    }
521    // Dead host process — evict.
522    if !is_running {
523        return true;
524    }
525    // Host is alive. Evict only on a real title mismatch (PID reuse). If no
526    // title was recorded, or the current title is unavailable, we cannot
527    // reliably detect PID reuse — keep the session rather than risk evicting
528    // a live process.
529    match (recorded_title.as_deref(), current_title) {
530        (Some(recorded), Some(current)) => recorded != current,
531        _ => false,
532    }
533}
534
535/// How long stopping `daemons` can take on shutdown, on top of `base`.
536///
537/// The supervisor stops its daemons dependents first, one level after
538/// another, and each can take its whole stop timeout plus the wait after
539/// SIGKILL. Killed before it is done, the supervisor leaves the daemons of the
540/// later levels running with no supervisor. So `base` (the
541/// `supervisor.stop_timeout` setting, also each daemon's default timeout) is
542/// extended by every running daemon's stop in turn: an upper bound, since the
543/// daemons of one level stop at the same time.
544pub(crate) fn daemons_stop_budget<'a>(
545    daemons: impl IntoIterator<Item = &'a crate::daemon::Daemon>,
546    base: std::time::Duration,
547) -> std::time::Duration {
548    let pitchfork_id = DaemonId::pitchfork();
549    daemons
550        .into_iter()
551        .filter(|d| d.pid.is_some() && d.id != pitchfork_id)
552        .map(|d| {
553            // A daemon without its own timeout is given the supervisor's.
554            let timeout = d.stop_signal.and_then(|s| s.timeout).unwrap_or(base);
555            timeout + crate::procs::PROCESS_GROUP_SIGKILL_WAIT
556        })
557        .fold(base, |total, stop| total.saturating_add(stop))
558}
559
560/// The longest the supervisor's whole shutdown can take with `daemons` to
561/// stop, so `supervisor stop` can allow for it before killing the supervisor:
562/// the daemons' stops (see [`daemons_stop_budget`]) and what `close()` does
563/// before and after them.
564pub(crate) fn shutdown_budget<'a>(
565    daemons: impl IntoIterator<Item = &'a crate::daemon::Daemon>,
566    base: std::time::Duration,
567) -> std::time::Duration {
568    daemons_stop_budget(daemons, base)
569        .saturating_add(SHUTDOWN_PRE_STOP_BUDGET)
570        .saturating_add(SHUTDOWN_POST_STOP_BUDGET)
571}
572
573/// Set when a graceful shutdown begins, by a signal or a `Shutdown` request.
574/// A signal received after that forces the exit (see `force_exit`).
575static SHUTDOWN_BEGUN: AtomicBool = AtomicBool::new(false);
576
577/// Taken by whichever exit ends the process: a graceful stop once `close()`
578/// has returned, or a forced exit as soon as it starts. The other then waits
579/// for the process to end instead of exiting with its own status, so a forced
580/// exit's status cannot be overtaken by a graceful exit with success.
581static EXIT_CLAIMED: AtomicBool = AtomicBool::new(false);
582
583/// Wait for an exit another path has claimed; it ends the process.
584async fn wait_for_claimed_exit() -> ! {
585    loop {
586        std::future::pending::<()>().await;
587    }
588}
589
590/// End a graceful stop with success, unless a forced exit claimed the process
591/// first.
592async fn exit_gracefully() -> ! {
593    if EXIT_CLAIMED.swap(true, atomic::Ordering::SeqCst) {
594        wait_for_claimed_exit().await
595    }
596    exit(0)
597}
598
599impl Supervisor {
600    pub fn new() -> Result<Self> {
601        Ok(Self {
602            state_file: Mutex::new(StateFile::read(&*env::PITCHFORK_STATE_FILE).unwrap_or_else(
603                |e| {
604                    warn!("failed to read state file, starting with empty state: {e}");
605                    StateFile::new(env::PITCHFORK_STATE_FILE.clone())
606                },
607            )),
608            last_refreshed_at: Mutex::new(time::Instant::now()),
609            pending_notifications: Mutex::new(vec![]),
610            retrying: std::sync::Mutex::new(HashMap::new()),
611            stop_epochs: std::sync::Mutex::new(HashMap::new()),
612            pending_autostops: Mutex::new(HashMap::new()),
613            in_flight_autostops: Mutex::new(HashMap::new()),
614            ipc_shutdown: Mutex::new(None),
615            hook_tasks: Mutex::new(Vec::new()),
616            active_monitors: AtomicU32::new(0),
617            monitor_done: Notify::new(),
618            proxy_cancel: Mutex::new(None),
619            proxy_task: Mutex::new(None),
620            dns_task: Mutex::new(None),
621            mdns_publisher: Mutex::new(None),
622            lan_monitor_task: Mutex::new(None),
623            flush_cancel: std::sync::Mutex::new(None),
624            monitored: std::sync::Mutex::new(HashMap::new()),
625            sink_output: std::sync::Mutex::new(HashMap::new()),
626            stop_locks: Mutex::new(HashMap::new()),
627            shutting_down: AtomicBool::new(false),
628            starts_frozen: tokio::sync::OnceCell::new(),
629        })
630    }
631
632    /// Get (or create) the per-daemon stop lock for `id`.
633    pub(crate) async fn stop_lock(&self, id: &DaemonId) -> std::sync::Arc<tokio::sync::Mutex<()>> {
634        self.stop_locks
635            .lock()
636            .await
637            .entry(id.clone())
638            .or_default()
639            .clone()
640    }
641
642    /// A restart in flight when the previous supervisor exited will never
643    /// finish: no one is left to start the new process. A record it left
644    /// without a process is recorded as stopped, and one whose old process
645    /// was still being stopped as stopping, which is what a plain stop
646    /// interrupted at the same point leaves for orphan cleanup to reconcile.
647    async fn settle_interrupted_restarts(&self) {
648        let mut state_file = self.state_file.lock().await;
649        let restarting: Vec<(DaemonId, bool)> = state_file
650            .daemons
651            .values()
652            .filter(|d| d.status.is_restarting())
653            .map(|d| (d.id.clone(), d.pid.is_some()))
654            .collect();
655        for (id, has_pid) in restarting {
656            let status = if has_pid {
657                DaemonStatus::Stopping
658            } else {
659                DaemonStatus::Stopped
660            };
661            debug!(
662                "daemon {id} was left restarting by a previous supervisor; recording it as {status}"
663            );
664            state_file.set_status(&id, status);
665        }
666    }
667
668    pub async fn start(
669        &self,
670        is_boot: bool,
671        container: bool,
672        web_port: Option<u16>,
673        web_path: Option<String>,
674    ) -> Result<()> {
675        // Ensure the state directory and its contents are accessible by non-root
676        // users. This is needed when the supervisor is started with `sudo` — all
677        // files it creates are owned by root, which prevents normal CLI clients
678        // from reading/writing state or connecting to the IPC socket.
679        #[cfg(unix)]
680        fix_state_dir_permissions();
681
682        // Ignoring Ctrl+C is inherited, so a supervisor started from a process
683        // that ignores it would neither see Ctrl+C itself nor let its daemons
684        // see it: a daemon with `stop_signal = "SIGINT"` would never get the
685        // Ctrl+C sent to stop it. Handle it again before any daemon starts.
686        #[cfg(windows)]
687        if unsafe { windows_sys::Win32::System::Console::SetConsoleCtrlHandler(None, 0) } == 0 {
688            warn!(
689                "failed to stop ignoring Ctrl+C: {}",
690                std::io::Error::last_os_error()
691            );
692        }
693
694        // Refuse to run beside a supervisor that is already listening, and
695        // do so before recording ourselves in the state file or starting any
696        // daemons: taking over its socket would leave it running but
697        // unreachable. (`--force` has already waited for the one it replaced
698        // to let go of the socket.) The lock is held until our own listener
699        // is bound, so a supervisor starting at the same time waits here and
700        // then finds this one listening.
701        let startup_lock = StartupLock::acquire().await?;
702        if crate::ipc::supervisor_listening().await {
703            return Err(miette::miette!(
704                "another pitchfork supervisor is already listening on {}",
705                crate::ipc::socket_display()
706            ));
707        }
708
709        let pid = std::process::id();
710        // Ensure PROCS has data for the supervisor PID before upsert_daemon reads title()
711        PROCS.refresh_pids(&[pid]);
712        // Determine container mode: CLI flag takes priority, then settings.
713        // Running as PID 1 always enables it: orphaned descendants of daemons
714        // re-parent to us, and without the zombie reaper they would accumulate
715        // as unreaped zombies — which also keep their process group alive,
716        // stalling whole-group stop waits indefinitely.
717        let container_mode =
718            container || settings().supervisor.container || std::process::id() == 1;
719        if container_mode {
720            info!("Starting supervisor in container/PID1 mode with pid {pid}");
721        } else {
722            info!("Starting supervisor with pid {pid}");
723        }
724
725        // Whether the previous supervisor exited uncleanly must be read before
726        // we record ourselves in the state file just below (see
727        // `supervisor_exited_uncleanly`); the background cleanup task runs
728        // after that record exists, so it receives the answer instead of
729        // reading it too late.
730        let unclean = supervisor_exited_uncleanly(self).await;
731
732        self.upsert_daemon(
733            UpsertDaemonOpts::builder(DaemonId::pitchfork())
734                .set(|o| {
735                    o.pid = Some(pid);
736                    o.status = DaemonStatus::Running;
737                })
738                .build(),
739        )
740        .await?;
741        self.settle_interrupted_restarts().await;
742        #[cfg(unix)]
743        fix_state_dir_permissions();
744
745        // Self-heal: if the boot registration points to a stale binary path
746        // (e.g. after a brew/mise upgrade), re-register with the current path.
747        // Runs in the background — must not block or fail supervisor startup.
748        tokio::task::spawn_blocking(|| {
749            if let Ok(boot_manager) = crate::boot_manager::BootManager::new() {
750                boot_manager.check_and_reregister_if_stale();
751            }
752        });
753
754        // If the previous supervisor died uncleanly, its daemon child processes
755        // may still be alive (orphaned, re-parented to init).  Terminate them
756        // before starting replacements so we don't end up with duplicate
757        // processes holding the same ports.
758        //
759        // This runs in the background: each orphan kill now waits for its
760        // whole process group to exit (seconds per orphan), and doing that
761        // inline would delay IPC socket creation past the CLI's short connect
762        // budget on autostart. Per-daemon stop locks serialize the cleanup
763        // against any Run/Stop requests that arrive for the same daemon in the
764        // meantime, and boot daemons start after cleanup completes so they
765        // cannot observe an orphan as "already running".
766        let boot_after_cleanup = is_boot;
767        tokio::spawn(async move {
768            cleanup_orphaned_daemons(&SUPERVISOR, unclean).await;
769            if boot_after_cleanup {
770                info!("Boot start mode enabled, starting boot_start daemons");
771                if let Err(e) = SUPERVISOR.start_boot_daemons().await {
772                    error!("failed to start boot daemons: {e}");
773                }
774            }
775        });
776
777        self.interval_watch()?;
778
779        // Run the first cron check synchronously before starting the cron
780        // watcher and IPC server. This registers config-only cron daemons and
781        // fires any `immediate=true` triggers in the foreground, so they cannot
782        // race with a concurrent `pitchfork start` IPC. By the time the cron
783        // watcher's first tick runs, `last_cron_triggered` is already anchored
784        // and the immediate daemons are already running.
785        if let Err(e) = self.check_cron_schedules().await {
786            error!("failed to check cron schedules on startup: {e}");
787        }
788
789        self.cron_watch()?;
790        self.signals()?;
791        self.daemon_file_watch().await?;
792
793        // In container mode, install SIGCHLD handler to reap orphaned/zombie processes
794        #[cfg(unix)]
795        if container_mode {
796            self.reap_zombies()?;
797        }
798
799        // Start web server: CLI --web-port takes priority, then settings.web.auto_start + bind_port
800        let s = settings();
801        let effective_port = web_port.or_else(|| {
802            if s.web.auto_start {
803                match u16::try_from(s.web.bind_port).ok().filter(|&p| p > 0) {
804                    Some(p) => Some(p),
805                    None => {
806                        error!(
807                            "web.bind_port {} is out of valid port range (1-65535), web UI disabled",
808                            s.web.bind_port
809                        );
810                        None
811                    }
812                }
813            } else {
814                None
815            }
816        });
817        // CLI --web-path takes priority, then settings.web.base_path
818        let effective_path = web_path.or_else(|| {
819            let bp = s.web.base_path.clone();
820            if bp.is_empty() { None } else { Some(bp) }
821        });
822        if let Some(port) = effective_port {
823            tokio::spawn(async move {
824                if let Err(e) = crate::web::serve(port, effective_path).await {
825                    error!("Web server error: {e}");
826                }
827            });
828        }
829
830        // Start standalone API server if configured
831        let api_port = if s.api.auto_start {
832            match u16::try_from(s.api.bind_port).ok().filter(|&p| p > 0) {
833                Some(p) => Some(p),
834                None => {
835                    error!(
836                        "api.bind_port {} is out of valid port range (1-65535), API server disabled",
837                        s.api.bind_port
838                    );
839                    None
840                }
841            }
842        } else {
843            None
844        };
845        if let Some(port) = api_port {
846            tokio::spawn(async move {
847                if let Err(e) = crate::web::serve_api(port, None).await {
848                    error!("API server error: {e}");
849                }
850            });
851        }
852
853        // Start reverse proxy server if enabled
854        if s.proxy.enable {
855            // Pre-generate the TLS certificate synchronously before spawning the proxy
856            // task. This ensures the cert exists immediately after `sup start` returns,
857            // so `proxy trust` can be run right away without waiting for the async task.
858            #[cfg(feature = "proxy-tls")]
859            if s.proxy.https {
860                let proxy_dir = crate::env::PITCHFORK_STATE_DIR.join("proxy");
861                let ca_cert_path = proxy_dir.join("ca.pem");
862                let ca_key_path = proxy_dir.join("ca-key.pem");
863                // Checked and written under the CA lock: `proxy setup` may be
864                // generating the same pair right now.
865                match crate::proxy::server::ensure_ca(&ca_cert_path, &ca_key_path, || {
866                    ca_cert_path.exists() && ca_key_path.exists()
867                }) {
868                    Ok(true) => {
869                        info!(
870                            "Generated local CA certificate at {}",
871                            ca_cert_path.display()
872                        );
873                    }
874                    Ok(false) => {}
875                    Err(e) => {
876                        error!("Failed to generate CA certificate: {e}");
877                    }
878                }
879
880                // Auto-trust: attempt to install the CA certificate into the
881                // system trust store. May fail silently due to permissions;
882                // user can run `pitchfork proxy trust` manually.
883                if s.proxy.auto_trust && ca_cert_path.exists() {
884                    use crate::proxy::trust::{AutoTrustResult, auto_trust};
885                    match auto_trust(&ca_cert_path) {
886                        AutoTrustResult::AlreadyTrusted => {}
887                        AutoTrustResult::Trusted => {
888                            info!("CA certificate auto-trusted in system store");
889                        }
890                        AutoTrustResult::NotTrusted { reason } => {
891                            warn!("Auto-trust skipped: {reason}");
892                            warn!("Run `pitchfork proxy trust` to install manually");
893                        }
894                    }
895                }
896            }
897            // Spawn the proxy server and wait for its bind result via a oneshot
898            // channel.  This avoids the TOCTOU race of a pre-flight bind check
899            // while still surfacing binding failures immediately.
900            let (bind_tx, bind_rx) = tokio::sync::oneshot::channel();
901            let proxy_cancel = tokio_util::sync::CancellationToken::new();
902            let proxy_cancel_clone = proxy_cancel.clone();
903            *self.proxy_cancel.lock().await = Some(proxy_cancel);
904            let proxy_task = tokio::spawn(async move {
905                if let Err(e) = crate::proxy::server::serve(bind_tx, proxy_cancel_clone).await {
906                    error!("Proxy server error: {e}");
907                }
908            });
909            *self.proxy_task.lock().await = Some(proxy_task);
910            match bind_rx.await {
911                Ok(Ok(())) => {
912                    info!("Proxy server bound successfully");
913                    // Resolved once and shared: mDNS and the DNS resolver
914                    // must advertise the same address.
915                    let lan_ip = self.resolve_lan_ip().await;
916                    self.start_mdns(lan_ip).await;
917                    self.start_dns_resolver(lan_ip).await;
918                }
919                Ok(Err(msg)) => {
920                    error!("{msg}");
921                    self.add_notification(log::LevelFilter::Error, msg).await;
922                }
923                Err(_) => {
924                    // Sender dropped without sending — serve() panicked or
925                    // returned before signalling.  Already logged by the
926                    // spawn error handler above.
927                }
928            }
929        }
930
931        // Pre-warm slug cache so the first /api/proxies request is fast.
932        // Spawned as a background task so it does not block startup.
933        tokio::spawn(async {
934            crate::proxy::server::get_cached_slugs().await;
935        });
936
937        let (ipc, ipc_handle) = IpcServer::new(startup_lock).await?;
938        *self.ipc_shutdown.lock().await = Some(ipc_handle);
939        self.start_state_flush_task();
940        self.conn_watch(ipc).await
941    }
942
943    /// Start the loopback DNS resolver for the proxy TLD.
944    ///
945    /// The resolver shares the proxy's cancellation token, so it stops with the
946    /// proxy. A bind failure is a notification rather than a fatal error: the
947    /// proxy still works for anyone who reaches it some other way.
948    async fn start_dns_resolver(&self, lan_ip: Option<std::net::Ipv4Addr>) {
949        let s = crate::settings::settings();
950        if !s.proxy.dns {
951            return;
952        }
953        let cfg = crate::proxy::dns::config_from_settings(&s, lan_ip);
954        let port = crate::proxy::dns::dns_port(&s);
955        // Loopback only: the resolver is for this machine's stub resolver, and
956        // LAN peers are served by mDNS instead.
957        let addr = std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, port));
958
959        // The token's guard is held until the handle is stored. `close` takes
960        // the token under this lock before it collects `dns_task`, so it either
961        // runs first — and there is no token to spawn with — or waits until
962        // the handle is in place to be drained. Releasing it earlier left a
963        // window where `close` found no handle and the task outlived shutdown
964        // holding the resolver's sockets.
965        let cancel_guard = self.proxy_cancel.lock().await;
966        let Some(cancel) = cancel_guard.clone() else {
967            return;
968        };
969        let (bind_tx, bind_rx) = tokio::sync::oneshot::channel();
970        let task = tokio::spawn(async move {
971            if let Err(e) = crate::proxy::dns::serve(cfg, addr, bind_tx, cancel).await {
972                error!("DNS resolver error: {e}");
973            }
974        });
975        *self.dns_task.lock().await = Some(task);
976        drop(cancel_guard);
977        match bind_rx.await {
978            Ok(Ok(())) => info!("DNS resolver bound successfully"),
979            Ok(Err(msg)) => {
980                let msg = format!(
981                    "{msg}\nProxy host names will not resolve through pitchfork. \
982                     Choose another port with proxy.dns_port, or set proxy.dns = false."
983                );
984                error!("{msg}");
985                self.add_notification(log::LevelFilter::Error, msg).await;
986            }
987            Err(_) => {}
988        }
989    }
990
991    /// Watch the LAN address and keep the DNS responder, and mDNS when it is
992    /// running, pointed at the current one.
993    ///
994    /// Started even when the mDNS publisher could not be created: the DNS
995    /// responder serves this machine regardless, and an address it keeps
996    /// answering with after the interface has moved is worse than useless.
997    ///
998    /// Does nothing when `proxy.lan_ip` pins an address. That is a choice to
999    /// respect, not a starting point to drift from — the check lives here so
1000    /// neither caller can forget it.
1001    async fn start_lan_ip_monitor(
1002        &self,
1003        initial_ip: std::net::Ipv4Addr,
1004        port: u16,
1005        publisher: Option<std::sync::Arc<tokio::sync::Mutex<crate::proxy::mdns::MdnsPublisher>>>,
1006    ) {
1007        if !crate::settings::settings().proxy.lan_ip.is_empty() {
1008            return;
1009        }
1010        // No cancellation token means `close` has already taken it, so shutdown
1011        // is under way. Spawning here would leave a task polling with no way to
1012        // stop it, and past the point where `close` collects the handle.
1013        //
1014        // Held until the handle is stored, for the reason `start_dns_resolver`
1015        // gives: otherwise `close` can collect `lan_monitor_task` in between.
1016        let cancel_guard = self.proxy_cancel.lock().await;
1017        let Some(cancel) = cancel_guard.clone() else {
1018            debug!("Not starting the LAN IP monitor: the supervisor is shutting down");
1019            return;
1020        };
1021        let monitor_cancel = Some(cancel);
1022        let task = tokio::spawn(async move {
1023            let mut last_ip = initial_ip;
1024            let mut ticker = tokio::time::interval(std::time::Duration::from_secs(5));
1025            ticker.tick().await; // first tick is immediate
1026            loop {
1027                // Cancellation is raced against the tick, not checked after
1028                // it. Checking afterwards means the task only notices once the
1029                // full interval has elapsed, so a shutdown that waits a second
1030                // for it always gives up and aborts instead — the graceful
1031                // path would never once be taken.
1032                match monitor_cancel.as_ref() {
1033                    Some(cancel) => {
1034                        tokio::select! {
1035                            _ = ticker.tick() => {}
1036                            _ = cancel.cancelled() => break,
1037                        }
1038                    }
1039                    None => {
1040                        ticker.tick().await;
1041                    }
1042                }
1043                if let Some(new_ip) = crate::proxy::lan_ip::detect_lan_ip_if_changed(last_ip).await
1044                {
1045                    log::info!("LAN IP changed: {last_ip} → {new_ip}");
1046                    last_ip = new_ip;
1047                    crate::proxy::dns::update_lan_ip(new_ip);
1048                    if let Some(publisher) = publisher.as_ref() {
1049                        publisher.lock().await.republish_all(new_ip, port);
1050                    }
1051                }
1052            }
1053        });
1054        *self.lan_monitor_task.lock().await = Some(task);
1055        drop(cancel_guard);
1056    }
1057
1058    /// Start mDNS publishing for LAN mode (called after the proxy binds successfully).
1059    /// The LAN address mDNS publishes and the DNS resolver answers with.
1060    ///
1061    /// Resolved once and handed to both. Detecting separately in each let them
1062    /// disagree when the interface address changed in between, which would
1063    /// advertise one address over mDNS and serve another over DNS, and probed
1064    /// the network twice at startup for one answer.
1065    ///
1066    /// `None` means LAN mode is off, or is on and the address could not be
1067    /// determined; either way the caller has nothing to publish. The reason is
1068    /// reported here so it is said once rather than by each caller.
1069    async fn resolve_lan_ip(&self) -> Option<std::net::Ipv4Addr> {
1070        let s = crate::settings::settings();
1071        let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
1072        if !s.proxy.enable || !lan_enabled {
1073            return None;
1074        }
1075        if s.proxy.lan_ip.is_empty() {
1076            let detected = crate::proxy::lan_ip::detect_lan_ip().await;
1077            if detected.is_none() {
1078                error!(
1079                    "LAN mode is enabled but no LAN IP address could be detected. \
1080                     Set proxy.lan_ip to a specific address, or ensure you are connected to a network."
1081                );
1082            }
1083            return detected;
1084        }
1085        match s.proxy.lan_ip.parse::<std::net::Ipv4Addr>() {
1086            Ok(ip) => Some(ip),
1087            Err(e) => {
1088                let msg = format!(
1089                    concat!(
1090                        "proxy.lan_ip {:?} is not a valid IPv4 address: {}. ",
1091                        "LAN mode will not start; fix the setting or clear it ",
1092                        "to auto-detect."
1093                    ),
1094                    s.proxy.lan_ip, e
1095                );
1096                error!("{msg}");
1097                self.add_notification(log::LevelFilter::Error, msg).await;
1098                None
1099            }
1100        }
1101    }
1102
1103    async fn start_mdns(&self, lan_ip: Option<std::net::Ipv4Addr>) {
1104        let s = crate::settings::settings();
1105        let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
1106        if !s.proxy.enable || !lan_enabled {
1107            return;
1108        }
1109
1110        let Some(lan_ip) = lan_ip else { return };
1111        let port = u16::try_from(s.proxy.port).unwrap_or(443);
1112
1113        let Some(mut publisher) = crate::proxy::mdns::MdnsPublisher::new(lan_ip) else {
1114            error!("Failed to start mDNS publisher. Is Avahi (Linux) or Bonjour (macOS) running?");
1115            // The DNS responder hands out this address too, and it is useful on
1116            // this machine whether or not mDNS came up. Keep watching the
1117            // interface so its answers do not go stale.
1118            self.start_lan_ip_monitor(lan_ip, port, None).await;
1119            return;
1120        };
1121
1122        // Publish all registered slugs.
1123        let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
1124        for slug in slugs.keys() {
1125            let hostname = format!("{slug}.local");
1126            publisher.publish(&hostname, port);
1127        }
1128
1129        log::info!(
1130            "LAN mode: mDNS publishing on {lan_ip}, {} slug(s) registered",
1131            slugs.len()
1132        );
1133
1134        let publisher = std::sync::Arc::new(tokio::sync::Mutex::new(publisher));
1135
1136        // Start the IP monitor. It declines on its own when the address is
1137        // pinned rather than auto-detected.
1138        self.start_lan_ip_monitor(lan_ip, port, Some(publisher.clone()))
1139            .await;
1140
1141        *self.mdns_publisher.lock().await = Some(publisher);
1142    }
1143
1144    /// Re-read slugs from config and update mDNS records.
1145    ///
1146    /// Publishes new slugs and unpublishes removed ones. Called via IPC when
1147    /// `proxy add` or `proxy remove` modifies the slug registry.
1148    async fn sync_mdns(&self) {
1149        // Clone the Arc and release the outer lock immediately so we don't
1150        // block close() from taking the publisher during shutdown.
1151        let publisher = {
1152            let guard = self.mdns_publisher.lock().await;
1153            match guard.as_ref() {
1154                Some(p) => p.clone(),
1155                None => {
1156                    debug!("sync_mdns: mDNS publisher not active, skipping");
1157                    return;
1158                }
1159            }
1160        };
1161
1162        let s = crate::settings::settings();
1163        let port = u16::try_from(s.proxy.port).unwrap_or(443);
1164
1165        let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
1166        let mut pub_guard = publisher.lock().await;
1167
1168        // Unpublish slugs that no longer exist in config.
1169        let current_keys: Vec<&String> = slugs.keys().collect();
1170        let registered: Vec<String> = pub_guard.registered_hostnames();
1171        for hostname in &registered {
1172            // hostname is "slug.local" — extract slug part.
1173            let slug = hostname.strip_suffix(".local").unwrap_or(hostname);
1174            if !current_keys.iter().any(|k| k.as_str() == slug) {
1175                log::info!("mDNS: unpublishing removed slug {slug}");
1176                pub_guard.unpublish(hostname);
1177            }
1178        }
1179
1180        // Publish new slugs that aren't yet registered.
1181        for slug in slugs.keys() {
1182            let hostname = format!("{slug}.local");
1183            if !pub_guard.is_published(&hostname) {
1184                log::info!("mDNS: publishing new slug {slug}");
1185                pub_guard.publish(&hostname, port);
1186            }
1187        }
1188    }
1189
1190    /// Spawn a background task that periodically flushes the state file to
1191    /// disk if it has been marked dirty.  Uses debouncing (1s interval) to
1192    /// batch rapid state changes.
1193    fn start_state_flush_task(&self) {
1194        let cancel = tokio_util::sync::CancellationToken::new();
1195        *self.flush_cancel.lock().unwrap() = Some(cancel.clone());
1196        tokio::spawn(async move {
1197            let mut interval = time::interval(STATE_FLUSH_INTERVAL);
1198            interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
1199            loop {
1200                tokio::select! {
1201                    _ = interval.tick() => {}
1202                    _ = cancel.cancelled() => {
1203                        debug!("state flush task received shutdown signal");
1204                        break;
1205                    }
1206                }
1207                let state = SUPERVISOR.state_file.lock().await;
1208                if state.is_dirty()
1209                    && let Err(e) = state.write()
1210                {
1211                    warn!("failed to flush state file: {e}");
1212                }
1213            }
1214            debug!("state flush task exiting");
1215        });
1216    }
1217
1218    pub(crate) async fn flush_state(&self) {
1219        let state = self.state_file.lock().await;
1220        if state.is_dirty()
1221            && let Err(e) = state.write()
1222        {
1223            warn!("failed to flush state file: {e}");
1224        }
1225    }
1226
1227    pub(crate) async fn refresh(&self) -> Result<()> {
1228        trace!("refreshing");
1229
1230        // Collect PIDs we need to check (shell PIDs and liveness PIDs)
1231        // This is more efficient than refreshing all processes on the system
1232        let dirs_with_pids = self.get_dirs_with_shell_pids().await;
1233        let liveness_sessions = self.get_liveness_sessions().await;
1234        let pids_to_check: Vec<u32> = dirs_with_pids
1235            .values()
1236            .flatten()
1237            .copied()
1238            .chain(liveness_sessions.iter().map(|(pid, _, _)| *pid))
1239            .collect::<std::collections::HashSet<_>>()
1240            .into_iter()
1241            .collect();
1242
1243        if pids_to_check.is_empty() {
1244            // No PIDs to check, skip the expensive refresh
1245            trace!("no tracked PIDs to check, skipping process refresh");
1246        } else {
1247            debug!("refreshing PIDs: {pids_to_check:?}");
1248            PROCS.refresh_pids(&pids_to_check);
1249        }
1250
1251        let mut last_refreshed_at = self.last_refreshed_at.lock().await;
1252        *last_refreshed_at = time::Instant::now();
1253
1254        self.restore_own_record().await;
1255
1256        #[cfg_attr(not(unix), allow(unused_mut))]
1257        let mut dirs_to_leave: Vec<PathBuf> = Vec::new();
1258
1259        // Prune shell PIDs that are no longer running. This is essential on
1260        // Unix so that exited shells don't keep daemons alive forever.
1261        //
1262        // On Windows, skip this check: Git Bash (MSYS2) PIDs from `$$` are
1263        // Cygwin-internal PIDs that are invisible to sysinfo (which sees
1264        // Windows PIDs). The is_running check would always return false,
1265        // immediately removing every registered shell and breaking autostop.
1266        // Shell registration/deregistration relies on UpdateShellDir IPC
1267        // messages instead.
1268        #[cfg(unix)]
1269        for (dir, pids) in dirs_with_pids {
1270            let to_remove = pids
1271                .iter()
1272                .filter(|pid| !PROCS.is_running(**pid))
1273                .collect::<Vec<_>>();
1274            for pid in &to_remove {
1275                self.remove_shell_pid(**pid).await?
1276            }
1277            if to_remove.len() == pids.len() {
1278                dirs_to_leave.push(dir);
1279            }
1280        }
1281
1282        // Atomically remove project sessions whose host PID has died or whose
1283        // recorded title no longer matches the current process title. Every
1284        // project session carries a host PID in its key, so we iterate all of
1285        // them. Re-reading the sessions under the lock prevents enter/leave
1286        // interleaving from deleting a session that was just replaced with a
1287        // new title snapshot.
1288        //
1289        // Gated to Unix to mirror the shell-PID pruning above: on Windows,
1290        // Git Bash (MSYS2) `$$` PIDs are Cygwin-internal and invisible to
1291        // sysinfo, so the liveness check would immediately revoke every
1292        // freshly-entered session. Windows relies on explicit `project leave`
1293        // (or shell UpdateShellDir) for deregistration instead.
1294        #[cfg(unix)]
1295        {
1296            let mut state = self.state_file.lock().await;
1297            for (pid, dir, recorded_title) in liveness_sessions {
1298                let Some(session) = state.get_project_session(pid, &dir) else {
1299                    continue;
1300                };
1301                let current_title = PROCS.title(pid);
1302                let is_running = PROCS.is_running(pid);
1303                debug!(
1304                    "refresh liveness session pid {pid} dir {} recorded_title={recorded_title:?} current_title={current_title:?} is_running={is_running}",
1305                    dir.display()
1306                );
1307                if should_remove_liveness_session(
1308                    session,
1309                    &recorded_title,
1310                    current_title.as_deref(),
1311                    is_running,
1312                ) {
1313                    warn!(
1314                        "removing project session pid {pid} dir {} (liveness pid title mismatch or dead)",
1315                        dir.display()
1316                    );
1317                    if state.remove_project_session(pid, &dir).is_some() {
1318                        dirs_to_leave.push(dir);
1319                    }
1320                }
1321            }
1322        }
1323
1324        for dir in dirs_to_leave {
1325            self.leave_dir(&dir).await?;
1326        }
1327
1328        // Catch state-`running` daemons that lost their monitor (e.g. the
1329        // monitor died with a previous supervisor): mark dead ones errored
1330        // and re-adopt live ones. Runs before check_retry so a daemon marked
1331        // errored here is retried on this same tick.
1332        self.reconcile_unmonitored_daemons().await;
1333
1334        self.check_retry().await?;
1335        self.process_pending_autostops().await?;
1336
1337        Ok(())
1338    }
1339
1340    /// Install a SIGCHLD handler that reaps orphaned zombie child processes.
1341    ///
1342    /// When running as PID 1 inside a container, orphaned processes are
1343    /// re-parented to PID 1. Without explicit reaping, they accumulate
1344    /// as zombies in the process table indefinitely.
1345    ///
1346    /// Only reaps processes that are NOT managed by the supervisor (i.e.
1347    /// not tracked in the state file). Managed daemon processes are reaped
1348    /// by their monitoring tasks via `child.wait()`.
1349    ///
1350    /// ## Strategy
1351    ///
1352    /// **Linux**: Uses `waitid(Id::All, WNOHANG | WNOWAIT | WEXITED)` to
1353    /// *peek* at the next zombie without consuming its status. If the PID
1354    /// belongs to a managed daemon, the reaper skips it so Tokio's
1355    /// `child.wait()` can collect the status normally. Only unmanaged
1356    /// orphans are actually reaped (via `waitpid(Pid, WNOHANG)`). This
1357    /// eliminates the race entirely.
1358    ///
1359    /// **Non-Linux Unix** (e.g. macOS — mainly for local development;
1360    /// container mode targets Linux): `waitid` is unavailable, so we fall
1361    /// back to `waitpid(None, WNOHANG)`. If the reaper accidentally
1362    /// consumes a managed PID's status, it stashes the exit code in
1363    /// [`REAPED_STATUSES`] for the monitoring task to recover.
1364    #[cfg(unix)]
1365    fn reap_zombies(&self) -> Result<()> {
1366        let mut stream = signal::unix::signal(SignalKind::child())
1367            .map_err(|e| miette::miette!("Failed to register SIGCHLD handler: {e}"))?;
1368        tokio::spawn(async move {
1369            loop {
1370                stream.recv().await;
1371                // Collect PIDs of managed daemons so we don't steal their exit status
1372                let managed_pids: HashSet<u32> = SUPERVISOR
1373                    .state_file
1374                    .lock()
1375                    .await
1376                    .daemons
1377                    .values()
1378                    .filter_map(|d| d.pid)
1379                    .collect();
1380                // Reap all available zombie children that are NOT managed
1381                Self::reap_unmanaged_zombies(&managed_pids).await;
1382            }
1383        });
1384        info!("container mode: SIGCHLD zombie reaper installed");
1385        Ok(())
1386    }
1387
1388    /// Linux implementation: peek with `waitid(WNOWAIT)` then selectively reap.
1389    ///
1390    /// `WNOWAIT` leaves the zombie in the table so we can inspect its PID
1391    /// without consuming the exit status. Only if the PID is *not* managed
1392    /// do we call `waitpid(Pid, WNOHANG)` to actually reap it.
1393    #[cfg(target_os = "linux")]
1394    async fn reap_unmanaged_zombies(managed_pids: &HashSet<u32>) {
1395        use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid, waitpid};
1396        use nix::unistd::Pid;
1397
1398        loop {
1399            // Peek at the next zombie without consuming it
1400            let peek_flags = WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT | WaitPidFlag::WEXITED;
1401            match waitid(Id::All, peek_flags) {
1402                Ok(WaitStatus::StillAlive) => break,
1403                Ok(status) => {
1404                    let Some(pid_raw) = status.pid().map(|p| p.as_raw() as u32) else {
1405                        break;
1406                    };
1407                    if managed_pids.contains(&pid_raw) {
1408                        // This is a managed daemon — leave it for Tokio's child.wait().
1409                        // We must break out of the loop because waitid(Id::All) would
1410                        // keep returning the same zombie if we don't consume it.
1411                        trace!(
1412                            "zombie reaper: skipping managed daemon pid {pid_raw}, \
1413                             leaving for Tokio to reap"
1414                        );
1415                        break;
1416                    }
1417                    // Not managed — actually reap it
1418                    match waitpid(Pid::from_raw(pid_raw as i32), Some(WaitPidFlag::WNOHANG)) {
1419                        Ok(s) => trace!("reaped orphaned zombie child: {s:?}"),
1420                        Err(nix::errno::Errno::ECHILD) => break,
1421                        Err(e) => {
1422                            trace!("waitpid error reaping pid {pid_raw}: {e}");
1423                            break;
1424                        }
1425                    }
1426                }
1427                Err(nix::errno::Errno::ECHILD) => break, // no children at all
1428                Err(e) => {
1429                    trace!("waitid error in zombie reaper: {e}");
1430                    break;
1431                }
1432            }
1433        }
1434    }
1435
1436    /// Non-Linux fallback: blind `waitpid(None, WNOHANG)` with stash recovery.
1437    ///
1438    /// Since `waitid(WNOWAIT)` is not available, we cannot peek. If we
1439    /// accidentally reap a managed PID, we stash the exit code in
1440    /// [`REAPED_STATUSES`] so the monitoring task can recover it.
1441    #[cfg(all(unix, not(target_os = "linux")))]
1442    async fn reap_unmanaged_zombies(managed_pids: &HashSet<u32>) {
1443        use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid};
1444
1445        loop {
1446            match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
1447                Ok(WaitStatus::StillAlive) => break,
1448                Ok(status) => {
1449                    let Some(pid) = status.pid().map(|p| p.as_raw() as u32) else {
1450                        continue;
1451                    };
1452                    if managed_pids.contains(&pid) {
1453                        // Race lost — stash the exit code for lifecycle recovery
1454                        let exit_code = match status {
1455                            WaitStatus::Exited(_, code) => code,
1456                            WaitStatus::Signaled(_, sig, _) => -(sig as i32),
1457                            _ => -1,
1458                        };
1459                        warn!(
1460                            "zombie reaper reaped managed daemon pid {pid} \
1461                             (exit_code={exit_code}); stashing status for recovery"
1462                        );
1463                        REAPED_STATUSES.lock().await.insert(pid, exit_code);
1464                    } else {
1465                        trace!("reaped orphaned zombie child: {status:?}");
1466                    }
1467                }
1468                Err(nix::errno::Errno::ECHILD) => break, // no more children
1469                Err(e) => {
1470                    trace!("waitpid error in zombie reaper: {e}");
1471                    break;
1472                }
1473            }
1474        }
1475    }
1476
1477    #[cfg(unix)]
1478    fn signals(&self) -> Result<()> {
1479        let signals = [
1480            SignalKind::terminate(),
1481            SignalKind::alarm(),
1482            SignalKind::interrupt(),
1483            SignalKind::quit(),
1484            SignalKind::hangup(),
1485            SignalKind::user_defined1(),
1486            SignalKind::user_defined2(),
1487        ];
1488        for signal in signals {
1489            let stream = match signal::unix::signal(signal) {
1490                Ok(s) => s,
1491                Err(e) => {
1492                    warn!("Failed to register signal handler for {signal:?}: {e}");
1493                    continue;
1494                }
1495            };
1496            tokio::spawn(async move {
1497                let mut stream = stream;
1498                loop {
1499                    stream.recv().await;
1500                    if SHUTDOWN_BEGUN.swap(true, atomic::Ordering::SeqCst) {
1501                        SUPERVISOR.force_exit().await;
1502                    } else {
1503                        // Spawned, so this loop keeps receiving: a second
1504                        // signal of the same kind must reach `force_exit`
1505                        // rather than wait for the graceful stop to finish.
1506                        tokio::spawn(SUPERVISOR.handle_signal());
1507                    }
1508                }
1509            });
1510        }
1511        Ok(())
1512    }
1513
1514    #[cfg(windows)]
1515    fn signals(&self) -> Result<()> {
1516        tokio::spawn(async move {
1517            loop {
1518                if let Err(e) = signal::ctrl_c().await {
1519                    error!("Failed to wait for ctrl-c: {}", e);
1520                    return;
1521                }
1522                if SHUTDOWN_BEGUN.swap(true, atomic::Ordering::SeqCst) {
1523                    SUPERVISOR.force_exit().await;
1524                } else {
1525                    tokio::spawn(SUPERVISOR.handle_signal());
1526                }
1527            }
1528        });
1529        Ok(())
1530    }
1531
1532    async fn handle_signal(&self) {
1533        info!("received signal, stopping");
1534        self.close().await;
1535        exit_gracefully().await
1536    }
1537
1538    /// A second signal while `close()` is still stopping daemons: exit now,
1539    /// but kill the daemons not stopped yet first. They run in their own
1540    /// sessions, so exiting without this would leave them running with no
1541    /// supervisor.
1542    async fn force_exit(&self) -> ! {
1543        if EXIT_CLAIMED.swap(true, atomic::Ordering::SeqCst) {
1544            // The graceful stop has finished and is exiting already.
1545            wait_for_claimed_exit().await
1546        }
1547        // Set by `close()` too, but this may run first: from now on a start
1548        // that takes its daemon's lock does not spawn (see `run_once`).
1549        self.shutting_down.store(true, atomic::Ordering::Release);
1550        warn!("received another signal while stopping; killing the remaining daemons and exiting");
1551        let mut killed = HashSet::new();
1552        self.kill_active_daemons(&mut killed).await;
1553        // A start that passed its check before the flag holds its daemon's
1554        // stop lock until the daemon's PID is recorded. Its process is killed
1555        // above if it has already spawned (it is monitored from the moment it
1556        // spawns); wait the locks out for one still on its way, then kill
1557        // again. The stops `close()` holds locks for end quickly now that
1558        // their daemons are killed; the wait is bounded all the same, by one
1559        // deadline for all the locks so a forced exit is not held up by each.
1560        let locks: Vec<_> = self.stop_locks.lock().await.values().cloned().collect();
1561        let deadline = time::Instant::now() + Duration::from_secs(5);
1562        for lock in locks {
1563            let _ = time::timeout_at(deadline, lock.lock()).await;
1564        }
1565        self.kill_active_daemons(&mut killed).await;
1566        exit(1)
1567    }
1568
1569    /// Kill the process group of every active daemon not in `killed` at once,
1570    /// with no grace period, adding each one dealt with to `killed`.
1571    ///
1572    /// Daemons being monitored count as well: a start registers its process
1573    /// for monitoring as soon as it spawns, before its PID is recorded in
1574    /// state, and that can take a while (a cron start writes the state file
1575    /// first).
1576    ///
1577    /// The group is killed even when its leader, the PID on record, has
1578    /// already exited: the graceful stop may have ended a shell whose children
1579    /// ignore the signal. While the group has members its ID cannot be reused,
1580    /// so it is still this daemon's; a live leader is checked against its
1581    /// recorded start time, as `stop` does. A kill that fails is not counted,
1582    /// so a later pass tries again.
1583    async fn kill_active_daemons(&self, killed: &mut HashSet<(DaemonId, u32)>) {
1584        let mut kills = tokio::task::JoinSet::new();
1585        let mut targets: Vec<((DaemonId, u32), Option<u64>)> = self
1586            .active_daemons()
1587            .await
1588            .into_iter()
1589            .filter_map(|d| Some(((d.id, d.pid?), d.start_time)))
1590            .collect();
1591        let monitored: Vec<_> = self
1592            .monitored
1593            .lock()
1594            .expect("monitored lock poisoned")
1595            .iter()
1596            .map(|(id, entry)| (id.clone(), entry.pid))
1597            .collect();
1598        for key in monitored {
1599            if !targets.iter().any(|(k, _)| *k == key) {
1600                // Not recorded yet, so there is no start time to check it
1601                // against; it is a child this supervisor has just spawned.
1602                targets.push((key, None));
1603            }
1604        }
1605        for (key, start_time) in targets {
1606            let pid = key.1;
1607            if killed.contains(&key) {
1608                continue;
1609            }
1610            if PROCS.is_running(pid) {
1611                if !signalling_pid_is_authorized(start_time, PROCS.start_time(pid)) {
1612                    // Recycled: not the daemon's process any more.
1613                    killed.insert(key);
1614                    continue;
1615                }
1616            } else if !PROCS.process_group_alive(pid) {
1617                // Leader and group both gone: nothing left to kill.
1618                killed.insert(key);
1619                continue;
1620            }
1621            kills.spawn(async move {
1622                // The stop signal is followed by SIGKILL at once.
1623                let result = PROCS
1624                    .kill_process_group_async(
1625                        pid,
1626                        crate::config_types::StopSignal::default().into(),
1627                        Some(Duration::from_millis(1)),
1628                    )
1629                    .await;
1630                if let Err(e) = &result {
1631                    error!("failed to kill daemon {}: {e}", key.0);
1632                }
1633                (key, result.is_ok())
1634            });
1635        }
1636        for (key, ok) in kills.join_all().await {
1637            if ok {
1638                killed.insert(key);
1639            }
1640        }
1641    }
1642
1643    /// Stop new daemons from starting, and wait for the starts already under
1644    /// way to finish, so the active daemons can be listed for good.
1645    ///
1646    /// A start that took its daemon's stop lock before `shutting_down` was set
1647    /// may still be spawning; its daemon must be in the list. A start that
1648    /// takes a lock from now on sees the flag and does not spawn (see
1649    /// `run_once`).
1650    ///
1651    /// Done once: a caller that comes while the freeze is under way waits for
1652    /// it to finish, and one that comes later returns at once. By then the
1653    /// locks may be held by `close()`'s stops, which waiting for would hold a
1654    /// `Shutdown` reply until those stops end.
1655    async fn freeze_starts(&self) {
1656        self.shutting_down.store(true, atomic::Ordering::Release);
1657        self.starts_frozen
1658            .get_or_init(|| async {
1659                let locks: Vec<_> = self.stop_locks.lock().await.values().cloned().collect();
1660                for lock in locks {
1661                    drop(lock.lock().await);
1662                }
1663            })
1664            .await;
1665    }
1666
1667    /// Begin a graceful shutdown for `supervisor stop` and return how long it
1668    /// may take: the client waits that long before killing the supervisor.
1669    ///
1670    /// The budget is computed here rather than by the client: only the
1671    /// supervisor knows its own settings, and only once new starts are frozen
1672    /// is the list of daemons to stop final.
1673    pub(crate) async fn begin_shutdown(&self) -> Duration {
1674        // Under way already, the freeze is waited for rather than skipped: a
1675        // daemon whose start it waits for is not listed until that start ends.
1676        // A shutdown that has frozen starts already answers at once, and the
1677        // daemons it has yet to stop are still active.
1678        self.freeze_starts().await;
1679        let base = settings().supervisor_stop_timeout();
1680        let budget = shutdown_budget(&self.active_daemons().await, base);
1681        if !SHUTDOWN_BEGUN.swap(true, atomic::Ordering::SeqCst) {
1682            tokio::spawn(async {
1683                info!("stop requested, stopping");
1684                SUPERVISOR.close().await;
1685                exit_gracefully().await
1686            });
1687        }
1688        budget
1689    }
1690
1691    pub(crate) async fn close(&self) {
1692        self.shutting_down.store(true, atomic::Ordering::Release);
1693        // Signal the proxy server to stop accepting new connections
1694        // and drain in-flight ones, *before* stopping daemons so the
1695        // proxy has time to finish forwarding active requests.
1696        if let Some(cancel) = self.proxy_cancel.lock().await.take() {
1697            cancel.cancel();
1698        }
1699
1700        // Stop the LAN IP monitor task. It watches the token that was just
1701        // cancelled, so give it a moment to come back on its own rather than
1702        // cutting it off mid-iteration the instant after asking it to stop.
1703        if let Some(mut monitor_task) = self.lan_monitor_task.lock().await.take()
1704            && tokio::time::timeout(LAN_MONITOR_STOP_WAIT, &mut monitor_task)
1705                .await
1706                .is_err()
1707        {
1708            monitor_task.abort();
1709        }
1710
1711        // Shutdown the mDNS publisher (sends goodbye packets).
1712        if let Some(publisher) = self.mdns_publisher.lock().await.take() {
1713            publisher.lock().await.shutdown();
1714        }
1715
1716        if let Some(mut dns_task) = self.dns_task.lock().await.take()
1717            && tokio::time::timeout(DNS_STOP_WAIT, &mut dns_task)
1718                .await
1719                .is_err()
1720        {
1721            // Cancelled but still running: aborted, as the LAN monitor is,
1722            // so its sockets are not left bound to the resolver port.
1723            dns_task.abort();
1724        }
1725
1726        if let Some(proxy_task) = self.proxy_task.lock().await.take() {
1727            let _ = tokio::time::timeout(PROXY_STOP_WAIT, proxy_task).await;
1728        }
1729
1730        // Clean up /etc/hosts entries managed by pitchfork
1731        let s = settings();
1732        if s.proxy.enable && s.proxy.sync_hosts {
1733            crate::proxy::hosts::clean_hosts_file();
1734        }
1735
1736        self.freeze_starts().await;
1737
1738        let pitchfork_id = DaemonId::pitchfork();
1739        let active = self.active_daemons().await;
1740        let active_ids: Vec<DaemonId> = active
1741            .iter()
1742            .filter(|d| d.id != pitchfork_id)
1743            .map(|d| d.id.clone())
1744            .collect();
1745
1746        // Stop daemons in reverse dependency order, from the dependencies
1747        // they were started with: the supervisor's own directory need not
1748        // see their projects' config.
1749        // Daemons within the same level are stopped concurrently.
1750        //
1751        // Each stop waits for the daemon's whole process group (bounded by its
1752        // stop budget) and levels are sequential, so total shutdown time is the
1753        // sum of the slowest stop per level. If an external manager (docker,
1754        // systemd) kills us before this completes, cleanup_orphaned_daemons()
1755        // recovers the leftover processes and stale state on the next start.
1756        let daemons = self.state_file.lock().await.daemons.clone();
1757        let ids = active_ids.clone();
1758        let stop_levels =
1759            match tokio::task::spawn_blocking(move || reverse_stop_order(&ids, &daemons)).await {
1760                Ok(levels) => levels,
1761                // Stopping everything at once still stops everything.
1762                Err(e) => {
1763                    error!("computing the shutdown order panicked: {e}");
1764                    vec![active_ids.clone()]
1765                }
1766            };
1767        for level in &stop_levels {
1768            let mut tasks = Vec::new();
1769            for id in level {
1770                let id = id.clone();
1771                tasks.push(tokio::spawn(async move {
1772                    if let Err(err) = SUPERVISOR.stop(&id).await {
1773                        error!("failed to stop daemon {id}: {err}");
1774                    }
1775                }));
1776            }
1777            for task in tasks {
1778                let _ = task.await;
1779            }
1780        }
1781        // A forced exit kills the daemons, so the stops above can finish
1782        // before it has. Shutting the IPC server down next would let the
1783        // supervisor return and exit with success, so leave the exit to it.
1784        // (A graceful stop claims the exit only after this returns.)
1785        if EXIT_CLAIMED.load(atomic::Ordering::SeqCst) {
1786            wait_for_claimed_exit().await
1787        }
1788        let _ = self.remove_daemon(&pitchfork_id).await;
1789
1790        // Signal the background state flush task to exit so it doesn't
1791        // keep waking up and acquiring the state mutex after shutdown.
1792        if let Some(cancel) = self.flush_cancel.lock().unwrap().take() {
1793            cancel.cancel();
1794        }
1795
1796        // Force-flush state to disk before shutting down IPC so no
1797        // in-memory-only changes are lost.
1798        {
1799            let state = self.state_file.lock().await;
1800            if state.is_dirty()
1801                && let Err(e) = state.write()
1802            {
1803                warn!("failed to flush state file during shutdown: {e}");
1804            }
1805        }
1806
1807        // Signal IPC server to shut down gracefully
1808        if let Some(mut handle) = self.ipc_shutdown.lock().await.take() {
1809            handle.shutdown().await;
1810        }
1811
1812        // Wait for all in-flight monitoring tasks to finish registering their
1813        // hook handles. Each monitoring task increments `active_monitors` when
1814        // its process exits, and decrements it (+ notifies `monitor_done`)
1815        // after all fire_hook() calls complete. This replaces the old
1816        // yield_now() approach which had a race window.
1817        let drain_timeout = time::sleep(MONITOR_DRAIN_WAIT);
1818        tokio::pin!(drain_timeout);
1819        loop {
1820            if self.active_monitors.load(atomic::Ordering::Acquire) == 0 {
1821                break;
1822            }
1823            tokio::select! {
1824                _ = self.monitor_done.notified() => {}
1825                _ = &mut drain_timeout => {
1826                    warn!("timed out waiting for monitoring tasks to register hooks, proceeding with shutdown");
1827                    break;
1828                }
1829            }
1830        }
1831        // The hooks run at the same time, so they are given one deadline
1832        // together: `supervisor stop` allows for this wait, and must not be
1833        // outlasted by it.
1834        let handles: Vec<JoinHandle<()>> = std::mem::take(&mut *self.hook_tasks.lock().await);
1835        let hook_deadline = time::Instant::now() + HOOK_DRAIN_WAIT;
1836        for handle in handles {
1837            match time::timeout_at(hook_deadline, handle).await {
1838                Ok(_) => {} // Hook completed (success or error, doesn't matter)
1839                Err(_) => {
1840                    warn!(
1841                        "hook task did not complete within {HOOK_DRAIN_WAIT:?} during shutdown, skipping"
1842                    );
1843                }
1844            }
1845        }
1846
1847        // Unix: remove the socket directory if it is empty. The IPC server
1848        // already removed our socket; anything left belongs to a supervisor
1849        // that replaced this one (e.g. `supervisor run --force`) while we
1850        // were stopping daemons, and must not be deleted.
1851        // Windows: named pipes have no filesystem component.
1852        #[cfg(unix)]
1853        let _ = fs::remove_dir(&*env::IPC_SOCK_DIR);
1854    }
1855
1856    pub(crate) async fn add_notification(&self, level: log::LevelFilter, message: String) {
1857        self.pending_notifications
1858            .lock()
1859            .await
1860            .push((level, message));
1861    }
1862}
1863
1864/// Fix ownership on the state directory so non-root users can access files
1865/// created by a `sudo`-started supervisor.
1866///
1867/// When `[settings.supervisor] user`, a recorded invoking user (see
1868/// [`env::InvokingUser`]), or `SUDO_UID`/`SUDO_GID` are set, we
1869/// `chown` the state directory and safe subdirectories back to that non-root
1870/// runtime user. This is strictly better than `chmod 0o666` because it does not
1871/// widen the permission bits — the files stay owner-only (0o600/0o700) but the
1872/// *owner* is the user that daemon processes and CLI clients need to share.
1873///
1874/// **Security**: The `proxy/` subtree is intentionally skipped. It contains
1875/// `ca-key.pem` which must remain `0o600` and owned by the process that
1876/// generated it. Changing its ownership or permissions would expose the CA
1877/// private key to other local users.
1878///
1879/// If none of these are available (e.g. a direct root login, or a boot service
1880/// installed from a root shell), we fall back to relaxing permissions on only
1881/// the `sock/` and `logs/` subdirectories (plus `state.toml`) so CLI clients
1882/// can still function.
1883#[cfg(unix)]
1884fn fix_state_dir_permissions() {
1885    let state_dir = &*env::PITCHFORK_STATE_DIR;
1886    if let Some((uid, gid)) = state_owner_ids() {
1887        if !state_dir.exists()
1888            && let Err(err) = fs::create_dir_all(state_dir)
1889        {
1890            warn!(
1891                "failed to create state directory for ownership fix at {}: {err}",
1892                state_dir.display()
1893            );
1894            return;
1895        }
1896
1897        // Best path: chown back to the runtime user. Permissions stay tight.
1898        chown_recursive(state_dir, uid, gid, true);
1899        debug!(
1900            "chowned state directory to uid={uid} gid={gid} at {}",
1901            state_dir.display()
1902        );
1903    } else {
1904        if !state_dir.exists() {
1905            return;
1906        }
1907
1908        // Fallback: relax permissions on safe subdirectories only.
1909        // proxy/ is never touched.
1910        chmod_safe_subtrees(state_dir);
1911        debug!(
1912            "relaxed permissions on safe subtrees at {}",
1913            state_dir.display()
1914        );
1915    }
1916}
1917
1918#[cfg(unix)]
1919pub(crate) fn state_owner_ids() -> Option<(u32, u32)> {
1920    if !nix::unistd::Uid::effective().is_root() {
1921        return None;
1922    }
1923
1924    let s = settings();
1925    let user = s.supervisor.user.trim();
1926    if !user.is_empty() {
1927        return resolve_supervisor_user_ids(user).or_else(|| {
1928            warn!(
1929                "failed to resolve supervisor.user '{user}' for state ownership; falling back to the invoking user"
1930            );
1931            env::invoking_user_ids()
1932        });
1933    }
1934
1935    env::invoking_user_ids()
1936}
1937
1938#[cfg(unix)]
1939fn resolve_supervisor_user_ids(user: &str) -> Option<(u32, u32)> {
1940    let user_record = if user.chars().all(|c| c.is_ascii_digit()) {
1941        let uid = user.parse::<u32>().ok()?;
1942        nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
1943            .ok()
1944            .flatten()
1945    } else {
1946        nix::unistd::User::from_name(user).ok().flatten()
1947    }?;
1948
1949    Some((user_record.uid.as_raw(), user_record.gid.as_raw()))
1950}
1951
1952/// Recursively `chown` a directory tree. If `skip_proxy` is true, the `proxy/`
1953/// subdirectory is skipped entirely to protect the CA private key.
1954#[cfg(unix)]
1955fn chown_recursive(dir: &std::path::Path, uid: u32, gid: u32, skip_proxy: bool) {
1956    // chown the directory itself
1957    let _ = chown_path(dir, uid, gid);
1958
1959    let entries = match std::fs::read_dir(dir) {
1960        Ok(e) => e,
1961        Err(_) => return,
1962    };
1963    for entry in entries.flatten() {
1964        let path = entry.path();
1965        if path.is_dir() {
1966            // Skip proxy/ at the top level of the state directory
1967            if skip_proxy
1968                && let Some(name) = path.file_name().and_then(|n| n.to_str())
1969                && name == "proxy"
1970            {
1971                continue;
1972            }
1973            chown_recursive(&path, uid, gid, false);
1974        } else {
1975            let _ = chown_path(&path, uid, gid);
1976        }
1977    }
1978}
1979
1980/// `chown` a single path using libc. Returns Ok(()) on success.
1981#[cfg(unix)]
1982fn chown_path(path: &std::path::Path, uid: u32, gid: u32) -> std::io::Result<()> {
1983    use std::ffi::CString;
1984    use std::os::unix::ffi::OsStrExt;
1985    let c_path = CString::new(path.as_os_str().as_bytes())
1986        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
1987    let ret = unsafe { libc::chown(c_path.as_ptr(), uid, gid) };
1988    if ret == 0 {
1989        Ok(())
1990    } else {
1991        Err(std::io::Error::last_os_error())
1992    }
1993}
1994
1995/// Fallback: relax permissions on safe subdirectories only (sock/, logs/, and
1996/// state.toml). The proxy/ subtree is never touched.
1997#[cfg(unix)]
1998fn chmod_safe_subtrees(state_dir: &std::path::Path) {
1999    // The state directory itself needs to be traversable
2000    let _ = fs::set_permissions(state_dir, fs::Permissions::from_mode(0o755));
2001
2002    // state.toml — needs to be readable by CLI clients
2003    let state_file = state_dir.join("state.toml");
2004    if state_file.exists() {
2005        let _ = fs::set_permissions(&state_file, fs::Permissions::from_mode(0o644));
2006    }
2007
2008    // Safe subdirectories: sock/ and logs/
2009    for subdir_name in &["sock", "logs"] {
2010        let subdir = state_dir.join(subdir_name);
2011        if subdir.is_dir() {
2012            chmod_recursive(&subdir);
2013        }
2014    }
2015}
2016
2017/// On startup, reconcile daemon processes left behind by a previous supervisor
2018/// that was terminated unexpectedly (e.g. `kill -9`).
2019///
2020/// This iterates the state file for daemon entries with a recorded PID. If the
2021/// PID is still alive and its current identity matches the recorded start time
2022/// (or the recorded title for older state files), it is assumed to be an orphan
2023/// from the previous supervisor session and `supervisor.orphan_policy` decides
2024/// its fate: `adopt` (default) resumes supervision via a poll monitor and keeps
2025/// the daemon's state intact; `kill` terminates it and resets its state to
2026/// `Stopped` with no PID. If a matching live process cannot be terminated
2027/// securely, its running state is retained to prevent a duplicate instance
2028/// from being started.
2029///
2030/// Missing or mismatched identity data fails closed so a PID recycled by an
2031/// unrelated process is never adopted or killed. On Unix platforms without
2032/// durable process handles, orphan termination also fails closed because the
2033/// PID/PGID cannot be pinned between identity validation and signaling.
2034///
2035/// This is gated by the `supervisor.cleanup_orphans` setting (default: true).
2036///
2037/// `unclean` is whether the previous supervisor exited uncleanly (see
2038/// [`supervisor_exited_uncleanly`]). It is read in `start()` before the
2039/// starting supervisor records itself in the state file — this function runs
2040/// in the background after that record exists, so reading it here would
2041/// always report unclean.
2042async fn cleanup_orphaned_daemons(supervisor: &Supervisor, unclean: bool) {
2043    if !settings().supervisor.cleanup_orphans {
2044        return;
2045    }
2046
2047    let candidates: Vec<_> = {
2048        let state = supervisor.state_file.lock().await;
2049        state
2050            .daemons
2051            .values()
2052            .filter(|d| d.id != DaemonId::pitchfork() && d.pid.is_some())
2053            .cloned()
2054            .collect()
2055    };
2056
2057    if candidates.is_empty() {
2058        return;
2059    }
2060
2061    info!(
2062        "checking {} daemon(s) for orphaned processes",
2063        candidates.len()
2064    );
2065
2066    let policy = orphan_policy();
2067    let boot_time = PROCS.boot_time();
2068
2069    // Reconcile orphans in parallel — a kill waits for the daemon's whole
2070    // process group to exit, bounded by that daemon's stop budget, so
2071    // sequential processing would make total cleanup time the sum of the
2072    // budgets.
2073    let tasks: Vec<_> = candidates
2074        .into_iter()
2075        .map(|daemon| {
2076            let policy = policy.clone();
2077            tokio::spawn(cleanup_orphaned_daemon(daemon, policy, boot_time, unclean))
2078        })
2079        .collect();
2080    for task in tasks {
2081        let _ = task.await;
2082    }
2083}
2084
2085/// Reconcile a single orphan candidate: adopt it, kill it, or reset its state,
2086/// per the policy and identity checks described on [`cleanup_orphaned_daemons`].
2087///
2088/// Holds the daemon's stop lock so a concurrent Run/Stop request for the same
2089/// daemon (cleanup runs in the background) serializes with the orphan kill,
2090/// and re-checks the recorded PID under the lock: if it changed, another path
2091/// already replaced or cleaned up this record and the snapshot is stale.
2092async fn cleanup_orphaned_daemon(
2093    daemon: crate::daemon::Daemon,
2094    policy: String,
2095    boot_time: u64,
2096    unclean: bool,
2097) {
2098    let supervisor: &Supervisor = &SUPERVISOR;
2099    let Some(pid) = daemon.pid else { return };
2100
2101    let lock = supervisor.stop_lock(&daemon.id).await;
2102    let _guard = lock.lock().await;
2103    let current_pid = {
2104        let state = supervisor.state_file.lock().await;
2105        state.daemons.get(&daemon.id).and_then(|d| d.pid)
2106    };
2107    if current_pid != Some(pid) {
2108        debug!(
2109            "orphan cleanup: daemon {} pid changed (recorded {pid}, now {current_pid:?}), skipping",
2110            daemon.id
2111        );
2112        return;
2113    }
2114
2115    // Refresh the candidate immediately before checking it: waiting for the
2116    // stop lock can await another path's stop timeout, during which this PID
2117    // may exit and be recycled.
2118    PROCS.refresh_pids(&[pid]);
2119
2120    if !PROCS.is_running(pid) {
2121        // PID already dead — the daemon exited while unsupervised, so
2122        // record a terminal status that reflects whether it died under a
2123        // crashed supervisor (retryable) or with the machine.
2124        let status = unobserved_exit_status(
2125            &daemon.status,
2126            daemon.boot_time,
2127            boot_time,
2128            unclean,
2129            daemon.oneshot,
2130        );
2131        reset_daemon_state(supervisor, &daemon.id, status, ExitObservation::Unobserved).await;
2132        return;
2133    }
2134
2135    // Safety check: verify the live process really is the daemon we
2136    // recorded, not an unrelated process that received a recycled PID.
2137    // The kernel start time is a stable identity for the lifetime of a
2138    // process, and is the only thing accepted as one.
2139    let current_start_time = PROCS.start_time(pid);
2140    let matches = process_identity_matches(daemon.start_time, current_start_time);
2141
2142    if !matches {
2143        // Either side missing means the identity cannot be checked at all,
2144        // which is different from checking it and finding a stranger: retain
2145        // the running state rather than resetting a record whose process may
2146        // well still be the daemon.
2147        if daemon.start_time.is_none() || current_start_time.is_none() {
2148            warn!(
2149                "could not verify the identity of live pid {pid} recorded for daemon {}; retaining running state",
2150                daemon.id,
2151            );
2152            return;
2153        }
2154        warn!(
2155            "pid {pid} recorded for daemon {} belongs to a different process now (PID recycled); resetting state without killing",
2156            daemon.id,
2157        );
2158        // The daemon died at some unknown point and the OS handed its PID
2159        // to something else — same unobserved exit as a dead PID.
2160        let status = unobserved_exit_status(
2161            &daemon.status,
2162            daemon.boot_time,
2163            boot_time,
2164            unclean,
2165            daemon.oneshot,
2166        );
2167        reset_daemon_state(supervisor, &daemon.id, status, ExitObservation::Unobserved).await;
2168        return;
2169    }
2170
2171    // Both policies need a verified start time: killing revalidates it
2172    // while pinned to the process, and adoption anchors its poll monitor
2173    // to it so a later PID recycle is never mistaken for the daemon.
2174    let Some(expected_start_time) = current_start_time else {
2175        warn!(
2176            "could not read start time for live pid {pid} recorded for daemon {}; retaining running state",
2177            daemon.id,
2178        );
2179        return;
2180    };
2181
2182    // Identity verified — the process really is our orphaned daemon.
2183    // The policy decides whether supervision resumes or the slate is
2184    // wiped clean.
2185    if policy == "adopt" {
2186        supervisor
2187            .adopt_daemon(&daemon, pid, expected_start_time)
2188            .await;
2189        return;
2190    }
2191
2192    info!("terminating orphaned daemon {} (pid {pid})", daemon.id);
2193
2194    let stop_cfg = daemon.stop_signal.unwrap_or_default();
2195    let termination_result = PROCS
2196        .kill_process_group_if_start_time_matches_async(
2197            pid,
2198            Some(expected_start_time),
2199            stop_cfg.signal.into(),
2200            stop_cfg.timeout,
2201        )
2202        .await;
2203
2204    match termination_result {
2205        Ok(true) => {}
2206        Ok(false) => {
2207            warn!(
2208                "could not securely terminate orphaned daemon {} (pid {pid}); retaining running state",
2209                daemon.id
2210            );
2211            return;
2212        }
2213        Err(err) => {
2214            warn!(
2215                "failed to terminate orphaned daemon {} (pid {pid}): {err}; retaining running state",
2216                daemon.id
2217            );
2218            return;
2219        }
2220    }
2221
2222    // We terminated the orphan ourselves, so this is an observed,
2223    // intentional stop rather than an unobserved exit.
2224    reset_daemon_state(
2225        supervisor,
2226        &daemon.id,
2227        DaemonStatus::Stopped,
2228        ExitObservation::Terminated,
2229    )
2230    .await;
2231}
2232
2233/// Effective `supervisor.orphan_policy`, warning on an unrecognized value
2234/// (which falls back to the default of adopting).
2235pub(crate) fn orphan_policy() -> String {
2236    let policy = settings().supervisor.orphan_policy.clone();
2237    match policy.as_str() {
2238        "adopt" | "kill" => policy,
2239        other => {
2240            warn!("unknown supervisor.orphan_policy '{other}', defaulting to 'adopt'");
2241            "adopt".to_string()
2242        }
2243    }
2244}
2245
2246/// Verify that live process identity matches the persisted daemon identity.
2247///
2248/// Both start times are required. A process name was once accepted in place of
2249/// a recorded start time, for state written before start times existed, but a
2250/// name is not an identity: a recycled PID belonging to another copy of the same
2251/// program matches it, and adopting or killing on that basis acts on the wrong
2252/// process. Missing identity, on either side, means unverifiable — and
2253/// unverifiable must never authorize acting on a process.
2254fn process_identity_matches(
2255    recorded_start_time: Option<u64>,
2256    current_start_time: Option<u64>,
2257) -> bool {
2258    match (recorded_start_time, current_start_time) {
2259        (Some(recorded), Some(current)) => recorded == current,
2260        _ => false,
2261    }
2262}
2263
2264/// Whether a PID read from persisted state may be signalled.
2265///
2266/// Stopping a daemon signals its whole process *group*, so acting on a PID that
2267/// has been recycled since it was recorded takes down an unrelated process tree.
2268/// Records are refused only when their identity is positively contradicted: if
2269/// either start time is unknown the PID stays as signallable as it was before
2270/// identities were recorded, so a daemon whose record predates the field can
2271/// still be stopped rather than becoming permanently unstoppable.
2272///
2273/// This is deliberately weaker than [`process_identity_matches`], which decides
2274/// whether to adopt or kill a process nobody asked about. Here the user has
2275/// named the daemon and asked for it to stop; the check exists to catch the
2276/// case where the answer is provably the wrong process.
2277pub(crate) fn signalling_pid_is_authorized(
2278    recorded_start_time: Option<u64>,
2279    current_start_time: Option<u64>,
2280) -> bool {
2281    !matches!(
2282        (recorded_start_time, current_start_time),
2283        (Some(recorded), Some(current)) if recorded != current
2284    )
2285}
2286
2287/// How a daemon's run ended, which decides what happens to the recorded
2288/// `last_exit_success` that cron `retrigger = "success" | "fail"` reads.
2289#[derive(Clone, Copy, PartialEq, Eq)]
2290pub(crate) enum ExitObservation {
2291    /// Nobody saw how the run ended, because the monitor that would have
2292    /// observed it died with a previous supervisor. The recorded outcome is
2293    /// cleared to `None`.
2294    ///
2295    /// Every option here is imperfect, so this picks the one that asserts
2296    /// nothing false. `Some(false)` would fabricate a failure, silently
2297    /// breaking a `retrigger = "success"` chain whose run may well have
2298    /// succeeded; `Some(true)` fabricates the opposite; keeping the previous
2299    /// value attributes an earlier run's outcome to this one. `None` says
2300    /// "unknown", reusing the reading the cron watcher already applies to a
2301    /// daemon that has never run.
2302    ///
2303    /// The tradeoff is that `None` satisfies both `retrigger = "success"`
2304    /// (`unwrap_or(true)`) and `retrigger = "fail"` (`!unwrap_or(false)`), so
2305    /// such a daemon fires once at its next scheduled time regardless of which
2306    /// it configured. That is schedule-gated rather than a loop, and it biases
2307    /// toward running the daemon over leaving it permanently untriggered.
2308    /// Distinguishing "unknown" from "never ran" would require a third cron
2309    /// state and is deliberately left out of scope here.
2310    Unobserved,
2311    /// We terminated the process ourselves, so the outcome is not a mystery:
2312    /// it stopped because we asked it to. Recorded as a success, matching the
2313    /// convention `Supervisor::stop` already uses for a deliberate stop.
2314    Terminated,
2315}
2316
2317impl ExitObservation {
2318    /// The `last_exit_success` value this observation implies.
2319    pub(crate) fn last_exit_success(self) -> Option<bool> {
2320        match self {
2321            ExitObservation::Unobserved => None,
2322            ExitObservation::Terminated => Some(true),
2323        }
2324    }
2325}
2326
2327/// Clear a daemon's runtime state (pid, process identity, active port) after
2328/// its process is gone or is no longer ours to manage.
2329///
2330/// Config fields are preserved by cloning the existing record, so a reset can
2331/// never drop a daemon's command, retry policy, or schedule.
2332async fn reset_daemon_state(
2333    supervisor: &Supervisor,
2334    id: &DaemonId,
2335    status: DaemonStatus,
2336    observation: ExitObservation,
2337) {
2338    let mut state_file = supervisor.state_file.lock().await;
2339    let Some(existing) = state_file.daemons.get(id) else {
2340        return;
2341    };
2342    let mut daemon = existing.clone();
2343    daemon.pid = None;
2344    daemon.title = None;
2345    daemon.start_time = None;
2346    daemon.boot_time = None;
2347    daemon.status = status;
2348    daemon.last_exit_success = observation.last_exit_success();
2349    daemon.active_port = None;
2350    state_file.clear_active_port(id);
2351    state_file.insert_daemon(id, daemon);
2352}
2353
2354/// Boot times this far apart are treated as different boots.
2355///
2356/// Sized to the only platform that reports a jittery value: Windows derives
2357/// boot time as `now - GetTickCount64()`, sampling two clocks independently,
2358/// so consecutive calls within one boot can differ by about a second. Linux
2359/// (`/proc/stat` btime) and macOS (`kern.boottime`) report stable values.
2360///
2361/// Deliberately kept this tight so a genuine reboot can never fall inside it:
2362/// a prior session would have to boot, start the supervisor, spawn a daemon,
2363/// have that daemon die, and complete a reboot inside two seconds, which no
2364/// real boot cycle reaches. A larger window would misread a short-lived
2365/// previous boot (e.g. a device in a reboot loop) as the current one and
2366/// resurrect daemons a reboot should have left stopped.
2367pub(crate) const BOOT_TIME_TOLERANCE_SECS: u64 = 2;
2368
2369/// Terminal status for a daemon whose process is gone and whose exit was
2370/// never observed, because the monitor that would have seen it died with a
2371/// previous supervisor.
2372///
2373/// A daemon recorded `Running` was expected to still be alive, so it died
2374/// under the crashed supervisor: `Errored(-1)` ("unknown exit code") makes it
2375/// eligible for its configured retries. Two cases stay `Stopped` instead:
2376///
2377/// - records from an earlier boot, whose processes died with the machine —
2378///   auto-restarting those is what `boot_start` is for, and reviving every
2379///   retry-configured daemon after a reboot would be a surprise
2380/// - any other status (in practice `Stopping`), i.e. an intentional stop that
2381///   completed while the supervisor was gone
2382pub(crate) fn unobserved_exit_status(
2383    status: &DaemonStatus,
2384    recorded_boot_time: Option<u64>,
2385    current_boot_time: u64,
2386    supervisor_exited_uncleanly: bool,
2387    oneshot: bool,
2388) -> DaemonStatus {
2389    let same_boot = recorded_boot_time
2390        .is_some_and(|recorded| recorded.abs_diff(current_boot_time) <= BOOT_TIME_TOLERANCE_SECS);
2391    // A task gets `stopped` rather than `errored` for the same reason the
2392    // adopted path does: `errored` is what `check_retry` looks for, and
2393    // nobody saw how this run ended, so retrying it would re-run a migration
2394    // or a seed that may well have succeeded. Leave re-running to an explicit
2395    // start.
2396    if status.is_running() && same_boot && supervisor_exited_uncleanly && !oneshot {
2397        DaemonStatus::Errored(-1)
2398    } else {
2399        DaemonStatus::Stopped
2400    }
2401}
2402
2403/// Whether the supervisor that owned this state file failed to shut down
2404/// cleanly, meaning any daemon it left behind stopped for reasons nobody
2405/// recorded.
2406///
2407/// A clean shutdown removes the supervisor's own entry: `close()` does it on
2408/// Unix, where the stop signal is delivered and handled, and the
2409/// `supervisor stop` command does it on Windows, which has no POSIX signals
2410/// and force-terminates the process instead. A crash, an external `kill -9`,
2411/// or a `--force` replacement all leave the entry behind.
2412///
2413/// This must be read before the starting supervisor records itself, which is
2414/// why `cleanup_orphaned_daemons` runs first in `start()`.
2415async fn supervisor_exited_uncleanly(supervisor: &Supervisor) -> bool {
2416    supervisor
2417        .state_file
2418        .lock()
2419        .await
2420        .daemons
2421        .contains_key(&DaemonId::pitchfork())
2422}
2423
2424/// Recursively chmod: directories → 0o755, files → 0o644.
2425#[cfg(unix)]
2426fn chmod_recursive(dir: &std::path::Path) {
2427    let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o755));
2428    let entries = match fs::read_dir(dir) {
2429        Ok(e) => e,
2430        Err(_) => return,
2431    };
2432    for entry in entries.flatten() {
2433        let path = entry.path();
2434        if path.is_dir() {
2435            chmod_recursive(&path);
2436        } else {
2437            let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o644));
2438        }
2439    }
2440}
2441
2442#[cfg(test)]
2443mod tests {
2444    use super::{
2445        BOOT_TIME_TOLERANCE_SECS, legacy_supervisor_title_matches, process_identity_matches,
2446        should_remove_liveness_session, signalling_pid_is_authorized, supervisor_identity_matches,
2447        unobserved_exit_status,
2448    };
2449    use crate::daemon_status::DaemonStatus;
2450    use crate::state_file::ProjectSession;
2451
2452    const BOOT: u64 = 1_700_000_000;
2453
2454    #[test]
2455    fn unobserved_running_death_in_current_boot_is_retryable() {
2456        // Died under a crashed supervisor during this boot: Errored(-1) makes
2457        // the daemon eligible for its configured retries.
2458        assert!(matches!(
2459            unobserved_exit_status(&DaemonStatus::Running, Some(BOOT), BOOT, true, false),
2460            DaemonStatus::Errored(-1)
2461        ));
2462    }
2463
2464    #[test]
2465    fn unobserved_task_death_is_stopped_not_retried() {
2466        // Nobody saw how the run ended, so `errored` would hand a migration or
2467        // a seed to check_retry on a guess. Matches what the adopted path
2468        // records, and what the guide promises.
2469        assert!(matches!(
2470            unobserved_exit_status(&DaemonStatus::Running, Some(BOOT), BOOT, true, true),
2471            DaemonStatus::Stopped
2472        ));
2473    }
2474
2475    #[test]
2476    fn unobserved_running_death_from_previous_boot_is_stopped() {
2477        // The process died with the machine; reviving every retry-configured
2478        // daemon after a reboot is what boot_start is for.
2479        assert!(matches!(
2480            unobserved_exit_status(
2481                &DaemonStatus::Running,
2482                Some(BOOT - 86_400),
2483                BOOT,
2484                true,
2485                false
2486            ),
2487            DaemonStatus::Stopped
2488        ));
2489    }
2490
2491    #[test]
2492    fn unobserved_exit_tolerates_boot_time_jitter() {
2493        // Windows recomputes boot time as now - GetTickCount64(), which can
2494        // drift about a second between samples within one boot.
2495        let within = BOOT + BOOT_TIME_TOLERANCE_SECS;
2496        assert!(matches!(
2497            unobserved_exit_status(&DaemonStatus::Running, Some(within), BOOT, true, false),
2498            DaemonStatus::Errored(-1)
2499        ));
2500        let beyond = BOOT + BOOT_TIME_TOLERANCE_SECS + 1;
2501        assert!(matches!(
2502            unobserved_exit_status(&DaemonStatus::Running, Some(beyond), BOOT, true, false),
2503            DaemonStatus::Stopped
2504        ));
2505    }
2506
2507    #[test]
2508    fn unobserved_exit_after_clean_shutdown_is_stopped() {
2509        // A deliberate `supervisor stop` can leave running records behind on
2510        // platforms where the supervisor cannot handle the stop signal. Those
2511        // daemons were stopped on purpose, so they must not be reported as
2512        // failures or resurrected by the retry checker.
2513        assert!(matches!(
2514            unobserved_exit_status(&DaemonStatus::Running, Some(BOOT), BOOT, false, false),
2515            DaemonStatus::Stopped
2516        ));
2517    }
2518
2519    #[test]
2520    fn unobserved_exit_treats_short_previous_boot_as_previous() {
2521        // A device in a reboot loop can produce consecutive boots seconds
2522        // apart. The jitter window must stay far below that so those records
2523        // are still recognised as belonging to an earlier boot.
2524        for gap in [5, 30, 59, 60] {
2525            assert!(
2526                matches!(
2527                    unobserved_exit_status(
2528                        &DaemonStatus::Running,
2529                        Some(BOOT - gap),
2530                        BOOT,
2531                        true,
2532                        false
2533                    ),
2534                    DaemonStatus::Stopped
2535                ),
2536                "boot {gap}s earlier should be treated as a previous boot"
2537            );
2538        }
2539    }
2540
2541    #[test]
2542    fn unobserved_exit_without_recorded_boot_time_is_stopped() {
2543        // Legacy state files predating the field fail closed to today's
2544        // behavior rather than triggering surprise retries.
2545        assert!(matches!(
2546            unobserved_exit_status(&DaemonStatus::Running, None, BOOT, true, false),
2547            DaemonStatus::Stopped
2548        ));
2549    }
2550
2551    #[test]
2552    fn supervisor_identity_matches_same_generation() {
2553        assert!(supervisor_identity_matches(
2554            Some(100),
2555            Some(100),
2556            Some(BOOT),
2557            BOOT
2558        ));
2559    }
2560
2561    #[test]
2562    fn supervisor_identity_survives_clock_steps_when_tokens_match() {
2563        // An NTP step or sleep/resume moves the realtime-derived boot time by
2564        // far more than the tolerance while the supervisor keeps running.
2565        // Matching start tokens prove it is the same process; declaring it
2566        // stale here would start a second supervisor.
2567        assert!(supervisor_identity_matches(
2568            Some(100),
2569            Some(100),
2570            Some(BOOT),
2571            BOOT + 3600
2572        ));
2573        assert!(supervisor_identity_matches(
2574            Some(100),
2575            Some(100),
2576            Some(BOOT + 3600),
2577            BOOT
2578        ));
2579    }
2580
2581    #[test]
2582    fn supervisor_identity_rejects_recycled_pid() {
2583        // The supervisor died and something else got its PID, within this
2584        // boot or across a reboot: the token differs either way.
2585        assert!(!supervisor_identity_matches(
2586            Some(100),
2587            Some(200),
2588            Some(BOOT),
2589            BOOT
2590        ));
2591        assert!(!supervisor_identity_matches(
2592            Some(100),
2593            Some(200),
2594            Some(BOOT),
2595            BOOT + 3600
2596        ));
2597    }
2598
2599    #[test]
2600    fn supervisor_identity_uses_boot_time_when_a_token_is_missing() {
2601        // Discussion #877: the record survived a reboot and an early system
2602        // daemon now owns the PID. With no live token to compare, the boot
2603        // time is what proves the record stale.
2604        assert!(!supervisor_identity_matches(
2605            Some(100),
2606            None,
2607            Some(BOOT),
2608            BOOT + 3600
2609        ));
2610        // Same boot (within Windows boot-time jitter) and no contradiction.
2611        assert!(supervisor_identity_matches(
2612            Some(100),
2613            None,
2614            Some(BOOT),
2615            BOOT + BOOT_TIME_TOLERANCE_SECS
2616        ));
2617    }
2618
2619    #[test]
2620    fn supervisor_identity_tolerates_legacy_records() {
2621        // A record written before either field existed is not contradicted by
2622        // anything here; `supervisor_record_is_live` applies the process-name
2623        // check to those instead.
2624        assert!(supervisor_identity_matches(None, Some(100), None, BOOT));
2625        // A record with only a boot time is still rejected across a reboot.
2626        assert!(!supervisor_identity_matches(
2627            None,
2628            Some(100),
2629            Some(BOOT),
2630            BOOT + 3600
2631        ));
2632        assert!(supervisor_identity_matches(
2633            None,
2634            Some(100),
2635            Some(BOOT),
2636            BOOT
2637        ));
2638    }
2639
2640    #[test]
2641    fn legacy_supervisor_title_requires_a_pitchfork_process() {
2642        assert!(legacy_supervisor_title_matches(Some("pitchfork")));
2643        assert!(legacy_supervisor_title_matches(Some("pitchfork.exe")));
2644        assert!(legacy_supervisor_title_matches(Some("Pitchfork")));
2645        // Discussion #877: an Apple LaunchAgent inherited the PID after a reboot.
2646        assert!(!legacy_supervisor_title_matches(Some(
2647            "AMPDeviceDiscoveryAgent"
2648        )));
2649        assert!(!legacy_supervisor_title_matches(Some("sleep")));
2650        assert!(!legacy_supervisor_title_matches(None));
2651    }
2652
2653    #[test]
2654    fn unobserved_exit_of_stopping_daemon_is_stopped() {
2655        // An intentional stop that completed while the supervisor was gone is
2656        // not a failure, even within the same boot.
2657        assert!(matches!(
2658            unobserved_exit_status(&DaemonStatus::Stopping, Some(BOOT), BOOT, true, false),
2659            DaemonStatus::Stopped
2660        ));
2661    }
2662
2663    #[test]
2664    fn orphan_identity_requires_both_start_times() {
2665        assert!(process_identity_matches(Some(123), Some(123)));
2666        assert!(!process_identity_matches(Some(123), Some(456)));
2667        // Unreadable current identity: unverifiable, so not a match.
2668        assert!(!process_identity_matches(Some(123), None));
2669    }
2670
2671    #[test]
2672    fn signalling_is_refused_only_for_a_contradicted_identity() {
2673        // Provably someone else's process group: refuse.
2674        assert!(!signalling_pid_is_authorized(Some(123), Some(456)));
2675        // Verified as the daemon's own.
2676        assert!(signalling_pid_is_authorized(Some(123), Some(123)));
2677        // Unknown on either side. Stopping stays possible, because the user has
2678        // named this daemon and a record that cannot be verified must not become
2679        // one that can never be stopped.
2680        assert!(signalling_pid_is_authorized(None, Some(123)));
2681        assert!(signalling_pid_is_authorized(Some(123), None));
2682        assert!(signalling_pid_is_authorized(None, None));
2683    }
2684
2685    #[test]
2686    fn orphan_identity_rejects_records_without_a_start_time() {
2687        // State written before start times were recorded. A process name used
2688        // to stand in here, but another copy of the same program on a recycled
2689        // PID matches a name, so such records are no longer verifiable and must
2690        // not authorize adopting or killing anything.
2691        assert!(!process_identity_matches(None, Some(123)));
2692        assert!(!process_identity_matches(None, None));
2693    }
2694
2695    #[test]
2696    fn should_not_remove_when_state_title_differs_from_snapshot() {
2697        // The session was re-entered after the snapshot was taken, producing a
2698        // new title in state. The snapshot title is stale; skip removal.
2699        let session = ProjectSession {
2700            liveness_title: Some("new_title".to_string()),
2701        };
2702        let recorded_title = Some("old_title".to_string());
2703
2704        assert!(!should_remove_liveness_session(
2705            &session,
2706            &recorded_title,
2707            Some("new_title"),
2708            true,
2709        ));
2710    }
2711
2712    #[test]
2713    fn should_remove_when_running_title_mismatches() {
2714        let session = ProjectSession {
2715            liveness_title: Some("recorded_title".to_string()),
2716        };
2717        let recorded_title = Some("recorded_title".to_string());
2718
2719        assert!(should_remove_liveness_session(
2720            &session,
2721            &recorded_title,
2722            Some("different_title"),
2723            true,
2724        ));
2725    }
2726
2727    #[test]
2728    fn should_remove_when_dead() {
2729        let session = ProjectSession {
2730            liveness_title: Some("recorded_title".to_string()),
2731        };
2732        let recorded_title = Some("recorded_title".to_string());
2733
2734        assert!(should_remove_liveness_session(
2735            &session,
2736            &recorded_title,
2737            Some("recorded_title"),
2738            false,
2739        ));
2740    }
2741
2742    #[test]
2743    fn should_not_remove_when_alive_and_title_matches() {
2744        let session = ProjectSession {
2745            liveness_title: Some("recorded_title".to_string()),
2746        };
2747        let recorded_title = Some("recorded_title".to_string());
2748
2749        assert!(!should_remove_liveness_session(
2750            &session,
2751            &recorded_title,
2752            Some("recorded_title"),
2753            true,
2754        ));
2755    }
2756
2757    fn budget_daemon(
2758        name: &str,
2759        pid: Option<u32>,
2760        timeout: Option<std::time::Duration>,
2761    ) -> crate::daemon::Daemon {
2762        crate::daemon::Daemon {
2763            id: crate::daemon_id::DaemonId::new("proj", name),
2764            pid,
2765            stop_signal: timeout.map(|timeout| crate::config_types::StopConfig {
2766                timeout: Some(timeout),
2767                ..crate::config_types::StopConfig::default()
2768            }),
2769            ..crate::daemon::Daemon::default()
2770        }
2771    }
2772
2773    #[test]
2774    fn stop_budget_covers_each_running_daemon_in_turn() {
2775        let base = std::time::Duration::from_secs(5);
2776        let sigkill = crate::procs::PROCESS_GROUP_SIGKILL_WAIT;
2777        let daemons = [
2778            budget_daemon("db", Some(1), Some(std::time::Duration::from_secs(4))),
2779            budget_daemon("app", Some(2), Some(std::time::Duration::from_secs(4))),
2780            // No timeout of its own: the supervisor's applies.
2781            budget_daemon("worker", Some(3), None),
2782            // Not running: nothing to stop.
2783            budget_daemon("idle", None, Some(std::time::Duration::from_secs(60))),
2784            crate::daemon::Daemon {
2785                id: crate::daemon_id::DaemonId::pitchfork(),
2786                pid: Some(4),
2787                ..crate::daemon::Daemon::default()
2788            },
2789        ];
2790        assert_eq!(
2791            super::daemons_stop_budget(&daemons, base),
2792            base + (std::time::Duration::from_secs(4) + sigkill) * 2 + (base + sigkill)
2793        );
2794    }
2795
2796    #[test]
2797    fn stop_budget_is_the_base_with_no_running_daemons() {
2798        let base = std::time::Duration::from_secs(5);
2799        assert_eq!(super::daemons_stop_budget(&[], base), base);
2800    }
2801}