Skip to main content

agentmux_launcher/supervisor/
unix.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::host_spawn::{spawn_host_unix, terminate_child_gracefully};
5use crate::logging::log;
6use crate::second_instance::bind_socket_with_recovery;
7use crate::show_fatal_dialog;
8use crate::supervisor::srv_exit::{respawn_srv, signal_name, srv_exit_action, Srv, SrvAction};
9use crate::supervisor::{HOST_RESTART_BUDGET, HOST_RESTART_WINDOW};
10use crate::{
11    data_dir, event_log, hash, host_pipe, ipc, mem_supervisor, other_instances, saga,
12    srv_spawner, startup_events, state, tray,
13};
14
15/// Await the next delivery of a Unix signal, or never resolve if the
16/// signal stream couldn't be installed. Lets `run_unix`'s `select!`
17/// treat an absent handler as "this branch is dormant" rather than
18/// special-casing `Option` at every poll.
19#[cfg(not(target_os = "windows"))]
20async fn next_signal(s: &mut Option<tokio::signal::unix::Signal>) {
21    match s {
22        Some(sig) => {
23            sig.recv().await;
24        }
25        None => std::future::pending::<()>().await,
26    }
27}
28
29/// Unix (macOS/Linux) main flow: resolve paths → bind launcher IPC
30/// socket (single-instance signal) → set up reducer / event log / saga
31/// coordinator / IPC server → spawn srv → spawn host with srv endpoints
32/// AND the launcher socket path in env → supervised wait → cleanup.
33///
34/// As of A1 (SPEC_LAUNCHER_LINUX_PACKAGED_AND_SPLASH_2026_06_05.md §4)
35/// the launcher's window/pool/instance reducer + durable saga
36/// coordinator are now live on Linux. The 17 host-side `report_*` IPC
37/// calls reach the reducer; the saga log persists at
38/// `<data-dir>/db/launcher-sagas.db`; second-instance launches are
39/// detected via socket-bind contention.
40///
41/// Differs from `run_windows` only where the OS forces it:
42///   * No Job Object — A0 (`PR_SET_PDEATHSIG` in `spawn_host_unix` and
43///     `srv_spawner`) gives the equivalent kernel-side reap when the
44///     launcher dies abnormally.
45///   * As of SPEC_LAUNCHER_TEARDOWN_BACKSTOP_2026_07_11 unix parity, host
46///     and srv are each spawned into their OWN process group
47///     (`.process_group(0)`) rather than inheriting the launcher's — the
48///     prerequisite for `kill_process_group_forcefully`'s
49///     `kill(-pgid, SIGKILL)` to be scoped to exactly what THIS launcher
50///     spawned, never the launcher's own group. Side effect (reagent P1,
51///     PR #2200): **a terminal Ctrl+C no longer reaches host/srv
52///     directly** — only the launcher (still in the terminal's foreground
53///     group) receives that SIGINT. Host/srv now die exclusively via the
54///     launcher's own explicit `terminate_child_gracefully` SIGTERM in the
55///     cleanup epilogue below (after the launcher's own SIGINT arm has
56///     already won the `select!` and broken the loop), never by an
57///     independent signal race inside the loop. See the (now narrower)
58///     group-shutdown guard comments on the `host_child.wait()` /
59///     `srv_child.wait()` arms for what scenario they still cover.
60///     `kill <launcher-pid>` is unaffected — the launcher's own
61///     SIGINT/SIGTERM handlers still catch it and drive the same cleanup.
62///   * Unix-domain-socket IPC (A1) instead of named pipes; protocol on
63///     the wire is identical (newline-delimited JSON Command/Event).
64///     The launcher-side server uses `tokio::net::UnixListener`; the
65///     host-side client uses `tokio::net::UnixStream`. See
66///     `ipc::server::run_ipc_server` (Unix arm) and
67///     `crates/cef/src/launcher_ipc/mod.rs::connect_to_launcher` (Unix arm).
68///   * srv-side IPC is still skipped on Unix (srv is launched with an
69///     empty `srv_pipe_path`); follow-up PR will bring srv's Unix
70///     socket online too.
71///   * Cleanup is SIGTERM-then-SIGKILL (we own the reap) rather than
72///     KILL_ON_JOB_CLOSE.
73///
74/// srv's stdin write-end is held for the launcher's lifetime — its EOF is
75/// srv's parent-death backstop if the launcher is SIGKILLed (the one case
76/// our signal handlers can't cover).
77#[cfg(not(target_os = "windows"))]
78pub(crate) async fn run_unix(
79    launcher_exe_dir: &std::path::Path,
80    real_exe: &std::path::Path,
81    args: &[String],
82    // macOS/Linux: pre-created sink whose rx was already handed to the
83    // splash thread in main() (both platforms paint the splash before
84    // calling into here). Other Unix / splash disabled: None; a fresh sink
85    // (rx dropped) is created below.
86    startup_sink_opt: Option<startup_events::StartupEventSink>,
87) {
88    use tokio::signal::unix::{signal, SignalKind};
89
90    let version = env!("CARGO_PKG_VERSION");
91
92    // Startup telemetry bus, resolved up front (rather than after the
93    // pre-supervisor work below, where it used to live) so that work itself
94    // can be wrapped in a "prep" stage — previously invisible in the splash
95    // panel on every platform (confirmed via grep: only "migrations"/
96    // "backend"/"host" were ever reported; the selftest fixture's "prep"/
97    // "Launcher setup" fixture data implied this stage already existed for
98    // real, but it never did). See
99    // docs/specs/PLAN_SPLASH_TELEMETRY_OPEN_ITEMS_2026_07_22.md item 4.
100    let startup_sink = startup_sink_opt.unwrap_or_else(|| {
101        let (s, rx) = startup_events::StartupEventSink::new();
102        drop(rx);
103        s
104    });
105    startup_sink.stage_begin("prep", "Launcher setup");
106    let prep_t = std::time::Instant::now();
107
108    // 1. Resolve + create data dirs (same authority as run_windows: srv +
109    //    host receive these via env so they can't drift).
110    let paths = match data_dir::resolve_paths(launcher_exe_dir, version) {
111        Ok(p) => p,
112        Err(e) => {
113            log(&format!("FATAL: path resolution failed: {}", e));
114            eprintln!("Failed to resolve AgentMux data directories: {}", e);
115            std::process::exit(1);
116        }
117    };
118    // What the user is told after a recovery (SPEC_RECOVERY_NOTICES_AND_TOASTS §4.4).
119    crate::incidents::init(&paths.data_dir);
120    log(&format!(
121        "paths resolved: data={} config={} user_home={} portable={}",
122        paths.data_dir.display(),
123        paths.config_dir.display(),
124        paths.user_home_dir.display(),
125        paths.portable_root.is_some(),
126    ));
127    if let Err(e) = data_dir::ensure_dirs(&paths) {
128        log(&format!("FATAL: failed to create data dirs: {}", e));
129        eprintln!("{}", e);
130        std::process::exit(1);
131    }
132
133    // -----------------------------------------------------------------
134    // A1.1 — IPC server setup on Linux (the wire is up). Mirrors the
135    // Windows path at the equivalent point in `run_windows`. Once this
136    // lands the host's 17 `report_*` IPC calls reach the (already
137    // platform-neutral) reducer, the window-pool / single-instance /
138    // instance-numbering logic activates, sagas get persisted to the
139    // launcher_saga.db SQLite log, and `--diag sagas` reads something
140    // useful.
141    //
142    // Spec: docs/specs/SPEC_LAUNCHER_LINUX_PACKAGED_AND_SPLASH_2026_06_05.md §4
143    // -----------------------------------------------------------------
144
145    // Compute the socket path from a data-dir hash + version, identical
146    // scoping rule to the Windows pipe namespace. `pipe_name` is now
147    // pure on both platforms — the side-effecting ensure step lives
148    // in `ensure_ipc_socket_dir` and is invoked separately below so
149    // that any future read-only inspector (e.g. a Linux `--diag`
150    // port) can call `pipe_name` without mutating the filesystem.
151    let pipe_version = option_env!("AGENTMUX_BUILD_LABEL")
152        .unwrap_or(env!("CARGO_PKG_VERSION"));
153    let dir_hash = hash::data_dir_hash16(&paths.data_dir, pipe_version);
154    let socket_path = ipc::pipe_name(&dir_hash);
155    log(&format!(
156        "launcher IPC socket = {} (data_dir={} pipe_version={})",
157        socket_path,
158        paths.data_dir.display(),
159        pipe_version
160    ));
161    // Ensure the socket dir exists with safe ownership/perms BEFORE
162    // any bind attempts. This may call std::process::exit(2) on a
163    // hostile-dir-on-disk scenario (cross-user squatting attack).
164    let _ = ipc::ensure_ipc_socket_dir();
165
166    // Single-instance handshake (A1.6). The bind is the authoritative
167    // signal: a second launcher pointing at the same data dir gets
168    // `EADDRINUSE`. The Windows path enjoys atomic `first_pipe_
169    // instance(true)`; Unix bind isn't atomic with respect to stale-
170    // file recovery, so we serialize that recovery via an `flock(2)`
171    // lockfile (codex P1 + reagent P1 on PR #1288).
172    //
173    // Concurrent-cleanup race the lockfile defends against:
174    //   1. Stale socket file remains from a crashed prior launcher.
175    //   2. Launcher A and B start concurrently. Both `bind` returns
176    //      EADDRINUSE because the file exists.
177    //   3. Without the lock: both A and B `connect` → ECONNREFUSED
178    //      (no listener on the stale file), both `unlink`, both
179    //      `bind` succeeds → two live launchers for one data dir,
180    //      and B's `unlink` may have removed A's freshly-bound
181    //      socket file before B bound its own.
182    //   4. With the lock: A holds the lock → does probe + unlink +
183    //      rebind atomically. B blocks on the lock. When A releases,
184    //      B's retry-bind sees A's running listener (file exists) and
185    //      B's `connect` succeeds → B exits cleanly as second
186    //      instance. No double-recovery.
187    //
188    // The lockfile lives next to the socket as `<socket>.lock`. It is
189    // intentionally NOT removed on clean shutdown — the inode is
190    // tiny, and leaving it lets the next launcher reuse it without a
191    // create-race. (Stale-lock-file scenarios are bounded: flock(2)
192    // is auto-released on process exit even for SIGKILL.)
193    let first_socket = bind_socket_with_recovery(&socket_path, &paths.data_dir, &dir_hash, &paths.common.channel);
194
195    // macOS: we are the first instance (second-instance launches exit inside
196    // bind_socket_with_recovery). Publish this instance's bound-socket identity
197    // to the splash's reopen handler so a Finder double-click / `open` (no -n)
198    // forwards open_new_window to exactly THIS (channel, version) instance —
199    // never a recomputed hash. SPEC_MACOS_REOPEN_NEW_WINDOW_2026_06_22.md.
200    #[cfg(target_os = "macos")]
201    crate::splash_mac::set_reopen_target(paths.data_dir.clone(), dir_hash.clone());
202
203    // Optional tray / menu-bar icon (issue #2977 Workstream 1). Same placement
204    // rationale as the Windows supervisor: this is the first point where we
205    // know we are THE instance (a second launch exits inside
206    // `bind_socket_with_recovery`), so a second icon cannot appear, and
207    // `data_dir`/`dir_hash` — all the actions need to reach the host — are
208    // resolved. Fire-and-forget: `None` when the tray is off,
209    // unsupported here, or failed to start; the action loop is a detached
210    // thread that only ever forwards over the same authenticated channel a
211    // second launch uses.
212    if let Some(tray_rx) = tray::start_if_enabled(paths.data_dir.clone(), dir_hash.clone()) {
213        tray::spawn_action_loop(tray_rx, paths.data_dir.clone(), dir_hash.clone());
214    }
215
216    // Task #35 (SPEC_WIN10_PAGEFILE_OOM_CRASH_2026_06_29.md P1) — read-only
217    // detection of other, OLDER AgentMux instances still running. Mirrors
218    // the Windows call site: we only reach this point once we've WON the
219    // single-instance socket bind above. Detection + logging ONLY — see
220    // `other_instances.rs` doc comment.
221    //
222    // reagent (PR #2117 round 1): synchronous I/O (fs::read_dir, socket
223    // connect probes), no `.await` in the body — spawn_blocking instead of
224    // plain tokio::spawn so it runs on the blocking-task pool and can never
225    // occupy/starve an async worker the IPC accept loop or host supervision
226    // needs, especially given channels/local-* dirs are documented to
227    // accumulate unpruned (more siblings to walk/probe over time).
228    {
229        let channels_root = paths.common.home_dir.join("channels");
230        let own_channel = paths.common.channel.clone();
231        let own_version = version.to_string();
232        tokio::task::spawn_blocking(move || {
233            other_instances::log_older_running_instances(&channels_root, &own_channel, &own_version);
234        });
235    }
236
237    // Broadcast bus for reducer-emitted events. Same capacity (1024)
238    // and rationale as the Windows path.
239    let (events_tx, _) =
240        tokio::sync::broadcast::channel::<agentmux_common::ipc::Event>(1024);
241
242    // Event log: in-memory ring + disk persistence at
243    // <data-dir>/launcher-events.log. Disk writer task spawned next.
244    let log_disk_path = paths.data_dir.join("launcher-events.log");
245    let event_log = std::sync::Arc::new(event_log::EventLog::new(Some(log_disk_path)));
246    let event_log_for_writer = std::sync::Arc::clone(&event_log);
247    let disk_writer_rx = events_tx.subscribe();
248    tokio::spawn(event_log::run_disk_writer(
249        event_log_for_writer,
250        disk_writer_rx,
251    ));
252
253    // Canonical state shared between IPC server + saga coordinator.
254    let state = std::sync::Arc::new(tokio::sync::Mutex::new(state::State::default()));
255
256    // Pillar 1 Step 6 — in-memory saga registry (see the Windows
257    // supervisor's comment for the full rationale). Best-effort cleanup of
258    // the legacy durable files.
259    let saga_log = std::sync::Arc::new(saga::LauncherSagaLog::new());
260    for legacy in [
261        paths.data_dir.join("db").join("launcher-sagas.db"),
262        paths.data_dir.join("launcher-sagas.db"),
263    ] {
264        for suffix in ["", "-wal", "-shm"] {
265            let p = std::path::PathBuf::from(format!("{}{}", legacy.display(), suffix));
266            if p.exists() && std::fs::remove_file(&p).is_ok() {
267                log(&format!("[saga] removed legacy durable saga log file {:?} (Step 6: registry is in-memory)", p));
268            }
269        }
270    }
271
272    // "prep" ends here — everything above (paths, IPC socket, single-instance
273    // handshake, other-instances check, event log, saga registry legacy
274    // cleanup) is done. What follows (saga coordinator + IPC server setup,
275    // srv spawn) has its own stages/overlap already.
276    startup_sink.stage_end(
277        "prep",
278        prep_t.elapsed().as_millis() as u64,
279        startup_events::StartupStatus::Ok,
280        None,
281    );
282
283    // Saga coordinator-setup/IPC-server-startup run concurrently with the
284    // srv boot below (tokio::join!) instead of sequentially before it.
285    // Neither branch depends on the other's output: this setup never reads
286    // srv_result, and srv never connects back to the launcher's IPC socket
287    // during its own startup. See SPEC_MACOS_LAUNCH_SPEED_AND_SPLASH_
288    // TELEMETRY_2026_07_02.md §A.4 item 5.
289    let launcher_setup = async {
290        // Host pipe wrapper for saga-issued Commands → host. The IPC
291        // server's per-connection handler installs the host's writer once
292        // the host registers (see ipc/server.rs handle_connection's
293        // ClientKind::Host branch).
294        let host_pipe = std::sync::Arc::new(host_pipe::HostPipe::new(
295            events_tx.clone(),
296            std::sync::Arc::clone(&state),
297        ));
298
299        // Saga coordinator. Same construction + error handling as the
300        // Windows path; the coordinator itself is platform-neutral.
301        let saga_coord_inner =
302            saga::SagaCoordinator::new(events_tx.clone(), std::sync::Arc::clone(&state))
303                .with_log(std::sync::Arc::clone(&saga_log))
304                .unwrap_or_else(|e| {
305                    log(&format!(
306                        "[main] FATAL: failed to seed saga_id allocator: {}",
307                        e
308                    ));
309                    std::process::exit(1);
310                })
311                .with_host_pipe(std::sync::Arc::clone(&host_pipe));
312        let saga_coord = std::sync::Arc::new(saga_coord_inner);
313        let saga_rx = events_tx.subscribe();
314        tokio::spawn(saga::run_coordinator(
315            std::sync::Arc::clone(&saga_coord),
316            saga_rx,
317        ));
318
319        let ipc_handle = ipc::run_ipc_server(
320            socket_path.clone(),
321            first_socket,
322            ipc::server::ServerCtx {
323                launcher_pid: std::process::id(),
324                launcher_version: env!("CARGO_PKG_VERSION").to_string(),
325                state: std::sync::Arc::clone(&state),
326                events_tx,
327                event_log,
328                host_pipe: std::sync::Arc::clone(&host_pipe),
329                startup_sink: Some(startup_sink.clone()),
330            },
331        );
332        log(&format!("IPC server started on {}", socket_path));
333
334        (saga_coord, ipc_handle, host_pipe)
335    };
336
337    // 2b. Spawn srv. The srv pipe path is the launcher-owned socket
338    //    path scope (srv will gain its own Unix-socket bind in a
339    //    follow-up; for now we still pass an empty string so srv's
340    //    Windows-only IPC code stays disabled).
341    let srv_pipe_path = String::new();
342    // This launcher owns the data dir now (it won the single-instance socket
343    // above), so an srv still holding the dir's lock was left behind by an
344    // earlier launcher; stop it rather than fail to start.
345    crate::stale_srv::reclaim_or_say_headless_running(&paths.data_dir);
346    let (setup_result, srv_spawn_result) = tokio::join!(
347        launcher_setup,
348        srv_spawner::spawn_srv(launcher_exe_dir, &paths, &srv_pipe_path, &startup_sink, None)
349    );
350    let (saga_coord, _ipc_handle, host_pipe) = setup_result;
351    crate::host_quit::install(std::sync::Arc::clone(&host_pipe), std::sync::Arc::clone(&state));
352    let (first_srv_result, first_srv_child) = match srv_spawn_result {
353        Ok(pair) => pair,
354        Err(e) => {
355            log(&format!("FATAL: srv spawn failed: {}", e));
356            eprintln!("Failed to start backend: {}", e);
357            // On Unix `show_fatal_dialog` is itself an eprintln (no native dialog yet — see
358            // main.rs), so today this repeats the line above. Kept so both supervisors call the same
359            // helper with the same words: when a native macOS/Linux dialog lands in
360            // show_fatal_dialog, this path gets it for free.
361            srv_spawner::show_spawn_failure(&e, &paths.data_dir);
362            // A new version from a package upgrade that can't start: offer the one before it.
363            offer_go_back(version, launcher_exe_dir, &paths.data_dir, "couldn't start its backend");
364            std::process::exit(1);
365        }
366    };
367
368    // OS notification presenter (Linux: freedesktop notifications over D-Bus).
369    // macOS has no toast backend yet (SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24
370    // §6.2) and gets the no-op presenter, but still needs the srv session: it
371    // carries `app:startatlogin` to the menu-bar item and the LaunchAgent
372    // (SPEC_START_WITH_OS_2026_09_25 §3.9).
373    crate::notify::start(&first_srv_result.ws_endpoint, &first_srv_result.auth_key, &first_srv_result.host_reg_secret, paths.data_dir.clone(), dir_hash.clone(), state.clone());
374
375    // CRITICAL (same rationale as run_windows): `Srv::new` takes srv's stdin out
376    // of the Child so tokio's wait() can't close it and trip srv's parent-watch
377    // EOF, and holds it until launcher exit. It also takes srv's pid now: tokio's
378    // `Child::id()` is `None` once the child has been waited on, which is exactly
379    // when the cleanup needs it (srv died first, or `quiesce_srv` reaped it).
380    let mut srv = Srv::new(first_srv_result, first_srv_child);
381
382    // 3. Spawn the host with srv endpoints in env.
383    // dir_hash was computed once above for socket_path; reuse it here
384    // instead of re-hashing the same paths.data_dir + version.
385    let mut host_env = paths.common.to_env_vars();
386    host_env.push(("AGENTMUX_IPC_HASH", std::ffi::OsString::from(&dir_hash)));
387    // A1.3 — IPC env handshake. Tell the host where to find the
388    // launcher socket. The env var name `AGENTMUX_LAUNCHER_PIPE` is
389    // reused from the Windows side even though the underlying resource
390    // is a Unix-domain socket — keeps the `report_*` functions in
391    // `crates/cef/src/launcher_ipc/reporters.rs` unchanged and avoids
392    // touching the host's connect-on-startup code in `crates/cef/src/lib.rs`.
393    host_env.push((
394        "AGENTMUX_LAUNCHER_PIPE",
395        std::ffi::OsString::from(&socket_path),
396    ));
397    // AGENTMUX_HOME = the host's runtime directory (siblings of the
398    // host binary — libcef.so, paks, locales, etc). Mirrors the
399    // Windows path so the host's asset-resolution code finds its
400    // co-located data without searching $PATH-like fallbacks.
401    if let Some(host_runtime) = real_exe.parent() {
402        host_env.push((
403            "AGENTMUX_HOME",
404            std::ffi::OsString::from(host_runtime),
405        ));
406    }
407    // "host" stage currently covers process-spawn latency only (begin →
408    // spawn_host_unix returning a live Child), not full first-paint — the
409    // signal for "host painted its first frame" (AGENTMUX_SPLASH_READY_FILE)
410    // is written by the host process itself and consumed exclusively by the
411    // splash's own poll loop (splash_mac.rs / splash_linux); having the
412    // supervisor also poll/remove that file risks a race with the splash's
413    // consumer. Extending this stage to span to first-paint is a follow-up
414    // once a race-safe signal exists (see SPEC_MACOS_LAUNCH_SPEED_AND_
415    // SPLASH_TELEMETRY_2026_07_02.md §B.7). Spawn latency is still a real,
416    // independently useful number.
417    startup_sink.stage_begin("host", "Host startup");
418    let host_spawn_t = std::time::Instant::now();
419    let mut host_child = match spawn_host_unix(real_exe, args, &srv.result, &host_env, false) {
420        Some(c) => {
421            startup_sink.stage_end(
422                "host",
423                host_spawn_t.elapsed().as_millis() as u64,
424                startup_events::StartupStatus::Ok,
425                None,
426            );
427            c
428        }
429        None => {
430            startup_sink.stage_end(
431                "host",
432                host_spawn_t.elapsed().as_millis() as u64,
433                startup_events::StartupStatus::Error,
434                Some("spawn failed".to_string()),
435            );
436            log("FATAL: could not start CEF host — terminating");
437            eprintln!("Failed to launch AgentMux.");
438            terminate_child_gracefully(&srv.child);
439            let _ = srv.child.start_kill();
440            std::process::exit(1);
441        }
442    };
443
444    // 4. Signal handlers for `kill <launcher-pid>` (a terminal Ctrl+C
445    //    already signals the whole foreground group; these cover the
446    //    launcher-only case and make Ctrl+C deterministic too).
447    let mut sigint = signal(SignalKind::interrupt()).ok();
448    let mut sigterm = signal(SignalKind::terminate()).ok();
449    if sigint.is_none() || sigterm.is_none() {
450        log("WARN: failed to install one or more signal handlers — \
451             relying on default termination + srv stdin-EOF backstop");
452    }
453
454    // 5. Supervised wait loop — host crash budget mirrors run_windows.
455    log("entering supervised host + srv wait (unix)");
456    let mut host_restarts: Vec<std::time::Instant> = Vec::new();
457    // Separate budget for system-OOM host exits (memory-aware relaunch); see
458    // mem_supervisor + SPEC_MEMORY_PRESSURE_SUPERVISION_2026_06_16.
459    let mut oom_restarts: Vec<std::time::Instant> = Vec::new();
460    let mut last_abnormal_exit: Option<(i32, std::time::Instant)> = None;
461    let mut host_degraded = false;
462    // srv's own restart budgets (SPEC_UNIX_SRV_RESTART_BUDGET_2026_10_24): crashes, and exits while
463    // the computer was out of memory, which are waited out like the window process's.
464    let mut srv_restarts: Vec<std::time::Instant> = Vec::new();
465    let mut srv_oom_restarts: Vec<std::time::Instant> = Vec::new();
466    // Set when the launcher itself ends the host because srv was started again: that host is wired to
467    // the dead srv's endpoints. The host arm reads it first, so the exit is never taken for a crash.
468    let mut srv_recycle_kill = false;
469    // When the host's process group gets SIGKILL if it hasn't stopped by then (set with the SIGTERM).
470    let mut host_kill_at: Option<tokio::time::Instant> = None;
471    // SPEC_LAUNCHER_TEARDOWN_BACKSTOP_2026_07_11 unix parity — same shape as
472    // `run_windows`'s Phase 1/Phase 2 pair. Low-rate UI-thread liveness
473    // prober (60s, first tick delayed a full interval so a booting host
474    // isn't logged as a false miss) plus a low-rate poll (5s) of the armed
475    // teardown state machine (armed by the IPC server's post-reducer event
476    // hook on PoolDrained/OrphanInstance — see `ipc/server.rs`, already
477    // platform-neutral and unconsumed on unix until this — disarmed on
478    // WindowOpened and on every host exit below).
479    let mut ui_probe_interval = tokio::time::interval_at(
480        tokio::time::Instant::now() + std::time::Duration::from_secs(60),
481        std::time::Duration::from_secs(60),
482    );
483    ui_probe_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
484    let mut ui_probe_nonce: u64 = 0;
485    let mut teardown_check_interval =
486        tokio::time::interval(std::time::Duration::from_secs(5));
487    teardown_check_interval
488        .set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
489    // Same distinct exit code as Windows so wedged-host teardown is
490    // unambiguous in log/exit-code triage across platforms.
491    const TEARDOWN_BACKSTOP_EXIT_CODE: i32 = 86;
492    // "Upgrade & restart" (upgrade_restart.rs), as on Windows: srv's requests,
493    // the user's answer in the native dialog, and what to start once quit.
494    let mut upgrade_requests = crate::upgrade_restart::requests();
495    let (upgrade_yes_tx, mut upgrade_yes) = tokio::sync::mpsc::unbounded_channel::<crate::upgrade_restart::Staged>();
496    let mut relaunch: Option<(crate::upgrade_restart::Staged, std::time::Instant)> = None;
497    // Set where the launcher gives up on this version for good (crashes past the budget, srv
498    // that can't be started again): a package upgrade then offers the version before it.
499    let mut gave_up: Option<&'static str> = None;
500    let exit_code = loop {
501        tokio::select! {
502            Some(req) = upgrade_requests.recv() => {
503                match crate::upgrade_restart::staged(&req, launcher_exe_dir, &paths.data_dir, &paths.common.instance_dir, version) {
504                    Ok(staged) => {
505                        log(&format!("upgrade: srv asks to restart into {staged}; {}", if req.confirmed { "already confirmed" } else { "asking the user" }));
506                        let tx = upgrade_yes_tx.clone();
507                        let stopping = crate::upgrade_restart::stopping_note(&paths.data_dir);
508                        crate::upgrade_restart::ask_then(req.version, staged, stopping, paths.data_dir.clone(), None, req.confirmed, move |s| {
509                            let _ = tx.send(s);
510                        });
511                    }
512                    Err(e) => log(&format!("upgrade: refused srv's request: {e}")),
513                }
514            }
515            Some(staged) = upgrade_yes.recv() => {
516                log(&format!("upgrade: going ahead (the restart is confirmed); quitting to restart into {staged}"));
517                relaunch = Some((staged, std::time::Instant::now()));
518                let (data_dir, hash) = (paths.data_dir.clone(), dir_hash.clone());
519                tokio::task::spawn_blocking(move || crate::host_quit::quit_host(&data_dir, &hash));
520            }
521            _ = async {
522                match host_kill_at {
523                    Some(at) => tokio::time::sleep_until(at).await,
524                    None => std::future::pending::<()>().await,
525                }
526            } => {
527                host_kill_at = None;
528                log("host did not stop for the srv restart in time — killing its process group");
529                crate::host_spawn::kill_process_group_forcefully(&host_child);
530            }
531            _ = teardown_check_interval.tick() => {
532                let misses = crate::ui_liveness::consecutive_misses();
533                if crate::teardown_backstop::should_teardown(misses) {
534                    log(&format!(
535                        "[teardown-backstop] host wedged with zero user windows — terminating process \
536                         groups (armed > {}s grace, {} consecutive unanswered UI-thread probes)",
537                        crate::teardown_backstop::TEARDOWN_GRACE.as_secs(),
538                        misses,
539                    ));
540                    // I2/I3 hold by construction: each process group (host,
541                    // srv) was created explicitly at spawn time via
542                    // `.process_group(0)` — the blast radius is exactly the
543                    // processes THIS launcher spawned and their descendants,
544                    // never the launcher's own group. Mirrors the Windows J0
545                    // TerminateJobObject backstop; the one deliberate
546                    // exception to "never kill what a saga can reconcile" —
547                    // zero user windows remain and the UI thread is provably
548                    // dead, so there is nothing to reconcile.
549                    //
550                    // The host's group: SIGTERM first, brief grace, then the
551                    // hard SIGKILL. srv is NOT presumed wedged (only the host
552                    // lost track of its windows), so it is stopped by the
553                    // cleanup below like on any quit: `quiesce_srv` lets it
554                    // close every agent gracefully, and only then kills its
555                    // group if it had to be forced.
556                    crate::host_spawn::kill_process_group_gracefully(&host_child);
557                    tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
558                    crate::host_spawn::kill_process_group_forcefully(&host_child);
559                    break TEARDOWN_BACKSTOP_EXIT_CODE;
560                }
561            }
562            _ = ui_probe_interval.tick() => {
563                ui_probe_nonce += 1;
564                if let Some((missed, sent_at)) = crate::ui_liveness::record_probe_sent(ui_probe_nonce) {
565                    log(&format!(
566                        "[ui-liveness] probe nonce={} unanswered after {}s — UI thread did not pump in that window",
567                        missed,
568                        sent_at.elapsed().as_secs()
569                    ));
570                }
571                // Fail-fast send: try_send_command_no_buffer turns a
572                // disconnected pipe into an immediate error instead of
573                // buffering the probe through a crash-restart gap, where it
574                // could age into a false "did not pump" miss (see
575                // run_windows's identical comment for the full rationale).
576                if let Err(e) = host_pipe
577                    .try_send_command_no_buffer(&agentmux_common::ipc::Command::ProbeUiThread {
578                        nonce: ui_probe_nonce,
579                    })
580                    .await
581                {
582                    crate::ui_liveness::retract_probe(ui_probe_nonce);
583                    log(&format!(
584                        "[ui-liveness] probe send failed (transport, not liveness): {:?}",
585                        e
586                    ));
587                }
588            }
589            host_status = host_child.wait() => {
590                // SPEC_LAUNCHER_TEARDOWN_BACKSTOP Phase 2 — the host exiting
591                // (cleanly, crashing, or relaunched) always stands the armed
592                // teardown down: an Armed machine's whole premise is "the
593                // host is alive but wedged", and this is the crash-restart-
594                // gap false-positive guard — the machine stays suspended
595                // across the restart and can only re-arm from a fresh drain
596                // report by the NEW host.
597                if crate::teardown_backstop::disarm() {
598                    log("[teardown-backstop] disarmed — host exited (supervised-exit path owns it now)");
599                }
600                use std::os::unix::process::ExitStatusExt;
601                let status = match host_status {
602                    Ok(s) => s,
603                    Err(e) => {
604                        log(&format!("FATAL: host wait failed: {}", e));
605                        break 1;
606                    }
607                };
608                // The launcher stopped this host because srv was started again: start one against
609                // the new srv. It is srv's fault, counted in srv's budget, so it is not a host crash:
610                // no host budget, no GPU ladder, whatever code or signal the host ended with. Read
611                // before the exit is classified, or a SIGTERM would look like a group shutdown.
612                host_kill_at = None;
613                if std::mem::replace(&mut srv_recycle_kill, false) {
614                    log("CEF host stopped for the srv restart — relaunching it against the new srv");
615                    match spawn_host_unix(real_exe, args, &srv.result, &host_env, host_degraded) {
616                        Some(c) => {
617                            host_child = c;
618                            continue;
619                        }
620                        None => {
621                            log("host relaunch failed to spawn — giving up");
622                            break 1;
623                        }
624                    }
625                }
626                // Host killed by a signal. Originally written for the case
627                // where a terminal Ctrl+C reached the host DIRECTLY (it used
628                // to share our foreground process group) and host_child.wait()
629                // could win the select! race against our own SIGINT arm.
630                // Since PR #2200 gave host its own process group (prerequisite
631                // for the teardown backstop's group-kill), a terminal Ctrl+C
632                // no longer reaches host directly — only an EXTERNAL signal
633                // sent straight to host's own pid (e.g. `kill <host-pid>
634                // SIGTERM`, a container/systemd stop signal targeting it
635                // specifically) can still land here mid-loop. Kept for that
636                // case: without this guard such a signal-death has no exit
637                // code → unwrap_or(1) → looks like a crash and we'd relaunch a
638                // replacement host with nothing left to supervise it. Treat
639                // the group-shutdown signals (SIGINT/SIGTERM/SIGHUP) as a
640                // clean shutdown; real crash signals (SIGSEGV, SIGABRT, …)
641                // still fall through to the crash-budget relaunch below.
642                if let Some(sig) = status.signal() {
643                    if sig == libc::SIGINT || sig == libc::SIGTERM || sig == libc::SIGHUP {
644                        log(&format!("CEF host terminated by signal {} (group shutdown) — shutting down", sig));
645                        break 0;
646                    }
647                    log(&format!("CEF host killed by signal {} (crash) — entering crash-budget relaunch", sig));
648                }
649                let code = status.code().unwrap_or(1);
650                if code == 0 || super::is_sandbox_unavailable_exit(code) {
651                    log(&super::final_host_exit_line(code));
652                    break code;
653                }
654                // Classify system-OOM (wait it out) vs a genuine host fault
655                // (existing fast budget), mirroring run_windows. SPEC_MEMORY_
656                // PRESSURE_SUPERVISION_2026_06_16 §5.B. On Linux a kernel-OOM-kill
657                // arrives as a SIGKILL (code 1 here) and is caught by the low-
658                // commit reading (SPEC §9.4).
659                let commit_free = mem_supervisor::commit_free_mb();
660                match mem_supervisor::classify_host_exit(code, commit_free) {
661                    mem_supervisor::HostExitClass::SystemOom => {
662                        let now = std::time::Instant::now();
663                        if mem_supervisor::budget_exhausted(
664                            &mut oom_restarts,
665                            now,
666                            mem_supervisor::OOM_RESTART_WINDOW,
667                            mem_supervisor::OOM_RESTART_BUDGET,
668                        ) {
669                            log(&format!(
670                                "CEF host hit system OOM (code {}, {} MB commit-free); OOM restart \
671                                 budget exhausted ({} in {}s) — giving up",
672                                code,
673                                commit_free,
674                                mem_supervisor::OOM_RESTART_BUDGET,
675                                mem_supervisor::OOM_RESTART_WINDOW.as_secs()
676                            ));
677                            crate::incidents::record(&crate::incidents::memory_give_up());
678                            show_fatal_dialog(
679                                mem_supervisor::OOM_GIVEUP_TITLE,
680                                mem_supervisor::OOM_GIVEUP_BODY,
681                            );
682                            break code;
683                        }
684                        log(&format!(
685                            "CEF host hit system OOM (code {}, {} MB commit-free) — waiting for \
686                             memory to recover before relaunch",
687                            code, commit_free
688                        ));
689                        // Race the commit-recovery wait against shutdown + srv
690                        // death so the supervisor stays responsive during the
691                        // (up to OOM_RELAUNCH_DEADLINE) wait — without this the
692                        // SIGINT/SIGTERM + srv arms are starved for the whole
693                        // wait (reagent P2). Mirrors the outer select! arms.
694                        // If srv dies meanwhile, the wait goes on (there is no
695                        // running host to restart), and srv is started again
696                        // once memory is back, before the host
697                        // (SPEC_UNIX_SRV_RESTART_BUDGET_2026_10_24 §3.3).
698                        let mut wait = Box::pin(mem_supervisor::await_commit_recovery("host", log));
699                        let mut srv_stopped_during_wait: Option<crate::incidents::SrvStop> = None;
700                        let recovered = tokio::select! {
701                            r = &mut wait => r,
702                            srv_status = srv.child.wait() => {
703                                match srv_exit_action(srv_status, &mut srv_restarts, &mut srv_oom_restarts) {
704                                    SrvAction::Stop(c) => break c,
705                                    SrvAction::GiveUp(c) => {
706                                        gave_up = Some("couldn't keep its backend running");
707                                        break c;
708                                    }
709                                    SrvAction::Restart { why, .. } => srv_stopped_during_wait = Some(why),
710                                }
711                                tokio::select! {
712                                    r = &mut wait => r,
713                                    _ = next_signal(&mut sigint) => {
714                                        log("received SIGINT during OOM wait — shutting down");
715                                        break 0;
716                                    }
717                                    _ = next_signal(&mut sigterm) => {
718                                        log("received SIGTERM during OOM wait — shutting down");
719                                        break 0;
720                                    }
721                                }
722                            }
723                            _ = next_signal(&mut sigint) => {
724                                log("received SIGINT during OOM wait — shutting down");
725                                break 0;
726                            }
727                            _ = next_signal(&mut sigterm) => {
728                                log("received SIGTERM during OOM wait — shutting down");
729                                break 0;
730                            }
731                        };
732                        if !recovered {
733                            crate::incidents::record(&crate::incidents::memory_give_up());
734                            show_fatal_dialog(
735                                mem_supervisor::OOM_GIVEUP_TITLE,
736                                mem_supervisor::OOM_GIVEUP_BODY,
737                            );
738                            break code;
739                        }
740                        if let Some(why) = srv_stopped_during_wait {
741                            if let Err(e) = respawn_srv(launcher_exe_dir, &paths, &startup_sink, why, &mut srv).await {
742                                log(&format!("FATAL: srv respawn failed: {e} — terminating launcher"));
743                                gave_up = Some("couldn't keep its backend running");
744                                break 1;
745                            }
746                        }
747                        crate::incidents::record(&crate::incidents::host_restarted_low_memory());
748                        match spawn_host_unix(real_exe, args, &srv.result, &host_env, true) {
749                            Some(c) => host_child = c,
750                            None => {
751                                log("host relaunch failed to spawn — giving up");
752                                break code;
753                            }
754                        }
755                    }
756                    mem_supervisor::HostExitClass::Abnormal => {
757                        let now = std::time::Instant::now();
758                        host_restarts.retain(|t| now.duration_since(*t) < HOST_RESTART_WINDOW);
759                        if host_restarts.len() >= HOST_RESTART_BUDGET {
760                            log(&format!(
761                                "CEF host exited abnormally (code {}); restart budget exhausted \
762                                 ({} in {}s) — giving up",
763                                code,
764                                host_restarts.len(),
765                                HOST_RESTART_WINDOW.as_secs()
766                            ));
767                            crate::incidents::record(&crate::incidents::crash_give_up(
768                                crate::incidents::GaveUpOn::Window,
769                                code,
770                                host_restarts.len(),
771                                HOST_RESTART_WINDOW.as_secs(),
772                            ));
773                            gave_up = Some("keeps crashing");
774                            break code;
775                        }
776                        host_restarts.push(now);
777                        let was_degraded = host_degraded;
778                        if super::repeats_crash(last_abnormal_exit, code, now) {
779                            host_degraded = true;
780                        }
781                        last_abnormal_exit = Some((code, now));
782                        crate::incidents::record(&crate::incidents::host_restarted(code, host_degraded && !was_degraded));
783                        log(&format!(
784                            "CEF host exited abnormally (code {}) — relaunching (restart {}/{}{})",
785                            code,
786                            host_restarts.len(),
787                            HOST_RESTART_BUDGET,
788                            if host_degraded { ", degraded: --disable-gpu" } else { "" }
789                        ));
790                        match spawn_host_unix(real_exe, args, &srv.result, &host_env, host_degraded) {
791                            Some(c) => host_child = c,
792                            None => {
793                                log("host relaunch failed to spawn — giving up");
794                                break code;
795                            }
796                        }
797                    }
798                }
799            }
800            srv_status = srv.child.wait() => {
801                // srv exited with the host still running. A clean exit or a group-shutdown signal is
802                // the app stopping (see the host arm for why that still reaches here since PR #2200).
803                // Anything else is srv dying: start it again and restart the host, which is wired to
804                // the dead srv's endpoints, within srv's own budget — as run_windows does. Only a
805                // spent budget, or a srv that cannot start, ends the app.
806                let (why, wait_for_memory) = match srv_exit_action(srv_status, &mut srv_restarts, &mut srv_oom_restarts) {
807                    SrvAction::Stop(c) => break c,
808                    SrvAction::GiveUp(c) => {
809                        gave_up = Some("couldn't keep its backend running");
810                        break c;
811                    }
812                    SrvAction::Restart { why, wait_for_memory } => (why, wait_for_memory),
813                };
814                if wait_for_memory {
815                    // Race the wait against the host dying and against shutdown, as the host arm does.
816                    let recovered = tokio::select! {
817                        r = mem_supervisor::await_commit_recovery("srv", log) => r,
818                        host_status = host_child.wait() => {
819                            use std::os::unix::process::ExitStatusExt;
820                            match host_status {
821                                Ok(s) if s.success() || matches!(s.signal(), Some(sig) if sig == libc::SIGINT || sig == libc::SIGTERM || sig == libc::SIGHUP) => {
822                                    log("CEF host exited as part of shutdown (during the srv memory wait) — shutting down");
823                                    break 0;
824                                }
825                                Ok(s) => log(&format!(
826                                    "CEF host exited UNEXPECTEDLY during the srv memory wait {} — terminating launcher",
827                                    srv_exit_text(&s)
828                                )),
829                                Err(e) => log(&format!("FATAL: host wait failed during the srv memory wait: {e}")),
830                            }
831                            break 1;
832                        }
833                        _ = next_signal(&mut sigint) => {
834                            log("received SIGINT during the srv memory wait — shutting down");
835                            break 0;
836                        }
837                        _ = next_signal(&mut sigterm) => {
838                            log("received SIGTERM during the srv memory wait — shutting down");
839                            break 0;
840                        }
841                    };
842                    if !recovered {
843                        crate::incidents::record(&crate::incidents::memory_give_up());
844                        show_fatal_dialog(mem_supervisor::OOM_GIVEUP_TITLE, mem_supervisor::OOM_GIVEUP_BODY);
845                        break 1;
846                    }
847                }
848                if let Err(e) = respawn_srv(launcher_exe_dir, &paths, &startup_sink, why, &mut srv).await {
849                    log(&format!("FATAL: srv respawn failed: {e} — terminating launcher"));
850                    gave_up = Some("couldn't keep its backend running");
851                    break 1;
852                }
853                // The running host holds connections to the dead srv. End it (SIGTERM so CEF flushes
854                // its profile, SIGKILL if it hasn't stopped in time); the host arm starts the next
855                // one against `srv.result`.
856                srv_recycle_kill = true;
857                crate::host_spawn::kill_process_group_gracefully(&host_child);
858                host_kill_at = Some(tokio::time::Instant::now() + std::time::Duration::from_millis(1500));
859            }
860            _ = next_signal(&mut sigint) => {
861                log("received SIGINT — shutting down");
862                break 0;
863            }
864            _ = next_signal(&mut sigterm) => {
865                log("received SIGTERM — shutting down");
866                break 0;
867            }
868        }
869    };
870
871    #[cfg(target_os = "linux")]
872    crate::notify::shutdown();
873
874    // Close any open saga brackets before tearing down children so the
875    // durable log doesn't carry dangling SagaStarted entries into the
876    // next startup's LSD-3 compensation pass.
877    saga_coord.cancel_all_in_flight("launcher shutting down").await;
878
879    // 6. Cleanup, both children at once. The host: SIGTERM so it reaps its
880    //    render subprocesses, a short grace, then SIGKILL. srv: the one stop
881    //    path (`quiesce_srv`), which lets it close every agent gracefully
882    //    first (`agent_teardown::app_exit`) before any force-kill.
883    log("stopping children (host: SIGTERM → grace → SIGKILL; srv: quiesce)");
884    let stop_host = async {
885        terminate_child_gracefully(&host_child);
886        let _ = tokio::time::timeout(std::time::Duration::from_millis(1500), host_child.wait()).await;
887        let _ = host_child.start_kill();
888    };
889    let stop_srv = crate::upgrade::quiesce_srv(
890        &mut srv.child,
891        srv.stdin.take(),
892        agentmux_common::process::SRV_EXIT_WAIT,
893    );
894    let ((), srv_stopped) = tokio::join!(stop_host, stop_srv);
895    let srv_gone = match srv_stopped {
896        Ok((_, crate::upgrade::QuiesceOutcome::ExitedAfterForceKill)) => {
897            // Killed mid-teardown, with its own process group (`quiesce_srv`
898            // does that while srv is still unreaped). Its agent CLIs lead
899            // groups of their own and are ended just below.
900            log("WARN: srv didn't exit in time — killed it and its process group");
901            true
902        }
903        Ok((_, outcome)) => {
904            log(&format!("srv stopped ({outcome:?})"));
905            true
906        }
907        Err(e) => {
908            log(&format!("WARN: stopping srv failed: {e}"));
909            false
910        }
911    };
912    end_agents_left_by_srv(&paths.data_dir, srv.pid.filter(|_| srv_gone));
913    // Nothing of this install runs now but this launcher: the helper can replace it once it exits.
914    if let Some(why) = gave_up {
915        if offer_go_back(version, launcher_exe_dir, &paths.data_dir, why) {
916            log("upgrade: going back to the version before the last upgrade; exiting for the helper");
917        }
918    }
919    // srv has stopped, so the new version copies complete data on its first
920    // start. Only after a clean quit the user confirmed recently.
921    if let Some((staged, at)) = relaunch.filter(|(_, at)| exit_code == 0 && crate::upgrade_restart::still_confirmed(*at)) {
922        match crate::upgrade_restart::relaunch(&staged) {
923            Ok(()) => log(&format!("upgrade: started {staged} (confirmed {}s ago)", at.elapsed().as_secs())),
924            Err(e) => log(&format!("upgrade: couldn't start {staged}: {e}")),
925        }
926    }
927    log(&format!("launcher exiting with code {}", exit_code));
928    std::process::exit(exit_code);
929}
930
931/// A `.deb`/`.rpm` upgrade the app did that now can't be kept running: offer the version
932/// before it (`upgrade_package::offer_go_back`). `true` when the user said yes and the
933/// helper is waiting for this launcher to exit.
934#[cfg(target_os = "linux")]
935fn offer_go_back(version: &str, launcher_exe_dir: &std::path::Path, data_dir: &std::path::Path, why: &str) -> bool {
936    crate::upgrade_package::offer_go_back(version, launcher_exe_dir, data_dir, why)
937}
938
939#[cfg(not(target_os = "linux"))]
940fn offer_go_back(_version: &str, _launcher_exe_dir: &std::path::Path, _data_dir: &std::path::Path, _why: &str) -> bool {
941    false
942}
943
944/// srv is gone. An agent CLI it didn't close (srv was killed, crashed, or ran
945/// out of time) still runs in its own process group: end it and what it
946/// started. srv deletes `agent-roots.json` when it closed every agent itself.
947/// `srv_pid` is the pid taken when srv was spawned: tokio's `Child::id()` is
948/// `None` once the child has been waited on, which is the case here.
949pub(super) fn end_agents_left_by_srv(data_dir: &std::path::Path, srv_pid: Option<u32>) {
950    let Some(srv_pid) = srv_pid else { return };
951    if let Some(done) = agentmux_common::agent_roots::kill_orphans(data_dir, srv_pid) {
952        log(&format!(
953            "srv left agent CLIs running: killed {} agent cgroup(s) and {} CLI process group(s); {} had already exited",
954            done.cgroups, done.groups, done.gone
955        ));
956    }
957}
958
959/// How srv ended, for the log: "with code 3", or "killed by signal 9
960/// (SIGKILL)" when a signal ended it and there is no exit code. An outage on
961/// 2026-10-24 logged "code 1" for an srv that was killed, which hid the signal.
962fn describe_srv_exit(code: Option<i32>, signal: Option<i32>, core_dumped: bool) -> String {
963    match (code, signal) {
964        (Some(code), _) => format!("with code {code}"),
965        (None, Some(sig)) => {
966            let name = signal_name(sig);
967            let core = if core_dumped { ", core dumped" } else { "" };
968            if name.is_empty() {
969                format!("killed by signal {sig}{core}")
970            } else {
971                format!("killed by signal {sig} ({name}){core}")
972            }
973        }
974        (None, None) => "with no exit code or signal".to_string(),
975    }
976}
977
978/// [`describe_srv_exit`] for a real exit status.
979pub(super) fn srv_exit_text(s: &std::process::ExitStatus) -> String {
980    use std::os::unix::process::ExitStatusExt;
981    describe_srv_exit(s.code(), s.signal(), s.core_dumped())
982}
983
984#[cfg(test)]
985mod tests {
986    use super::describe_srv_exit;
987
988    #[test]
989    fn an_exit_code_is_reported_as_a_code() {
990        assert_eq!(describe_srv_exit(Some(1), None, false), "with code 1");
991    }
992
993    #[test]
994    fn a_signal_is_named_not_reported_as_code_1() {
995        assert_eq!(
996            describe_srv_exit(None, Some(libc::SIGKILL), false),
997            "killed by signal 9 (SIGKILL)"
998        );
999        assert_eq!(
1000            describe_srv_exit(None, Some(libc::SIGSEGV), true),
1001            "killed by signal 11 (SIGSEGV), core dumped"
1002        );
1003    }
1004
1005    #[test]
1006    fn an_unnamed_signal_keeps_its_number() {
1007        assert_eq!(
1008            describe_srv_exit(None, Some(libc::SIGUSR2), false),
1009            format!("killed by signal {}", libc::SIGUSR2)
1010        );
1011    }
1012
1013    #[test]
1014    fn a_real_kill_reaches_the_log_as_its_signal() {
1015        let mut child = std::process::Command::new("sleep")
1016            .arg("30")
1017            .spawn()
1018            .unwrap();
1019        child.kill().unwrap();
1020        let status = child.wait().unwrap();
1021        assert_eq!(
1022            super::srv_exit_text(&status),
1023            "killed by signal 9 (SIGKILL)"
1024        );
1025    }
1026
1027    /// The case the cleanup exists for: srv is killed and reaped before the
1028    /// teardown runs. tokio has then forgotten its pid, so the launcher uses
1029    /// the one it took at spawn; the CLI srv recorded dies, a pid whose start
1030    /// time doesn't match is left alone.
1031    #[tokio::test]
1032    async fn a_cli_left_by_a_reaped_srv_is_ended() {
1033        let dir = std::env::temp_dir().join(format!("launcher-orphans-{}", std::process::id()));
1034        std::fs::create_dir_all(&dir).unwrap();
1035        let mut srv = tokio::process::Command::new("sleep").arg("30").process_group(0).spawn().unwrap();
1036        let srv_pid = srv.id();
1037        let mut cli = tokio::process::Command::new("sleep").arg("30").process_group(0).spawn().unwrap();
1038        let cli_pid = cli.id().unwrap();
1039        let roots = agentmux_common::agent_roots::AgentRoots {
1040            srv_pid: srv_pid.unwrap(),
1041            cgroup: None,
1042            roots: vec![agentmux_common::agent_roots::Root {
1043                pid: cli_pid,
1044                start: agentmux_common::process::process_start_time(cli_pid).unwrap(),
1045            }],
1046        };
1047        agentmux_common::agent_roots::write(&dir, &roots).unwrap();
1048
1049        srv.kill().await.unwrap();
1050        assert_eq!(srv.id(), None, "tokio forgets the pid once srv is reaped");
1051        super::end_agents_left_by_srv(&dir, None);
1052        assert!(cli.try_wait().unwrap().is_none(), "no pid, no signal");
1053
1054        super::end_agents_left_by_srv(&dir, srv_pid);
1055        let status = tokio::time::timeout(std::time::Duration::from_secs(5), cli.wait()).await.unwrap().unwrap();
1056        assert!(!status.success());
1057        assert_eq!(agentmux_common::agent_roots::read(&dir), None, "the file is deleted");
1058        let _ = std::fs::remove_dir_all(&dir);
1059    }
1060}