Skip to main content

agentmux_srv/bootstrap/
background.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6use super::*;
7
8/// Output of [`spawn_background_subsystems`] — event/watcher infrastructure
9/// that needs no `AppState` and can start before it is built.
10pub struct BackgroundSubsystems {
11    pub event_bus: Arc<EventBus>,
12    pub broker: Arc<Broker>,
13    pub editor_file_watcher: Arc<backend::editor_file_watcher::EditorFileWatcher>,
14    pub media_file_watcher: Arc<backend::media_file_watcher::MediaFileWatcher>,
15    pub files_watcher: Arc<backend::files_watcher::FilesWatcher>,
16    pub fs_watch_pool: Arc<backend::fs_watch::FsWatchPool>,
17    pub config_watcher: Arc<wconfig::ConfigState>,
18    pub reactive_handler: &'static reactive::ReactiveHandler,
19    pub poller: Arc<Poller>,
20    pub messagebus: Arc<backend::messagebus::MessageBus>,
21    pub subagent_watcher: Arc<backend::subagent_watcher::SubagentWatcher>,
22    pub history_service: Arc<backend::history::HistoryService>,
23}
24
25/// Event infrastructure + all background task spawns that don't need
26/// `AppState` to exist yet: event bus/broker, editor file watcher, config
27/// watcher, sysinfo/watchdog/activity loops, the reactive handler + poller,
28/// the cloud push subscriber, messaging bridges (Discord/Telegram/Slack/
29/// WhatsApp), docsite dir, messagebus, subagent watcher, history service,
30/// and the session archiver.
31pub fn spawn_background_subsystems(
32    mstore: &Arc<Store>,
33    filestore: &Arc<FileStore>,
34    id_store: &Arc<Store>,
35    identity_store: &Arc<Store>,
36    work_store: &Arc<Store>,
37) -> BackgroundSubsystems {
38    install_build_slot();
39
40    // Event infrastructure
41    let event_bus = Arc::new(EventBus::new());
42    let broker = Arc::new(Broker::new());
43    backend::panic_watch::start_reporter(broker.clone());
44
45    // Bridge MPS events to WebSocket clients via EventBus
46    let bridge = backend::eventbus::EventBusBridge::new(event_bus.clone());
47    broker.set_client(Box::new(bridge));
48    // Remote connections' status changes, from wherever a connection is used.
49    backend::remote::link::init(broker.clone());
50    // The History pane's agent list: one event while transcripts change (`history_changed.rs`).
51    backend::history_changed::spawn_publisher(broker.clone());
52
53    // Shared filesystem-watcher framework — constructed once, before any
54    // consumer, all three of which now build on it (see
55    // SPEC_SHARED_FS_WATCHER_FRAMEWORK_2026_08_07.md §5's migration order:
56    // config_watcher_fs first, editor+media here, native memory as a future
57    // consumer).
58    let fs_watch_pool = backend::fs_watch::FsWatchPool::new();
59
60    // Watches files open in editor/preview panes, publishing a per-block
61    // wake signal on external changes. See SPEC_EDITOR_LIVE_FILE_RELOAD_2026_07_18.md.
62    let editor_file_watcher = backend::editor_file_watcher::EditorFileWatcher::new(fs_watch_pool.clone(), broker.clone());
63
64    // Watches directories a Media pane is pointed at, publishing a per-block
65    // wake signal when a matching-extension file changes. See
66    // SPEC_MEDIA_PANE_2026_07_26.md.
67    let media_file_watcher = backend::media_file_watcher::MediaFileWatcher::new(fs_watch_pool.clone(), broker.clone());
68
69    // Watches folders open in Files panes (`fs.watch`), publishing a
70    // per-block "re-list this folder" signal. See
71    // SPEC_FILE_BROWSER_PANE_2026_10_01.md §6.3.
72    let files_watcher = backend::files_watcher::FilesWatcher::new(fs_watch_pool.clone(), broker.clone());
73
74    deploy_shell_integration();
75
76    let config_watcher = start_config_watchers(&fs_watch_pool, &event_bus, &broker);
77    move_voice_key_into_vault(identity_store);
78
79    spawn_sampling_loops(mstore, filestore, work_store, &event_bus, &broker, &config_watcher);
80
81    let (reactive_handler, poller) = set_up_reactive_handler(mstore);
82
83    start_cloud_services(mstore, id_store, &event_bus, &broker, &config_watcher);
84
85    super::messaging_bridges::start_messaging_bridges(&config_watcher);
86
87    // Set up docsite directory
88    if let Some(app_path) = base::get_mux_app_path() {
89        let docsite_dir = app_path.join("docsite");
90        docsite::set_docsite_dir(docsite_dir);
91    }
92
93    // Local MessageBus for inter-agent communication
94    let messagebus = Arc::new(backend::messagebus::MessageBus::new());
95
96    let subagent_watcher = start_subagent_watcher(mstore, id_store, identity_store, &broker, &event_bus);
97
98    // History service — discovers and indexes past CLI agent conversations
99    let history_service = Arc::new(backend::history::HistoryService::new());
100    history_service.warm_in_background();
101
102    warm_agent_clis(mstore);
103
104    start_session_archiver(mstore, filestore);
105
106    start_provider_session_sweep(mstore, &config_watcher);
107    start_provider_session_report(&config_watcher);
108    start_history_compact_migration(&config_watcher, mstore, filestore);
109
110    BackgroundSubsystems {
111        event_bus,
112        broker,
113        editor_file_watcher,
114        media_file_watcher,
115        files_watcher,
116        fs_watch_pool,
117        config_watcher,
118        reactive_handler,
119        poller,
120        messagebus,
121        subagent_watcher,
122        history_service,
123    }
124}
125
126
127/// Agents' cargo waits for the host-wide build slot (build_slot.rs).
128fn install_build_slot() {
129    std::thread::spawn(|| match agentmux_common::build_slot::install_for_current_user() {
130        Ok(done) if !done.foreign.is_empty() => tracing::warn!(files = ?done.foreign, "build slot: left a cargo that is not ours in place"),
131        Ok(done) if !done.written.is_empty() => tracing::info!(files = ?done.written, "build slot installed"),
132        Ok(_) => {}
133        Err(e) => tracing::warn!(error = %e, "build slot: not installed"),
134    });
135    // A holder that has used no CPU for 10 minutes is shown as idle and its agent told once.
136    backend::build_slot_idle::install();
137}
138
139/// Deploys the shell integration scripts at startup, whichever pane is opened first.
140fn deploy_shell_integration() {
141    // Deploy shell integration scripts (muxlog.mjs/muxspect.mjs + rcfiles)
142    // unconditionally at startup, not opportunistically from a specific
143    // controller's spawn path. Previously the only call site was
144    // `ShellController::start`'s interactive (empty-command) branch
145    // (`blockcontroller/shell/lifecycle.rs`) — a user whose first-ever pane
146    // in a fresh data dir is an Agent pane (persistent/subprocess/acp, which
147    // never hits that branch) would never get the scripts deployed at all,
148    // so even muxspect's own documented `node ~/.agentmux/shell/muxspect.mjs`
149    // direct-path fallback would ENOENT (codex P1 on PR #2380 — a latent gap
150    // in muxlog's identical deployment mechanism that PR newly depends on).
151    // `deploy_scripts` is idempotent (skips if its version marker already
152    // matches), so calling it here in addition to the existing call site is
153    // safe, not a double-write race.
154    // Two roots, deliberately:
155    //   * the per-instance root the shells actually source (isolation, I6), and
156    //   * the stable `~/.agentmux/shell` path docs/MUXSPECT.md and docs/MUXSH.md
157    //     tell users to invoke directly, which must stay predictable.
158    let base = backend::shellintegration::integration_base();
159    backend::shellintegration::deploy_scripts(&base);
160    backend::shellintegration_prune::stamp_instance(&base, &backend::base::get_mux_data_dir());
161    backend::shellintegration::deploy_scripts(&backend::shellintegration::documented_shell_root());
162    prune_stale_shell_integration(base);
163}
164
165/// Removes the `~/.agentmux/shell/<hash>` folders of instances whose data dir is gone. In the
166/// background: it reads every instance's folder listing. See `shellintegration_prune`.
167fn prune_stale_shell_integration(current_base: std::path::PathBuf) {
168    std::thread::spawn(move || {
169        let home = backend::base::get_home_dir().join(".agentmux");
170        let live = backend::shellintegration_prune::live_instance_data_dirs(&home);
171        let report = backend::shellintegration_prune::prune_stale_integration_dirs(&home.join("shell"), &current_base, &live);
172        if report != backend::shellintegration_prune::PruneReport::default() {
173            tracing::info!(
174                removed = report.removed,
175                stamped = report.stamped,
176                unattributed = report.unattributed,
177                "shell integration folders of instances that are gone"
178            );
179        }
180    });
181}
182
183/// A Groq key left in settings.json as plain text goes into the Vault, and the setting becomes a `vault:<id>`
184/// reference (#47636). Decided from the value alone each start, so it runs once in practice and never leaves a
185/// marker. In the background: the Vault's seal key may need the OS keychain.
186fn move_voice_key_into_vault(identity_store: &Arc<Store>) {
187    let store = identity_store.clone();
188    std::thread::spawn(move || {
189        let path = backend::config_watcher_fs::resolve_settings_dir().join("settings.json");
190        let current = std::fs::read_to_string(path)
191            .ok()
192            .and_then(|text| agentmux_common::settings_jsonc::parse_jsonc(&text))
193            .and_then(|v| v.get("voice:groqApiKey").and_then(|k| k.as_str()).map(str::to_string));
194        match backend::vault::setting_key::move_setting(&store, "voice:groqApiKey", "Groq key (voice input)", current.as_deref(), backend::config_watcher_fs::merge_settings_to_disk) {
195            Ok(Some(_)) => {
196                // The last-good copy of the file held the plain key too: refreshed now, not at the next reload.
197                backend::config_watcher_fs::refresh_last_good();
198                tracing::info!("the Groq key in settings.json was moved into the Vault");
199            }
200            Ok(None) => {}
201            Err(e) => tracing::warn!(error = %e, "the Groq key in settings.json could not be moved into the Vault; it stays where it is"),
202        }
203    });
204}
205
206/// Creates the config state and starts the watchers for settings, widgets and the start page.
207fn start_config_watchers(
208    fs_watch_pool: &Arc<backend::fs_watch::FsWatchPool>,
209    event_bus: &Arc<EventBus>,
210    broker: &Arc<Broker>,
211) -> Arc<wconfig::ConfigState> {
212    // Config watcher (created before sysinfo loop so it can read telemetry:interval)
213    let config_watcher = Arc::new(wconfig::ConfigState::with_config(wconfig::build_default_config()));
214
215    // Load user's settings.json from disk (merges with defaults)
216    backend::config_watcher_fs::load_settings_from_disk(&config_watcher);
217
218    // Watch settings.json for changes and broadcast to WebSocket clients
219    backend::config_watcher_fs::spawn_settings_watcher(
220        fs_watch_pool.clone(),
221        config_watcher.clone(),
222        event_bus.clone(),
223    );
224
225    // The user's own widgets.json beside settings.json, merged over the
226    // built-in widgets (Pane Tab contract Phase 6: where an `ext:` widget is
227    // added). Same load-then-watch shape, same pool.
228    backend::user_widgets::load_user_widgets_from_disk(&config_watcher);
229    backend::user_widgets::spawn_user_widgets_watcher(
230        fs_watch_pool.clone(),
231        config_watcher.clone(),
232        event_bus.clone(),
233        broker.clone(),
234    );
235
236    // Browser pane start page — same load-then-watch shape as settings.json
237    // above, on the SAME fs_watch_pool instance, so it rides the existing
238    // GetFullConfig/live-broadcast pipeline instead of a parallel one. See
239    // docs/specs/SPEC_BROWSER_PANE_START_PAGE_2026_09_16.md §3.2.
240    backend::browser_start_page::load_start_page_from_disk(&config_watcher);
241    backend::browser_start_page::spawn_start_page_watcher(
242        fs_watch_pool.clone(),
243        config_watcher.clone(),
244        event_bus.clone(),
245    );
246    config_watcher
247}
248
249/// Starts the sampling and watching loops that need no app state.
250fn spawn_sampling_loops(
251    mstore: &Arc<Store>,
252    filestore: &Arc<FileStore>,
253    work_store: &Arc<Store>,
254    event_bus: &Arc<EventBus>,
255    broker: &Arc<Broker>,
256    config_watcher: &Arc<wconfig::ConfigState>,
257) {
258    // Say in the log when the runtime stops running tasks, and for how long.
259    backend::stall_watch::start();
260
261    // Start sysinfo collection loop (interval configurable via telemetry:interval)
262    let sysinfo_broker = broker.clone();
263    let sysinfo_config = config_watcher.clone();
264    let label_store = Arc::clone(mstore);
265    let pane_sampler = backend::sampler::panes::tower_sampler(move |id| {
266        backend::tower::sampler::block_label(&label_store, id)
267    });
268    // On its own thread, not a task: the tick must not wait for the runtime it measures.
269    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
270    if let Err(e) = backend::sampler::thread::spawn(sysinfo_broker, sysinfo_config, "local".to_string(), pane_sampler, stop) {
271        tracing::error!(error = %e, "sysinfo: the sampler thread did not start; no CPU, memory or network samples");
272    }
273
274    // Start agent process watchdog (kills panes that exceed max-runtime or idle-output limits)
275    let watchdog_config = config_watcher.clone();
276    let watchdog_store = Arc::clone(mstore);
277    // The work queue's store (`AppState::work_store`): a stopped agent's claims are released there.
278    let watchdog_work_store = Arc::clone(work_store);
279    let watchdog_broker = broker.clone();
280    tokio::spawn(async move {
281        backend::blockcontroller::watchdog::run_watchdog_loop(watchdog_config, watchdog_store, watchdog_work_store, watchdog_broker).await;
282    });
283
284    // Recover a missing session title for a running agent (the Swarm row and
285    // pane header read it); see activity_watcher.rs —
286    // reads reactive::get_global_handler() as its registry, so it needs no
287    // AppState and can start before AppState is built (matches sysinfo/watchdog above).
288    let activity_mstore = Arc::clone(mstore);
289    let activity_filestore = Arc::clone(filestore);
290    let activity_event_bus = event_bus.clone();
291    // Every ambient call's spend goes to the status bar's totals (ambient/spend.rs).
292    crate::ambient::spend::publish_on(event_bus.clone());
293    tokio::spawn(async move {
294        backend::reactive::activity_watcher::run_agent_summary_loop(
295            activity_mstore, activity_filestore, activity_event_bus,
296        ).await;
297    });
298
299    // The Swarm Supervisor: judges supervised agents' turns as they end and
300    // keeps them going (backend/supervisor). Watches the broker's turn ledger,
301    // so it needs no AppState either.
302    backend::supervisor::watcher::start(
303        Arc::clone(mstore),
304        Arc::clone(filestore),
305        event_bus.clone(),
306        broker.clone(),
307    );
308
309    // Push each agent's todo checklist + in-flight tool (swarm rows under the
310    // agent name). Separate loop from the summary above deliberately: this one
311    // is a tail-read + JSON parse with no model call, so it sweeps every 3s
312    // instead of 20s — a checklist that lags is worse than none. Same
313    // registry, same no-AppState property.
314    let progress_filestore = Arc::clone(filestore);
315    let progress_mstore = Arc::clone(mstore);
316    let progress_broker = broker.clone();
317    tokio::spawn(async move {
318        backend::reactive::progress_watcher::run_agent_progress_loop(
319            progress_filestore, progress_mstore, progress_broker,
320        ).await;
321    });
322
323    // Keep each agent's repository, branch and uncommitted files fresh for
324    // WhoIsWorkingOn and ListConversations (backend/work_facts/git.rs): git
325    // runs here, never on a request.
326    // The folders a container agent can write are read from this store. Named here, before anything that asks
327    // about a folder can run (the loop below names it too, once its task starts).
328    backend::fs_ops::container_folders::install(mstore);
329    let work_facts_mstore = Arc::clone(mstore);
330    tokio::spawn(async move {
331        backend::work_facts::git::run_git_refresh_loop(work_facts_mstore).await;
332    });
333
334    // The AWS grants file for container agents: a change to it is compared with the record and recorded when it is
335    // made, not only when the next container asks (identity::aws_broker::record).
336    tokio::spawn(async move {
337        let mut tick = tokio::time::interval(std::time::Duration::from_secs(15));
338        loop {
339            tick.tick().await;
340            let _ = tokio::task::spawn_blocking(crate::identity::aws_broker::policy::current).await;
341        }
342    });
343}
344
345/// Wires the global reactive handler to the controllers and creates its poller.
346fn set_up_reactive_handler(mstore: &Arc<Store>) -> (&'static reactive::ReactiveHandler, Arc<Poller>) {
347    // Reactive handler (global singleton) + poller
348    // Before the handler records anything: every jekt audit entry is also kept in a file.
349    backend::reactive::audit_store::install_for_this_srv();
350    let reactive_handler = reactive::get_global_handler();
351    reactive_handler.set_input_sender(Arc::new(|block_id: &str, data: &[u8]| {
352        backend::blockcontroller::send_input(
353            block_id,
354            backend::blockcontroller::BlockInputUnion::data(data.to_vec()),
355            None,
356        )
357    }));
358    // Controller-aware delivery (SPEC_AGENT_CONTROL_PROTOCOL §6 / Phase 3): persistent
359    // stream-json and ACP agents have no PTY, so muxbus Tier-1 keystroke injection
360    // silently misses them. Route those through their structured channel (live stdin /
361    // session/prompt) — which also steers the agent mid-turn — and fall back to PTY
362    // keystrokes only for terminal-based agents.
363    reactive_handler.set_message_sender(Arc::new(|block_id: &str, message: &str, inline: &[serde_json::Value], from: &backend::message_origin::MessageOrigin, expires_at_ms: Option<i64>| {
364        match backend::blockcontroller::deliver_agent_message_from(block_id, message, None, from.clone(), inline, expires_at_ms) {
365            Ok(backend::blockcontroller::AgentDelivery::Structured) => Ok(reactive::SenderDelivery::Delivered),
366            Ok(backend::blockcontroller::AgentDelivery::StructuredDeferred) => Ok(reactive::SenderDelivery::Deferred),
367            Ok(backend::blockcontroller::AgentDelivery::Pty) => Ok(reactive::SenderDelivery::Pty),
368            Err(e) => Err(e),
369        }
370    }));
371    // Recipient-identity check (issue #2695): before delivering, compare the
372    // resolved target's own live, spawn-time-captured identity (queried from
373    // the actual controller, independent of reactive_handler's own
374    // name/UID-to-block maps) against who the jekt was addressed to. See
375    // Controller::agent_id's doc comment for why this can't be derived from
376    // reactive_handler's own state.
377    reactive_handler.set_agent_identity_confirmer(Arc::new(|block_id: &str| {
378        backend::blockcontroller::get_controller(block_id).and_then(|c| c.agent_id())
379    }));
380    // Stable counterpart to the above (`AGENTMUX_AGENT_ID`, frozen at spawn)
381    // — see `Controller::stable_agent_id`'s and `NameBindings::stable`'s
382    // doc comments for why a jekt tagged with the stable ID needs its own,
383    // independently-sourced confirmer instead of reusing the live one.
384    reactive_handler.set_stable_agent_identity_confirmer(Arc::new(|block_id: &str| {
385        backend::blockcontroller::get_controller(block_id).and_then(|c| c.stable_agent_id())
386    }));
387    // Identity M2: the UID confirmer, consulted only for targets that
388    // resolved by UID — see `Handler::uid_identity_confirmer` for why it is
389    // a separate check and why `None` must mean "unverifiable".
390    reactive_handler.set_uid_identity_confirmer(Arc::new(|block_id: &str| {
391        backend::blockcontroller::get_controller(block_id).and_then(|c| c.stable_agent_uid())
392    }));
393    // Identity M2: liveness — the garbage collector that replaces
394    // eviction-by-name (spec §4.4.4 Q9). A block with no controller is dead
395    // and is swept when a name it held is resolved.
396    reactive_handler.set_block_liveness(Arc::new(|block_id: &str| {
397        backend::blockcontroller::get_controller(block_id).is_some()
398    }));
399    // A slug or display name an agent was renamed from still reaches it, once
400    // no live name or current one has (SPEC_FORK_SLUG_MIGRATION_2026_10_22.md
401    // Phase 1; `former_names` for display names).
402    let former_slug_store = Arc::clone(mstore);
403    reactive_handler.set_former_slug_resolver(Arc::new(move |name: &str| {
404        former_slug_store.former_name_owner(name).ok().flatten().map(|owner| owner.uid)
405    }));
406    // And the route form of an agent's current display name ("Naki-2" for
407    // "Naki #2"), which only a pane that had a typed turn is registered
408    // under: delivery only, before former names (#1459).
409    let display_route_store = Arc::clone(mstore);
410    reactive_handler.set_display_route_resolver(Arc::new(move |name: &str| {
411        display_route_store.display_route_owner(name).ok().flatten().map(|owner| owner.uid)
412    }));
413    let poller = Arc::new(Poller::new(
414        PollerConfig {
415            muxbus_url: None,
416            muxbus_token: None,
417            poll_interval_secs: reactive::DEFAULT_POLL_INTERVAL_SECS,
418        },
419        reactive_handler,
420    ));
421    (reactive_handler, poller)
422}
423
424/// Starts cloud delivery and the services that follow the account.
425fn start_cloud_services(
426    mstore: &Arc<Store>,
427    id_store: &Arc<Store>,
428    event_bus: &Arc<EventBus>,
429    broker: &Arc<Broker>,
430    config_watcher: &Arc<wconfig::ConfigState>,
431) {
432    // Cloud delivery's state for the UI, the sign-in notification and the
433    // agents' pause/resume notes. Reads nothing from the keychain itself.
434    crate::muxbus::delivery_status::install(event_bus.clone(), broker.clone());
435    // Each service's reachability for the status bar, and its probes.
436    crate::connectivity::install(event_bus.clone());
437    // Cloud push subscriber — single WS connection per sidecar that the cloud
438    // uses to push reactive injections instead of polling. The WS connection
439    // itself is a no-op until the user connects via muxbus.login, but
440    // `init_global` registers the muxbus credential with the broker
441    // scheduler unconditionally, which calls `Store::muxbus_is_fresh()` —
442    // a real, synchronous OS-keychain read — almost immediately. That read
443    // is the automatic (non-user-triggered) keychain touch
444    // docs/retro/retro-macos-muxbus-keychain-prompt-storm-2026-08-19.md
445    // investigates; skipping `init_global` entirely is not a no-op the way
446    // the comment above might suggest.
447    //
448    // `AGENTMUX_DISABLE_CLOUD_SUBSCRIBER` exists so `crates/srv/tests/
449    // integration_test.rs` can spawn the real binary without that read
450    // firing. Those tests spawn an ad-hoc/dev-signed `target/debug`
451    // binary, which is never on the Keychain ACL's trusted-signature list
452    // (only specific notarized, Developer-ID-signed installs are) — so
453    // every spawned test process gets its own interactive consent prompt
454    // for the SAME real credential, on whatever macOS account happens to
455    // be running the test. Confirmed live: a `cargo test -p agentmux-srv`
456    // run produced 4 near-simultaneous prompts, one per spawned subprocess,
457    // on a shared dev machine. Off by default — the shipped app and `task
458    // dev` must keep muxbus reconnect-on-launch working exactly as before.
459    //
460    // `isolated_muxbus_reconnect_enabled()` closes a second, broader gap
461    // the env-var flag above doesn't (see
462    // docs/retro/retro-macos-0560-stale-cef-cache-launch-crash-2026-09-16.md):
463    // every local `task package`/`task package:macos`/`task package:linux`
464    // build bakes a brand-new, randomized per-build channel (and, on
465    // macOS, a bundle identifier derived from it) into the binary, so it
466    // is a never-before-seen code signature to the Keychain every single
467    // time — the SAME already-`Always Allow`'d muxbus credential prompts
468    // again on every fresh local build, indefinitely. Only on macOS: Windows
469    // and Linux read the stored sign-in without a prompt, so there a local
470    // channel reconnects at launch like any other. Unlike
471    // `isolated_auth_enabled`/`isolated_settings_enabled` (which also
472    // isolate `task dev`'s `dev-<branch>` channel), this flag deliberately
473    // exempts `dev-*` — see its own doc comment for why a per-branch-stable
474    // dev channel doesn't have the per-build-random-identity problem this
475    // one exists to solve. Skipping this eager call is also NOT permanent
476    // for the process's lifetime on an isolated channel: `muxbus.login`
477    // lazily initializes the subscriber the moment the user explicitly
478    // logs in (see `muxbus_handlers.rs`), and `muxbus.status` gates on
479    // subscriber presence rather than re-deriving this same channel check,
480    // so it starts working immediately after that login with no restart
481    // required.
482    let muxbus_reason = agentmux_common::isolated_muxbus_reconnect_reason();
483    // A SQL read of this channel's own row: it never touches the keychain.
484    let own_sign_in = id_store.muxbus_has_own_sign_in();
485    if cloud_subscriber_disabled_from_env() {
486        tracing::info!("cloud_subscriber: init_global skipped (AGENTMUX_DISABLE_CLOUD_SUBSCRIBER)");
487    } else if skip_cloud_subscriber(muxbus_reason, own_sign_in) {
488        tracing::info!(
489            reason = muxbus_reason.as_str(),
490            "cloud_subscriber: init_global skipped (ISOLATED — channel-scoped, no automatic MuxBus reconnect)"
491        );
492    } else {
493        if muxbus_reason.is_isolated() {
494            tracing::info!("cloud_subscriber: reconnecting this channel's own MuxBus sign-in");
495        }
496        crate::muxbus::cloud_subscriber::CloudSubscriber::init_global(id_store.clone());
497    }
498    // W3-S D1b: publish each agent's instance-certified WAN key to the
499    // account's cloud directory. Not gated on the subscriber: a logged-out
500    // or isolated channel simply finds no token and publishes nothing.
501    crate::muxbus::wan_publish::spawn(mstore.clone(), id_store.clone());
502    // Whether a newer release exists: checked and staged in the background, and when asked
503    // (SPEC_BACKGROUND_UPDATES_ONE_CLICK_RESTART).
504    crate::backend::update::init(event_bus.clone(), config_watcher.clone(), crate::headless::active());
505    // Whether this start is an upgrade, for the note resumed agents get.
506    crate::backend::upgrade_notice::init(mstore.clone());
507    // What the last quit stopped of the agents' background work, to tell them.
508    crate::backend::background_work::init();
509}
510
511/// Starts the watcher for subagents spawned by Claude Code sessions.
512fn start_subagent_watcher(
513    mstore: &Arc<Store>,
514    id_store: &Arc<Store>,
515    identity_store: &Arc<Store>,
516    broker: &Arc<Broker>,
517    event_bus: &Arc<EventBus>,
518) -> Arc<backend::subagent_watcher::SubagentWatcher> {
519    // Subagent watcher — monitors Claude Code session dirs for spawned subagents
520    let subagent_watcher = backend::subagent_watcher::SubagentWatcher::spawn(
521        event_bus.clone(),
522        mstore.clone(),
523        id_store.clone(),
524        identity_store.clone(),
525    );
526    // Wires `subagent:backfill_status` (scoped, persisted MPS event) — see
527    // `SubagentWatcher`'s `broker` field doc comment for why this is a
528    // post-construction setter rather than a constructor parameter.
529    subagent_watcher.set_broker(broker.clone());
530    // Registered as a global so blockcontroller/persistent/stdout_reader.rs's turn-end
531    // reconciliation hook (SPEC_SUBAGENT_LIVE_RECONCILIATION_AND_RETIRE_
532    // 2026_07_20 Phase A) can reach it without threading an Arc through
533    // PersistentSubprocessController::new and every one of its callers.
534    backend::subagent_watcher::set_global(subagent_watcher.clone());
535    subagent_watcher
536}
537
538/// Installs the pinned CLI of every provider the user's agents use, in the background.
539fn warm_agent_clis(mstore: &Arc<Store>) {
540    // Install the pinned CLI of every provider the user's own agents use, in
541    // the background, so the first open after a pin bump doesn't wait on npm
542    // (SPEC_AGENT_OPEN_LATENCY_2026_09_27.md §4.1). Templates don't count:
543    // they span every provider. AGENTMUX_NO_CLI_WARM=1 turns it off.
544    if std::env::var("AGENTMUX_NO_CLI_WARM").map_or(true, |v| v != "1") {
545        match (
546            agentmux_common::DataPaths::from_env(),
547            mstore.agent_def_list(),
548        ) {
549            (Some(paths), Ok(defs)) => {
550                let providers: Vec<String> = defs
551                    .into_iter()
552                    .filter(|d| d.is_seeded != 1)
553                    .map(|d| d.provider)
554                    .collect();
555                backend::cli_install::warm_used_providers(paths, providers);
556            }
557            (_, Err(e)) => {
558                tracing::warn!(error = %e, "cli warm-up: cannot list agent definitions; skipped")
559            }
560            (None, _) => tracing::warn!("cli warm-up: no data paths; skipped"),
561        }
562    }
563}
564
565/// Ends the provider sessions an agent has left or let go idle: proves the history holds what their files hold, then
566/// removes the files by session id. It reads the switch and the idle limit each time and does nothing while the
567/// switch is off (`history:sessionfilesweep`, off until the history migration turns it on).
568fn start_provider_session_sweep(mstore: &Arc<Store>, config: &Arc<wconfig::ConfigState>) {
569    let (mstore, config) = (Arc::clone(mstore), Arc::clone(config));
570    let flag = Arc::clone(&config);
571    tokio::spawn(run_flagged_sweeps(move || backend::provider_sessions::Policy::from_extra(&flag.get_settings().extra).enabled, move || {
572        let (mstore, config) = (Arc::clone(&mstore), Arc::clone(&config));
573        async move {
574            let policy = backend::provider_sessions::Policy::from_extra(&config.get_settings().extra);
575            if !policy.enabled {
576                return;
577            }
578            let registry = mstore.shared_agent_registry();
579            let swept = tokio::task::spawn_blocking(move || {
580                backend::provider_sessions::sweep_global(&backend::provider_sessions::Roots::from_env(), &policy, agentmux_common::time::now_ms(), registry)
581            })
582            .await;
583            match swept {
584                Ok(Some(report)) => tracing::info!(?report, "provider session sweep complete"),
585                Ok(None) => tracing::debug!("provider session sweep skipped: no global transcript store or no lease store"),
586                Err(e) => tracing::warn!(error = %e, "provider session sweep failed"),
587            }
588        }
589    }));
590}
591
592/// The report-only pass over the provider session files no segment log names (`history:sessionfilereport`, off
593/// unless set): the sweep's own owner test and proof, a table of sessions beside the store and one totals line in the
594/// log. It removes, imports and locks nothing, and does nothing while the setting is off.
595fn start_provider_session_report(config: &Arc<wconfig::ConfigState>) {
596    let config = Arc::clone(config);
597    let flag = Arc::clone(&config);
598    tokio::spawn(run_flagged_sweeps(move || backend::provider_sessions::report_enabled(&flag.get_settings().extra), move || {
599        let config = Arc::clone(&config);
600        async move {
601            let extra = config.get_settings().extra.clone();
602            if !backend::provider_sessions::report_enabled(&extra) {
603                return;
604            }
605            let idle_days = backend::provider_sessions::Policy::from_extra(&extra).idle_days;
606            let done = tokio::task::spawn_blocking(move || {
607                backend::provider_sessions::report_global(&backend::provider_sessions::Roots::from_env(), idle_days, agentmux_common::time::now_ms())
608            })
609            .await;
610            match done {
611                Ok(Some(Ok(totals))) => tracing::info!(
612                    sessions = totals.sessions,
613                    bytes = totals.bytes,
614                    removable_bytes = totals.removable_bytes(),
615                    by_why = ?totals.by_why,
616                    "provider session report complete"
617                ),
618                Ok(Some(Err(why))) => tracing::warn!(why, "provider session report skipped"),
619                Ok(None) => tracing::debug!("provider session report skipped: no global transcript store"),
620                Err(e) => tracing::warn!(error = %e, "provider session report failed"),
621            }
622        }
623    }));
624}
625
626/// The reduce pass of the compact-form upgrade (spec section 9): a minute after start, then hourly, and at once
627/// (within a minute) when `history:compactmigrate` or its dry run is turned on. Each zone is rewritten beside its old file and
628/// swapped in one transaction; a zone that fails a check is left as it was.
629fn start_history_compact_migration(config: &Arc<wconfig::ConfigState>, mstore: &Arc<Store>, filestore: &Arc<FileStore>) {
630    let config = Arc::clone(config);
631    let (mstore, filestore) = (Arc::clone(mstore), Arc::clone(filestore));
632    let flag = Arc::clone(&config);
633    tokio::spawn(run_flagged_sweeps(move || backend::transcript::migrate_run::Policy::from_extra(&flag.get_settings().extra).enabled, move || {
634        let config = Arc::clone(&config);
635        let (mstore, filestore) = (Arc::clone(&mstore), Arc::clone(&filestore));
636        async move {
637            let policy = backend::transcript::migrate_run::Policy::from_extra(&config.get_settings().extra);
638            if !policy.enabled {
639                return;
640            }
641            // The pass stops between windows when the setting is turned off while it runs. (A quit ends
642            // the process; a swap is one transaction, so a pass cut off there leaves the old file.)
643            let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
644            let watcher = {
645                let (config, stop) = (Arc::clone(&config), Arc::clone(&stop));
646                tokio::spawn(async move {
647                    loop {
648                        tokio::time::sleep(std::time::Duration::from_secs(15)).await;
649                        if !backend::transcript::migrate_run::Policy::from_extra(&config.get_settings().extra).enabled {
650                            stop.store(true, std::sync::atomic::Ordering::Relaxed);
651                            return;
652                        }
653                    }
654                })
655            };
656            let ran = tokio::task::spawn_blocking(move || {
657                use backend::transcript::migrate_run::{pass_copies, pass_global};
658                let reduced = pass_global(&policy, &stop);
659                // Then the per-channel copies, each checked against the store the pass just reduced.
660                (reduced, pass_copies(&policy, &stop, &filestore, &mstore))
661            })
662            .await;
663            watcher.abort();
664            match ran {
665                Ok((Some(summary), copies)) => {
666                    tracing::info!(?summary, "history compact migration pass complete");
667                    if let Some(copies) = copies {
668                        tracing::info!(?copies, "history per-channel copies pass complete");
669                    }
670                }
671                Ok((None, _)) => tracing::debug!("history compact migration skipped: no global transcript store"),
672                Err(e) => tracing::warn!(error = %e, "history compact migration pass failed"),
673            }
674        }
675    }));
676}
677
678/// Starts the sweeps that archive sessions inactive for a week.
679fn start_session_archiver(mstore: &Arc<Store>, filestore: &Arc<FileStore>) {
680    // Session archiver — auto-archive sessions inactive for >7 days. Archives are kept forever.
681    // Skip if home directory can't be determined (would otherwise fall back to a
682    // relative path and create archives under the current working directory).
683    if let Some(archive_dir) = backend::session_archive::default_archive_dir() {
684        let archiver = Arc::new(backend::session_archive::SessionArchiver::new(
685            mstore.clone(),
686            filestore.clone(),
687            7,                              // inactive days
688            archive_dir,
689        ));
690        tokio::spawn(run_archive_sweeps(move || {
691            let archiver = Arc::clone(&archiver);
692            async move {
693                match archiver.sweep().await {
694                    Ok(stats) => tracing::info!(?stats, "session archiver sweep complete"),
695                    Err(e) => tracing::warn!(error = %e, "session archiver sweep failed"),
696                }
697            }
698        }));
699    } else {
700        tracing::warn!("session archiver: home dir unavailable, archiver disabled");
701    }
702}
703
704
705/// Should `CloudSubscriber::init_global` be skipped this run?
706///
707/// Presence-based, matching the `AGENTMUX_DEV`/`AGENTMUX_TRAY` idiom
708/// elsewhere in this codebase. See the call site's doc comment for why
709/// skipping this matters: `init_global` triggers a real, synchronous
710/// OS-keychain read almost immediately, which macOS gates behind an
711/// interactive consent prompt for any process whose code signature isn't
712/// on the target credential's trusted-signer ACL — exactly the case for an
713/// ad-hoc/dev-signed `target/debug` binary spawned by an integration test.
714fn cloud_subscriber_disabled_from_env() -> bool {
715    std::env::var("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER").is_ok()
716}
717
718/// Should the boot-time MuxBus reconnect be skipped on this channel?
719///
720/// The macOS default isolation (`ChannelDefaultIsolated`) exists so a never-before-seen local
721/// build doesn't read a keychain entry that prompts for its signature. A channel signs in to
722/// MuxBus on its own (`muxbus:channel:<ch>`, never the host-wide set), so a channel with no
723/// sign-in of its own has nothing to read and stays skipped; one that has its own reconnects, as
724/// on Windows and Linux. Otherwise an in-app upgrade (the same channel, a new version) came back
725/// signed out on every version (starpower, 0.60.6). An explicit `AGENTMUX_ISOLATED_MUXBUS=1`
726/// still skips.
727fn skip_cloud_subscriber(reason: agentmux_common::IsolatedMuxbusReconnectReason, own_sign_in: bool) -> bool {
728    use agentmux_common::IsolatedMuxbusReconnectReason as Reason;
729    match reason {
730        Reason::ExplicitOptIn => true,
731        Reason::ChannelDefaultIsolated => !own_sign_in,
732        Reason::ExplicitOptOut | Reason::LocalChannelNoPrompt | Reason::ChannelDefaultGlobal => false,
733    }
734}
735
736/// The session archiver sweeps a minute after srv starts, then hourly. Waiting
737/// the full hour first meant an srv restarted more often than hourly never
738/// archived anything.
739const ARCHIVE_FIRST_SWEEP: std::time::Duration = std::time::Duration::from_secs(60);
740const ARCHIVE_SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(3600);
741
742/// How often a flagged pass looks at its flag.
743const FLAG_LOOK_EVERY: std::time::Duration = std::time::Duration::from_secs(60);
744
745/// Run `sweep` on the archiver's schedule (a minute after start, then hourly) while `flag_on` says it is on, and also as soon
746/// as the flag is turned on: it is looked at every minute (the settings are in memory), and a flag that has gone from off to
747/// on since the last look runs the pass then, and the hourly wait starts again from it. A pass whose flag is off is not run;
748/// one whose flag stays on is not run twice inside the hour. A pass that is running is not interrupted by a look. Never returns.
749async fn run_flagged_sweeps<F, Fut>(flag_on: impl Fn() -> bool, mut sweep: F)
750where
751    F: FnMut() -> Fut,
752    Fut: std::future::Future<Output = ()>,
753{
754    let mut looks = tokio::time::interval_at(tokio::time::Instant::now() + ARCHIVE_FIRST_SWEEP, FLAG_LOOK_EVERY);
755    looks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
756    let mut was_on = flag_on();
757    let mut next_sweep = tokio::time::Instant::now() + ARCHIVE_FIRST_SWEEP;
758    loop {
759        looks.tick().await;
760        let on = flag_on();
761        let turned_on = on && !was_on;
762        was_on = on;
763        if on && (turned_on || tokio::time::Instant::now() >= next_sweep) {
764            sweep().await;
765            next_sweep = tokio::time::Instant::now() + ARCHIVE_SWEEP_EVERY;
766        } else if tokio::time::Instant::now() >= next_sweep {
767            // Due while the flag is off: nothing to run, and the next try is an hour on (or the moment the flag is turned on).
768            next_sweep = tokio::time::Instant::now() + ARCHIVE_SWEEP_EVERY;
769        }
770    }
771}
772
773/// Run `sweep` on the session archiver's schedule. Never returns.
774async fn run_archive_sweeps<F, Fut>(mut sweep: F)
775where
776    F: FnMut() -> Fut,
777    Fut: std::future::Future<Output = ()>,
778{
779    tokio::time::sleep(ARCHIVE_FIRST_SWEEP).await;
780    loop {
781        sweep().await;
782        tokio::time::sleep(ARCHIVE_SWEEP_EVERY).await;
783    }
784}
785
786#[cfg(test)]
787mod archive_schedule_tests {
788    use super::*;
789    use std::sync::atomic::{AtomicU32, Ordering};
790    use std::time::Duration;
791
792    #[tokio::test(start_paused = true)]
793    async fn the_archiver_sweeps_a_minute_after_start_then_hourly() {
794        let sweeps = Arc::new(AtomicU32::new(0));
795        let counter = Arc::clone(&sweeps);
796        let task = tokio::spawn(run_archive_sweeps(move || {
797            let counter = Arc::clone(&counter);
798            async move {
799                counter.fetch_add(1, Ordering::SeqCst);
800            }
801        }));
802        tokio::time::sleep(Duration::from_secs(59)).await;
803        assert_eq!(sweeps.load(Ordering::SeqCst), 0);
804        tokio::time::sleep(Duration::from_secs(2)).await;
805        assert_eq!(sweeps.load(Ordering::SeqCst), 1, "the first sweep comes after a minute, not an hour");
806        tokio::time::sleep(Duration::from_secs(3600)).await;
807        assert_eq!(sweeps.load(Ordering::SeqCst), 2, "then hourly");
808        task.abort();
809    }
810}
811
812#[cfg(test)]
813mod flagged_sweep_tests {
814    use super::*;
815    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
816    use std::time::Duration;
817
818    fn spawn(on: &Arc<AtomicBool>) -> (Arc<AtomicU32>, tokio::task::JoinHandle<()>) {
819        let sweeps = Arc::new(AtomicU32::new(0));
820        let (counter, flag) = (Arc::clone(&sweeps), Arc::clone(on));
821        let task = tokio::spawn(run_flagged_sweeps(
822            move || flag.load(Ordering::SeqCst),
823            move || {
824                let counter = Arc::clone(&counter);
825                async move {
826                    counter.fetch_add(1, Ordering::SeqCst);
827                }
828            },
829        ));
830        (sweeps, task)
831    }
832
833    async fn pass(secs: u64) {
834        tokio::time::sleep(Duration::from_secs(secs)).await;
835    }
836
837    #[tokio::test(start_paused = true)]
838    async fn a_flag_that_stays_off_never_runs_the_pass() {
839        let on = Arc::new(AtomicBool::new(false));
840        let (sweeps, task) = spawn(&on);
841        pass(3 * 3600 + 5).await;
842        assert_eq!(sweeps.load(Ordering::SeqCst), 0);
843        task.abort();
844    }
845
846    #[tokio::test(start_paused = true)]
847    async fn a_flag_that_is_turned_on_runs_one_pass_within_a_minute() {
848        let on = Arc::new(AtomicBool::new(false));
849        let (sweeps, task) = spawn(&on);
850        pass(10 * 60).await;
851        assert_eq!(sweeps.load(Ordering::SeqCst), 0, "off: nothing ran, at the first sweep's minute or after");
852        on.store(true, Ordering::SeqCst);
853        pass(61).await;
854        assert_eq!(sweeps.load(Ordering::SeqCst), 1, "turned on: it ran without waiting for the hour");
855        pass(30 * 60).await;
856        assert_eq!(sweeps.load(Ordering::SeqCst), 1, "and not again while the flag stays on");
857        pass(31 * 60).await;
858        assert_eq!(sweeps.load(Ordering::SeqCst), 2, "then hourly from the run it was turned on for");
859        task.abort();
860    }
861
862    #[tokio::test(start_paused = true)]
863    async fn a_flag_that_stays_on_runs_a_minute_after_start_then_hourly_and_never_twice_in_a_minute() {
864        let on = Arc::new(AtomicBool::new(true));
865        let (sweeps, task) = spawn(&on);
866        pass(59).await;
867        assert_eq!(sweeps.load(Ordering::SeqCst), 0);
868        pass(2).await;
869        assert_eq!(sweeps.load(Ordering::SeqCst), 1, "the first pass comes after a minute");
870        pass(59 * 60 - 5).await;
871        assert_eq!(sweeps.load(Ordering::SeqCst), 1, "looking every minute does not run it again");
872        pass(66).await;
873        assert_eq!(sweeps.load(Ordering::SeqCst), 2, "the hourly pass");
874        task.abort();
875    }
876
877    #[tokio::test(start_paused = true)]
878    async fn a_flag_turned_off_and_on_again_runs_again_and_one_turned_off_stops_the_hourly_pass() {
879        let on = Arc::new(AtomicBool::new(true));
880        let (sweeps, task) = spawn(&on);
881        pass(61).await;
882        assert_eq!(sweeps.load(Ordering::SeqCst), 1);
883        on.store(false, Ordering::SeqCst);
884        pass(2 * 3600).await;
885        assert_eq!(sweeps.load(Ordering::SeqCst), 1, "off: the hourly pass does not run");
886        on.store(true, Ordering::SeqCst);
887        pass(61).await;
888        assert_eq!(sweeps.load(Ordering::SeqCst), 2, "on again: it runs at once");
889        task.abort();
890    }
891}
892
893#[cfg(test)]
894mod cloud_subscriber_gate_tests {
895    use super::*;
896    use std::sync::Mutex;
897
898    // Serialize: both tests mutate the same process-global env var, and
899    // `cargo test` runs tests in parallel by default within one binary.
900    static ENV_LOCK: Mutex<()> = Mutex::new(());
901
902    fn lock() -> std::sync::MutexGuard<'static, ()> {
903        ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
904    }
905
906    #[test]
907    fn defaults_to_enabled_so_shipped_and_dev_behavior_is_unchanged() {
908        let _guard = lock();
909        std::env::remove_var("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER");
910        assert!(
911            !cloud_subscriber_disabled_from_env(),
912            "must default to false — the shipped app and `task dev` need the \
913             real muxbus reconnect-on-launch behavior with no opt-out set"
914        );
915    }
916
917    #[test]
918    fn is_disabled_when_the_var_is_present_regardless_of_value() {
919        let _guard = lock();
920        // Presence-based, not value-based — matches AGENTMUX_DEV/AGENTMUX_TRAY.
921        // An empty value must still disable it; a caller setting the var to
922        // "" to mean "off" would otherwise silently get the opposite of
923        // what every other flag in this idiom does.
924        std::env::set_var("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER", "");
925        assert!(cloud_subscriber_disabled_from_env());
926        std::env::set_var("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER", "1");
927        assert!(cloud_subscriber_disabled_from_env());
928        std::env::remove_var("AGENTMUX_DISABLE_CLOUD_SUBSCRIBER");
929    }
930}
931
932#[cfg(test)]
933mod boot_reconnect_tests {
934    use super::*;
935    use agentmux_common::IsolatedMuxbusReconnectReason as Reason;
936
937    /// starpower (macOS, a `local-…` channel kept current by in-app upgrades) came back signed out
938    /// on every version: the default isolation skipped the reconnect even though the channel had
939    /// signed in on its own. A channel with its own sign-in reconnects.
940    #[test]
941    fn a_channel_with_its_own_sign_in_reconnects_at_boot() {
942        assert!(!skip_cloud_subscriber(Reason::ChannelDefaultIsolated, true));
943    }
944
945    /// A fresh local build (a new random channel, nothing stored) is still left alone, so the
946    /// keychain isn't read for a signature it has never seen.
947    #[test]
948    fn a_channel_with_no_sign_in_of_its_own_stays_skipped() {
949        assert!(skip_cloud_subscriber(Reason::ChannelDefaultIsolated, false));
950    }
951
952    #[test]
953    fn an_explicit_isolation_still_wins() {
954        assert!(skip_cloud_subscriber(Reason::ExplicitOptIn, true));
955        assert!(skip_cloud_subscriber(Reason::ExplicitOptIn, false));
956    }
957
958    #[test]
959    fn every_other_channel_reconnects_as_before() {
960        for reason in [Reason::ExplicitOptOut, Reason::LocalChannelNoPrompt, Reason::ChannelDefaultGlobal] {
961            assert!(!skip_cloud_subscriber(reason, false), "{reason:?}");
962            assert!(!skip_cloud_subscriber(reason, true), "{reason:?}");
963        }
964    }
965}