Skip to main content

agentmux_srv/bootstrap/
state_services.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What `app_main` starts once the app state exists, in the order it started them: the
5//! hooks that let an agent be reached and resumed, the job run ledger and the cron
6//! scheduler, the sagas an earlier run left unresolved, and the services that run beside
7//! the server. Moved out of `app_main` without a change in behaviour.
8
9use super::*;
10use std::future::IntoFuture;
11
12/// Wires delivery and the restart-time resumers to the app state, and starts the native
13/// memory watchers.
14pub fn install_state_hooks(state: &AppState) {
15    // The relay's delivery path reaches the server's holds and file steps through this, before anything is claimed.
16    crate::server::muxbus_hooks::install();
17    // The controller code reaches the agent teardown through this, before any controller runs.
18    crate::sagas::teardown_hooks::install();
19    // The ambient calls find a provider's CLI through the server's lookup.
20    crate::ambient::cli_locator::set_locator(crate::server::cli_handlers::locate_for_ambient);
21    // Upgrade reactive message delivery now that AppState exists, so agents on a
22    // SubprocessController (every container agent, plus codex/gemini/qwen/kimi/
23    // muxcode on the host) can actually receive inter-agent
24    // messages instead of having them dropped on a PTY fallback they reject.
25    install_agent_turn_delivery(state);
26    // What is held for an agent waits while its pane has no controller yet (every resumed pane, at start).
27    crate::backend::reactive::controller_wait::set_has_controller(std::sync::Arc::new(|block_id: &str| crate::backend::blockcontroller::get_controller(block_id).is_some()));
28
29    // Cron fires through the same in-process inject path (identity M4c-3);
30    // before `cron_scheduler.start()` below, so no fire takes the HTTP
31    // fallback.
32    install_cron_delivery(state);
33    crate::server::job_actions::install(state);
34    // The Drone blocks that act on AgentMux (App query, Message, Task, Spawn, Notify) reach it here.
35    crate::drone::host::install(state);
36
37    // Durable jekt: replay messages held for an agent that was not running
38    // (SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md).
39    crate::server::jekt_held::install(state);
40    // The status bar learns of a change in the messages held for agents without asking (`jekt.held.summary`).
41    crate::server::jekt_held_summary::install(state);
42    // A routine message that came by the relay waits for a session gone cold, as a local one does (#2263).
43    crate::server::jekt_cold::install(state);
44    // A parked agent no pane shows is sent the input held for it while its model API was out.
45    crate::server::held_input::install(state);
46
47    // Agent panes no window reconnected to after the restart get their controller a minute in.
48    crate::server::controller_backstop::install(state);
49
50    // Idle agents with no view are stopped after the window (agents:always_available).
51    crate::server::agent_lifecycle::install(state);
52
53    // Parked agents that were running when srv stopped are resumed, a few seconds apart (agents:always_available).
54    crate::server::restart_resume::install(state);
55
56    // An agent has one pane: a second pane an older layout left is closed, pointing at the first.
57    crate::server::app_api::agent_reconcile::install(state);
58
59    // The helper install asks first (SPEC_REMOTES_PANE_2026_10_05.md §4.9).
60    crate::server::app_api::connections::install_helper_consent(state);
61
62    // Now that AppState exists, wire up close-on-exit so a shell pane can
63    // actually close itself when its process exits — see
64    // `install_close_on_exit_handler`'s doc comment.
65    install_close_on_exit_handler(state);
66
67    // Backstop for agent blocks left in a tab but in no pane — see
68    // `crate::sagas::orphan_reaper`'s module doc.
69    crate::sagas::orphan_reaper::install(state);
70
71    // Out-of-band native-memory write detection (fast fs-watch path + slow
72    // reconciliation-sweep path) — see
73    // docs/specs/SPEC_MEMORY_VERSION_CONTROL_AND_ARMORY_AUDIT_2026_08_19.md §4.5.
74    // Only the agents running in this process: the roster and the identity folders are shared by every
75    // channel on the host, and a channel starting beside another reads nothing of the other's agents.
76    let drift_state = state.clone();
77    backend::memory::native_drift::spawn(
78        state.fs_watch_pool.clone(),
79        state.mstore.clone(),
80        state.id_store.clone(),
81        state.broker.clone(),
82        std::sync::Arc::new(move || crate::server::agent_lifecycle::running_agent_ids(&drift_state)),
83    );
84
85    // Retention/GC for native-memory version history — see
86    // docs/specs/SPEC_MEMORY_VERSION_CONTROL_AND_ARMORY_AUDIT_2026_08_19.md §7.1.
87    backend::memory::native_retention::spawn(state.id_store.clone());
88
89    // The signing keys an older launch wrote into agents' `.mcp.json` files: taken out of each agent's folder, once per start,
90    // off the startup path.
91    let sweep_store = state.mstore.clone();
92    let _ = std::thread::Builder::new().name("mcp-json-key-sweep".into()).spawn(move || {
93        let files = backend::mcp_json_identity::strip_known_agents_signing_keys(&sweep_store);
94        if files > 0 {
95            tracing::info!(files, "start: removed old signing keys from agents' .mcp.json files");
96        }
97    });
98}
99
100/// Opens the job run ledger, closes the runs a restart interrupted, then starts the
101/// cron scheduler.
102pub async fn start_job_ledger_and_cron(state: &AppState) {
103    // The run ledger (SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3): close the
104    // runs a restart interrupted, then record every fire from here on.
105    let run_ledger = backend::jobs::RunLedger::new(
106        crate::server::cron::ledger_store(state),
107        Some(state.mstore.clone()),
108        state.broker.clone(),
109    );
110    // A `spawn` job's worker is closed when its run ends: its tab goes, so it
111    // doesn't count against the leader's worker limit for the next run.
112    let worker_state = state.clone();
113    run_ledger.install_worker_stop(std::sync::Arc::new(move |block_id: &str| {
114        crate::sagas::pending_shutdown::request(
115            &worker_state,
116            block_id,
117            "jobs",
118            "JobWorker",
119            "its run ended",
120            crate::sagas::pending_shutdown::Action::CloseTab {
121                detail: "a job's worker, its run ended".to_string(),
122            },
123        );
124    }));
125    // Runs are weighed against Settings' spending caps before they start, and
126    // stopped when they reach their own (jobs spec §5.3).
127    crate::server::job_caps::install(state, &run_ledger);
128    // A timeout or cancel of a run another channel follows is asked of that channel.
129    crate::server::jobs_remote_stop::install(state, &run_ledger);
130    // A failing job opens one incident for its owner (jobs spec §3.4).
131    run_ledger.install_incidents(crate::server::cron::jobs_store(state));
132    // Cloud jobs report their runs in over MuxBus (jobs spec §4).
133    backend::jobs::cloud_hub::install(run_ledger.clone());
134    // A cloud run that never reported, or stopped reporting, is given up on (jobs spec §4.4).
135    if let Some(templates) = backend::job_templates::service() {
136        backend::jobs::watchdog::start(run_ledger.clone(), std::sync::Arc::new(templates.clone()));
137    }
138    // Drone runs that kept checkpoints go on from their newest; the rest of what the
139    // old process left open is closed as interrupted.
140    let resuming = crate::server::drone_resume::resume_runs(state, Some(&run_ledger)).await;
141    {
142        let ledger = run_ledger.clone();
143        let _ = tokio::task::spawn_blocking(move || ledger.recover_after_restart_except(&resuming)).await;
144    }
145    // A paused job's slots are counted as skips (jobs spec §3.3).
146    if let Some(jobs_store) = crate::server::cron::jobs_store(state) {
147        backend::jobs::paused::spawn(jobs_store, run_ledger.clone());
148    }
149    let local_ledger = run_ledger.clone();
150    state.cron_scheduler.install_runs(run_ledger);
151    // An `app_event` job's runs start when the broker reports the event it names; a `file_watch` job's, when its folder changes; a `poll` job's, when its query finds something new.
152    if let Some(jobs_store) = crate::server::cron::jobs_store(state) {
153        backend::jobs::app_events::spawn(&state.broker, state.mstore.clone(), jobs_store.clone(), state.cron_scheduler.clone());
154        backend::jobs::file_watch::spawn(&state.broker, state.fs_watch_pool.clone(), jobs_store.clone(), state.cron_scheduler.clone());
155        backend::jobs::poll::spawn(jobs_store, state.cron_scheduler.clone(), crate::drone::executor::blocks::app_query::poll_check());
156    }
157
158    // Start persistent cron scheduler — load enabled jobs from DB, fire any
159    // that missed their window (FIRE_ONCE_NOW), schedule all for future fires.
160    state.cron_scheduler.start().await;
161    // A local slot that passed with no row of any kind is given up on (jobs spec §4.4). After the scheduler's start-up
162    // catch-up, whose collapsed rows cover the slots missed while AgentMux was off.
163    if let Some(jobs_store) = crate::server::cron::jobs_store(state) {
164        backend::jobs::watchdog::start_local(local_ledger, jobs_store);
165    }
166}
167
168/// Compensates the sagas an earlier run left unresolved; non-fatal when it fails.
169pub async fn resume_unresolved_sagas(state: &AppState) {
170    // Saga durability PR 2 — resume-on-startup. Walk any sagas the
171    // durable log says are unresolved (running / compensating /
172    // failed) from a prior srv-process run, dispatch their inverse
173    // commands, and mark them compensated. Runs AFTER reducer
174    // bootstrap + persist subscriber spawn so the recovery's reducer
175    // dispatches operate against fully-populated state, BUT BEFORE
176    // the API server starts accepting requests so resumed
177    // compensation can't interleave with new sagas.
178    //
179    // Failure here is non-fatal: the saga log read might be transient,
180    // and starting up without recovery beats refusing to start.
181    // Operator can still inspect via `--diag sagas` (PR 2 part 2).
182    let resumed = crate::boot_timing::time_async(
183        "saga_resume_on_startup",
184        crate::sagas::recovery::compensate_unresolved(state),
185    )
186    .await
187    .unwrap_or_else(|e| {
188        tracing::error!(
189            "[saga] resume-on-startup failed: {} — continuing; operator review needed",
190            e
191        );
192        0
193    });
194    if resumed > 0 {
195        tracing::info!(
196            "[saga] resume-on-startup compensated {} unresolved saga(s) from prior run",
197            resumed
198        );
199    }
200}
201
202/// What agents spend through the model gateway is kept across restarts, and a cap reached is acted on
203/// (SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md §3).
204fn spawn_spend_services(state: &AppState) {
205    backend::model_gateway::spend::attach(Arc::clone(&state.mstore));
206    crate::server::spend_watch::start(state.clone());
207}
208
209/// Background-task rows end when their command exits, whose process is gone, or that nothing has reported on for a day
210/// (SPEC_BACKGROUND_TASK_STRUCTURED_FEED_AND_SWARM_OWNERSHIP_2026_09_27.md §5).
211fn spawn_background_task_sweep(state: &AppState) {
212    backend::background_task_exit::install(Arc::clone(&state.broker), Arc::clone(&state.mstore));
213    backend::background_task_pid::install(Arc::clone(&state.broker), Arc::clone(&state.mstore));
214    // A container pane's rows are checked inside its container, through whichever runtime srv is connected to.
215    let containers = backend::container_task_probe::DockerProbe { runtime: Arc::clone(&state.container_manager) };
216    backend::background_task_sweep::start(Arc::clone(&state.mstore), Arc::clone(&state.broker), Some(Arc::new(containers)));
217}
218
219/// Starts the services that run beside the server and need the app state.
220/// The panes that watch messages are told as they happen: the Audit when a row is written, the Atlas map when
221/// a message goes between two agents.
222fn install_message_brokers(state: &AppState) {
223    backend::audit_live::install_broker(Arc::clone(&state.broker));
224    backend::message_flow::install(Arc::clone(&state.broker));
225    backend::task_flow::install(Arc::clone(&state.broker));
226    backend::pr_flow::install(Arc::clone(&state.broker));
227    backend::pr_flow::install_cards(Arc::clone(&state.identity_store));
228    start_container_status(state);
229    install_withhold_alert(state);
230}
231
232/// An Audit row when the registry of withheld values refuses a value or degrades its matching: a line with the counts,
233/// never a value.
234fn install_withhold_alert(state: &AppState) {
235    let handler = state.reactive_handler;
236    backend::transcript::withhold::set_alert(queued_alert(move |line| {
237        handler.log_fleet_action_audit(Some("srv"), "srv", "", "transcript.withhold", false, Some(line.as_str()), &uuid::Uuid::new_v4().to_string(), None);
238    }));
239}
240
241/// A callback that only queues each line; `deliver` runs on its own thread. The registry raises an alert from inside
242/// message delivery, where the handler's lock is held, so a `deliver` that took that lock there would never return.
243fn queued_alert(deliver: impl Fn(String) + Send + 'static) -> impl Fn(&str) + Send + Sync + 'static {
244    let (queue, lines) = std::sync::mpsc::channel::<String>();
245    let spawned = std::thread::Builder::new().name("withhold-alert".into()).spawn(move || {
246        for line in lines {
247            deliver(line);
248        }
249    });
250    if let Err(e) = spawned {
251        tracing::warn!("withhold alert worker not started, alerts are only logged: {e}");
252    }
253    move |line| {
254        let _ = queue.send(line.to_string());
255    }
256}
257
258/// The Atlas map and the Swarm show this machine's agent containers as they change (`backend::container_status`).
259/// A machine with no container runtime is looked at once.
260fn start_container_status(state: &AppState) {
261    let mstore = Arc::clone(&state.mstore);
262    let hub = backend::container_status::install(Arc::clone(&state.broker), move || {
263        mstore.agent_def_list().unwrap_or_default().into_iter().filter(|d| d.is_seeded != 1).map(|d| (d.id, d.name)).collect()
264    });
265    // Git facts of a container agent are read inside its container, through this runtime.
266    backend::container::mounts::read_exec::install(&state.container_manager);
267    let source = backend::container_status::DockerSource::new(Arc::clone(&state.container_manager));
268    tokio::spawn(backend::container_status::run(source, hub, Default::default()));
269}
270
271/// Lists this instance for the other AgentMux instances on this machine (`muxspect instances`).
272pub fn publish_instance_record(state: &AppState) {
273    backend::instance_registry::spawn(backend::instance_registry::Identity {
274        version: state.version.clone(),
275        local_url: state.local_web_url.clone(),
276        auth_key: state.auth_key.clone(),
277        started_at: agentmux_common::time::now_ms_u64(),
278    });
279}
280
281pub fn spawn_state_services(state: &AppState) {
282    // Keeps the host's copy of which panes agents own current (for its popup
283    // decisions; docs/specs/SPEC_BROWSER_PANE_NATIVE_POPUPS_AGENT_DRIVEN_2026_10_08.md §3).
284    crate::server::browser_host_sync::spawn(state.clone());
285    // Every agent's runtime state is looked at and each change published (`agentruntime:changed:<id>`).
286    crate::server::agent_runtime::spawn(state.clone());
287    // srv's own memory and what holds it, logged every five minutes (`backend::mem_census`).
288    crate::server::muxspect_memory::spawn_reporter(state.clone());
289    spawn_spend_services(state);
290    // A running agent's startup file follows Global Memory (SPEC_MEMORY_DELIVERY_INDEX_NOT_FULL_TEXT_2026_11_17.md §3.1).
291    crate::server::startup_refresh::start(state.clone());
292    spawn_background_task_sweep(state);
293    // Overlap notes (an agent editing a file another agent is also changing
294    // is told who): the progress watcher's edits are checked from here on.
295    backend::work_facts::overlap_notes::install(
296        Arc::clone(&state.mstore),
297        Arc::clone(&state.work_store),
298        Arc::clone(&state.config_watcher),
299        state.http_client.clone(),
300        state.local_web_url.clone(),
301    );
302    // The Kanban: idle agents are reminded of the tasks waiting for them,
303    // and a PR opened on a task is linked to it (SPEC_WARDEN_KANBAN_2026_10_20.md).
304    backend::kanban::install(
305        Arc::clone(&state.mstore),
306        Arc::clone(&state.work_store),
307        Arc::clone(&state.config_watcher),
308        state.broker.clone(),
309        state.http_client.clone(),
310    );
311    tokio::spawn(backend::kanban::run_reminder_loop());
312    // A Vault entry's expiry date is reminded of, and its rotation filed as a task
313    // (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §15.2).
314    tokio::spawn(backend::vault::expiry::run(
315        Arc::clone(&state.identity_store),
316        Arc::clone(&state.work_store),
317        state.broker.clone(),
318    ));
319    // HTTP sign-ins the keychain still holds move into the Vault, under Personal (same spec §5.4, §9.3).
320    let vault = Arc::clone(&state.identity_store);
321    tokio::task::spawn_blocking(move || backend::vault::signins::move_from_keychain(&vault));
322    // An agent out of quota is woken at its reset (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §7).
323    backend::limit_wake::install(
324        Arc::clone(&state.mstore),
325        Arc::clone(&state.work_store),
326        Arc::clone(&state.event_bus),
327    );
328    tokio::spawn(backend::kanban::prs::run_merge_loop());
329    // An agent's AgentMux MCP server that didn't connect is noticed and
330    // repaired (`agent:mcpselfheal`).
331    backend::mcp_health::install(Arc::clone(&state.config_watcher));
332    // And one whose process is alive but has stopped answering, noticed by its
333    // heartbeat going quiet (#2614).
334    backend::mcp_health::spawn_watch(
335        tokio_util::sync::CancellationToken::new(),
336        |block_id, process, wedge| {
337            use backend::blockcontroller::persistent::PersistentSubprocessController;
338            if let Some(ctrl) = backend::blockcontroller::get_controller(block_id) {
339                if let Some(ctrl) = ctrl
340                    .as_any()
341                    .downcast_ref::<PersistentSubprocessController>()
342                {
343                    ctrl.mcp_wedged(process, wedge);
344                }
345            }
346        },
347    );
348    // Claude config dirs get the auto-compact window `agent:compactat` asks for.
349    backend::providers::install_config(Arc::clone(&state.config_watcher));
350    backend::context_reading::install_config(Arc::clone(&state.config_watcher));
351    // A container agent's turn that ended well is when srv's compaction backstop looks at its context.
352    let backstop_state = state.clone();
353    backend::context_reading::observe_container_turn_ends(Box::new(move |block_id| {
354        crate::server::compact_backstop::after_container_turn(&backstop_state, block_id);
355    }));
356    backend::container::limits::install_config(Arc::clone(&state.config_watcher));
357    // The Claude CLI's own cross-session messaging is off unless `agent:climessaging` is true.
358    backend::cli_messaging::install_config(Arc::clone(&state.config_watcher));
359    // The Supervisor's switch and limits are read live from the settings.
360    backend::supervisor::settings::install_config(Arc::clone(&state.config_watcher));
361    backend::transcript::framer::install_config(Arc::clone(&state.config_watcher));
362    backend::transcript::damage::install_broker(Arc::clone(&state.broker));
363    install_message_brokers(state);
364    crate::identity::accounts_changed::install_broker(Arc::clone(&state.broker));
365    // The open workspace saves itself as it changes (SPEC_WORKSPACES_2026_10_23.md §4.1).
366    crate::server::service::user_workspace::spawn_saver(Arc::clone(&state.mstore));
367    // One notice per account its agents are out of quota or signed out on
368    // (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §6).
369    crate::server::account_episodes::install(state.clone());
370    install_lan_sync(state);
371    // Agents' cargo caches are cleared as tasks finish, and the disk is watched
372    // (SPEC_BUILD_CACHE_CLEANUP_2026_10_26.md).
373    backend::build_cache_service::install(
374        Arc::clone(&state.mstore),
375        Arc::clone(&state.config_watcher),
376    );
377    // The version folders and unpacked portables an upgrade leaves behind are listed daily, and cleared on a host that turns it on.
378    backend::old_versions_service::install(Arc::clone(&state.config_watcher), crate::server::external_host::host().is_some());
379    install_turn_outcome_notes(state);
380}
381
382/// What this machine sends the machines on the LAN that are behind: fleet Global Memory entries, and the collections
383/// (Kanban boards) it shares with them (SPEC_USER_DATA_SYNC_LAYER §4.2).
384fn install_lan_sync(state: &AppState) {
385    crate::server::remote_ops::fleet_sync::install(state.clone());
386    crate::server::remote_ops::sync_loop::install(state.clone());
387}
388
389/// Tells whoever needs to know when a turn's outcome wasn't otherwise reported: a worker's leader
390/// (`worker_notes`, SPEC_AGENT_WORKERS_2026_10_15.md §3.3), and, since #2627, whoever sent the message that
391/// started a turn which then died of a retryable failure (`sender_failure_note`).
392fn install_turn_outcome_notes(state: &AppState) {
393    backend::worker_notes::install(
394        Arc::clone(&state.broker),
395        state.srv_events_tx.subscribe(),
396        Arc::clone(&state.mstore),
397        Arc::clone(&state.work_store),
398        Arc::clone(&state.filestore),
399        Arc::clone(&state.config_watcher),
400    );
401    // An agent that owes work and has gone quiet is nudged once, then its watchers are told
402    // (SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md).
403    backend::quiet_watch::install(
404        Arc::clone(&state.mstore),
405        Arc::clone(&state.work_store),
406        Arc::clone(&state.filestore),
407        Arc::clone(&state.config_watcher),
408    );
409    // A lead on another machine is sent the same note over the LAN (section 19 of that spec).
410    crate::server::quiet_remote::install(state.clone());
411    backend::sender_failure_note::install(Arc::clone(&state.broker), Arc::clone(&state.mstore));
412}
413
414/// Starts what is read from the data folder once the stores and watchers exist: widget
415/// packages, job templates and the Vault's secret-file folder.
416pub fn start_data_home_services(config: &config::Config, bg: &BackgroundSubsystems) {
417    // Widget packages: scan ~/.agentmux/widgets, apply this instance's
418    // approvals, merge their widget-bar entries, watch the folder
419    // (SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §8.1). After the user's
420    // widgets.json loaded above, whose v1 module entries it lists too.
421    backend::widget::packages::start(
422        &config.data_home,
423        config.auth_key.clone(),
424        bg.fs_watch_pool.clone(),
425        bg.config_watcher.clone(),
426        bg.event_bus.clone(),
427        bg.broker.clone(),
428    );
429    // Job templates: this instance's approvals and pinned publishers, beside
430    // the widgets' (SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.4).
431    backend::job_templates::start(&config.data_home);
432    // Where a command's Vault secret files go, emptied of any a crash left
433    // (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.3).
434    backend::vault::files::init(&config.data_home);
435}
436
437/// Tells the launcher srv is ready (the pipe on Windows, then `AGENTMUXSRV-ESTART`), logs the
438/// boot summary and queues the saga log's pruning.
439pub fn announce_ready(
440    state: &AppState,
441    net: &NetworkBundle,
442    reducer: &ReducerPlumbing,
443    config: &config::Config,
444    version: &str,
445    build_time: &str,
446) {
447    #[cfg(not(target_os = "windows"))]
448    let _ = reducer;
449    // Phase E.1b — srv pipe IPC server (Windows only; conditional on
450    // AGENTMUX_SRV_PIPE_PATH). Bind happens BEFORE the AGENTMUXSRV-ESTART
451    // line so the launcher knows the pipe is ready when host starts.
452    #[cfg(target_os = "windows")]
453    bind_srv_pipe_ipc(
454        version,
455        Arc::clone(&state.srv_state),
456        state.srv_events_tx.clone(),
457        Arc::clone(&reducer.srv_event_log),
458    );
459
460    // 6. Emit AGENTMUXSRV-ESTART on stderr (exact format from cmd/server/main-server.go:617)
461    emit_estart(
462        net.ws_addr.port(),
463        net.web_addr.port(),
464        version,
465        build_time,
466        &config.instance_id,
467    );
468
469    crate::boot_timing::log_summary();
470
471    // After ESTART, off the boot path: drop sagas that finished cleanly over
472    // 30 days ago, so sagas.db stops growing.
473    let saga_log = Arc::clone(&state.saga_log);
474    tokio::task::spawn_blocking(move || {
475        match saga_log.prune_finished_older_than(std::time::Duration::from_secs(30 * 24 * 60 * 60))
476        {
477            Ok(0) => {}
478            Ok(n) => tracing::info!("[saga] pruned {n} saga(s) that finished over 30 days ago"),
479            Err(e) => tracing::warn!("[saga] pruning finished sagas failed: {e}"),
480        }
481    });
482}
483
484/// Hands the LAN listeners their routers and starts the dev proxy.
485pub fn attach_listeners(
486    state: &AppState,
487    net: &NetworkBundle,
488    lan_router: axum::Router,
489    viewer_router: axum::Router,
490) {
491    // Native dev-proxy (docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md)
492    // — a small standalone HTTP server on its own fixed port, separate from
493    // the web/ws listeners above (Host-header routing to container-internal
494    // addresses, not part of AgentMux's own API surface). Detached: a bind
495    // failure or later error is logged inside `serve` itself and never
496    // fatal to srv startup, same posture as `lan_listeners`' reconcile loop.
497    tokio::spawn(backend::dev_proxy::serve(state.dev_proxy.clone()));
498
499    // Hand the LAN listener supervisor its router now that one exists —
500    // `build_routers` consumes `AppState`, which owns the supervisor, so this
501    // cannot happen at construction time. Then honor the current setting and
502    // start the self-healing sweep, which also picks up interface changes
503    // (DHCP renewal, Wi-Fi↔Ethernet handoff, VPN up/down) without a restart.
504    // See `backend::lan::listeners`.
505    net.lan_listeners.set_router(lan_router);
506    // The viewer listener (backend::viewer) comes up beside the LAN
507    // listeners, on its own port of the same range.
508    net.lan_listeners.set_viewer(
509        viewer_router,
510        Arc::clone(&state.viewer),
511        backend::lan::ports::LAN_PORT_RANGE,
512    );
513    net.lan_listeners
514        .apply(state.config_watcher.get_settings().network_lan_discovery);
515    Arc::clone(&net.lan_listeners).spawn_reconcile_loop();
516}
517
518/// Starts the loops that run for as long as the servers do and stop with `stdin_token`.
519pub fn spawn_serving_loops(
520    state: &AppState,
521    stdin_token: &tokio_util::sync::CancellationToken,
522) {
523    let fleet_source = backend::fleet_source::FleetSource::live(
524        state.reactive_handler,
525        Arc::clone(&state.mstore),
526        Arc::clone(&state.config_watcher),
527        state.local_web_url.clone(),
528    );
529    // Periodic WAL checkpoint — prevents unbounded WAL file growth during
530    // long-running sessions.
531    spawn_wal_checkpoint_loop(
532        stdin_token.clone(),
533        Arc::clone(&state.mstore),
534        Arc::clone(&state.filestore),
535    );
536    spawn_global_transcripts_truncate_loop(
537        stdin_token.clone(),
538        state.global_transcript_store.clone(),
539    );
540
541    // The fleet feed's change detection (`backend::fleet_feed`): compares the
542    // reachable agents, their kinds and states and this machine's channel
543    // count once a second, stops with the same token.
544    Arc::clone(&state.fleet_feed)
545        .spawn_change_detection(move || fleet_source.observe(), stdin_token.clone());
546
547    // The cloud presence record, published from the fleet feed's snapshot
548    // while signed in (`muxbus::wan_presence`). Here rather than beside
549    // `wan_publish::spawn` because the feed exists only once AppState does.
550    // Whether this install publishes by default is `wan_presence::policy`'s: a headless srv follows the desktop's rule.
551    crate::muxbus::cloud_installs::install(Arc::clone(&state.id_store), state.http_client.clone());
552    crate::muxbus::wan_presence::spawn(
553        Arc::clone(&state.fleet_feed),
554        Arc::clone(&state.id_store),
555        Arc::clone(&state.config_watcher),
556        stdin_token.clone(),
557    );
558}
559
560/// What runs once the servers have stopped: this channel leaves the LAN, then every agent closes.
561pub async fn shut_down(
562    state: &AppState,
563    lan_discovery: &backend::lan::discovery::LanDiscoveryController,
564) {
565    // This host's other LAN channels stop listing this one as a sibling.
566    lan_discovery.withdraw_instance_record();
567    backend::instance_registry::withdraw();
568    crate::headless::withdraw_port_file();
569
570    // Shutdown cleanup: close every agent through the one teardown
571    // (SPEC_AGENT_TEARDOWN_SINGLE_PATH_2026_10_01.md, `Policy::app_exit()`),
572    // so each gets to end its turn and exit and nothing it started (`task dev`
573    // → task.exe/node, `Shell()` sessions) orphans on srv exit. Capped at
574    // `agent_teardown::APP_EXIT_CAP`; the launcher's backstop takes whatever
575    // is left. Beside it, the cloud presence goodbye (at most 2 s, so it
576    // never outlasts the teardown's own cap): devices show this computer as
577    // offline at once instead of minutes later.
578    let (closed, ()) = tokio::join!(
579        crate::sagas::agent_teardown::app_exit(state),
580        crate::muxbus::wan_presence::goodbye_on_shutdown(),
581    );
582    tracing::info!(agents = closed, "shutdown: agents closed");
583    // The helper container of Docker Desktop's gateway forwarder ends with this srv: its secret was made for this launch.
584    if let Some(cm) = state.container_manager.get().await {
585        let _ = tokio::time::timeout(std::time::Duration::from_secs(3), backend::container::gateway_fwd::remove(&cm)).await;
586    }
587    #[cfg(unix)]
588    backend::process_tracker::roots_file::finish();
589}
590
591/// Opens every store and starts the background subsystems that need no app state, then what
592/// is read from the data folder.
593pub fn open_stores_and_background(
594    config: &config::Config,
595    version: &str,
596    build_time: &str,
597) -> (Stores, BackgroundSubsystems) {
598    // 4. Initialize backend: data dir, in-process migrations, open every store,
599    //    attach shared/global registries, run one-time seed/repair passes.
600    let stores = crate::boot_timing::time("open_stores_and_migrate", || {
601        open_stores_and_migrate(config, version, build_time)
602    });
603
604    // Event infrastructure + every background task that doesn't need AppState yet.
605    let bg = spawn_background_subsystems(
606        &stores.mstore,
607        &stores.filestore,
608        &stores.id_store,
609        &stores.identity_store,
610        &stores.work_store,
611    );
612
613    start_data_home_services(config, &bg);
614    (stores, bg)
615}
616
617/// Serves the web and WebSocket listeners until one fails or `stdin_token` is cancelled.
618pub async fn serve_until_shutdown(
619    web_listener: TcpListener,
620    ws_listener: TcpListener,
621    router: axum::Router,
622    stdin_token: &tokio_util::sync::CancellationToken,
623) {
624    // Every request carries both ends of its connection (`ConnectInfo<Conn>`: the sign-in's confirm reads them) and the
625    // address it came from (`ConnectInfo<SocketAddr>`: the loopback-only routes read it), on either listener.
626    let router = crate::server::confirm_peer::with_plain_peer(router);
627    let web_server = axum::serve(web_listener, router.clone().into_make_service_with_connect_info::<crate::server::confirm_peer::Conn>());
628    let ws_server = axum::serve(ws_listener, router.into_make_service_with_connect_info::<crate::server::confirm_peer::Conn>());
629
630    // Run both servers until shutdown
631    tokio::select! {
632        result = web_server.into_future() => {
633            if let Err(e) = result {
634                tracing::error!("web server error: {}", e);
635            }
636        }
637        result = ws_server.into_future() => {
638            if let Err(e) = result {
639                tracing::error!("ws server error: {}", e);
640            }
641        }
642        _ = stdin_token.cancelled() => {
643            tracing::info!("shutdown signal received, exiting");
644        }
645    }
646}
647
648#[cfg(test)]
649#[path = "state_services_tests.rs"]
650mod tests;