Skip to main content

lean_ctx/core/updater/
rewire.rs

1// SPDX-License-Identifier: Apache-2.0
2//! After an update: the one-time config migrations, LaunchAgent re-wrap,
3//! proxy restart and the setup refresh (`post_update_rewire`), limited to the
4//! recorded agent selection or the already-connected tools; then the daemon
5//! restart on the new binary (`restart_daemon_after_update`).
6
7use std::path::Path;
8use std::time::{Duration, Instant};
9
10/// #828: One-time migration — enable `shadow_mode` for users who never
11/// explicitly set it. Without shadow mode, most harnesses silently prefer
12/// native tools, negating lean-ctx's token savings. Idempotent: a state-dir
13/// marker prevents repeated flips if the user disables it after migration.
14fn migrate_shadow_mode_default() {
15    let Ok(state) = crate::core::paths::state_dir() else {
16        return;
17    };
18    let marker = state.join("shadow_mode_migrated");
19    if marker.exists() {
20        return;
21    }
22
23    // Read raw TOML to distinguish "explicitly set to false" from "never set".
24    let global = crate::core::config::Config::load_global();
25    let raw_toml = crate::core::config::Config::path()
26        .and_then(|p| std::fs::read_to_string(p).ok())
27        .unwrap_or_default();
28
29    let explicitly_set = raw_toml.lines().any(|line| {
30        let trimmed = line.trim();
31        trimmed.starts_with("shadow_mode") && trimmed.contains('=')
32    });
33
34    if !explicitly_set && !global.shadow_mode {
35        // User never touched shadow_mode — the old default was false.
36        // Set it to true in the global config so it persists.
37        match crate::core::config::Config::update_global(|c| c.shadow_mode = true) {
38            Ok(_) => {
39                eprintln!("  \u{2139} shadow_mode enabled (recommended default since v3.9.9).");
40                eprintln!("    Disable: lean-ctx config set shadow_mode false");
41            }
42            Err(e) => tracing::warn!("could not enable shadow_mode during update: {e}"),
43        }
44    } else if explicitly_set && !global.shadow_mode {
45        eprintln!("  \u{2139} shadow_mode is false in your config. Since v3.9.9, true is the");
46        eprintln!("    recommended default (60%+ more token savings). Enable:");
47        eprintln!("    lean-ctx config set shadow_mode true");
48    }
49
50    // Write marker so this migration runs only once.
51    if let Some(parent) = marker.parent() {
52        let _ = std::fs::create_dir_all(parent);
53    }
54    let _ = std::fs::write(&marker, "migrated");
55}
56
57/// Public entry point for the shadow_mode migration, callable from
58/// `cmd_dev_install` and other lifecycle commands.
59pub fn migrate_shadow_mode_default_public() {
60    migrate_shadow_mode_default();
61}
62
63pub(super) fn post_update_rewire(skip_rules: bool, quiet: bool, setup: &dyn SetupRefresh) {
64    // #356: regenerate installed LaunchAgent plists so they adopt the new
65    // deny-~/Documents seatbelt wrapper. A plist is only (re)written on install,
66    // so without this an upgrade keeps the old unwrapped plist — and the TCC
67    // prompt — until the next manual enable. Idempotent: install rewrites the
68    // plist and re-bootstraps it.
69    #[cfg(target_os = "macos")]
70    rewrap_launchagents_for_tcc();
71
72    // The persist decision reads the GLOBAL file only and writes via
73    // update_global, so a project-local override is never leaked into the
74    // global config (#443).
75    if crate::core::config::Config::load_global()
76        .proxy_enabled
77        .is_none()
78        && crate::proxy_autostart::is_installed()
79    {
80        match crate::core::config::Config::update_global(|c| c.proxy_enabled = Some(true)) {
81            Ok(_) => {
82                eprintln!("  \u{2139} Proxy was already active \u{2014} keeping enabled.");
83                eprintln!("    Disable anytime: lean-ctx proxy disable");
84            }
85            Err(e) => tracing::warn!("could not persist proxy_enabled during update: {e}"),
86        }
87    }
88
89    // #828: shadow_mode default changed to true. Migrate existing configs
90    // that never explicitly set it (still at old default false).
91    migrate_shadow_mode_default();
92
93    // Runtime decisions use the effective (global + project-local) config.
94    let cfg = crate::core::config::Config::load();
95    let proxy_active = cfg.proxy_enabled == Some(true);
96
97    // Determine whether rules should be injected during rewire.
98    // CLI --skip-rules always wins. Otherwise, respect the config setting.
99    let effective_skip_rules = if skip_rules {
100        true
101    } else {
102        !cfg.setup.should_inject_rules()
103    };
104
105    // PHASE 1: Restart proxy BEFORE writing env vars.
106    if proxy_active {
107        restart_proxy_if_running();
108        wait_for_proxy_health(crate::core::proxy_endpoint::default_port());
109    }
110
111    // PHASE 2: Run setup which writes MCP configs (always) and rules (if opted in).
112    // #1026: shell hooks are refreshed here — but install_all_with_style
113    // respects shell_hook_disabled, so users who opt out keep control.
114    if !cfg.shell_hook_disabled_effective() {
115        eprintln!("  \u{2139} Refreshing shell hooks in ~/.zshenv / ~/.bashenv.");
116        eprintln!("    Set shell_hook_disabled=true to prevent this in future updates.");
117    }
118    // Only the recorded selection (setup.agents) or, without one, the tools
119    // that are already connected: an update never connects a new tool.
120    if let Err(e) = setup.refresh(proxy_active, effective_skip_rules) {
121        tracing::error!("Setup refresh error: {e}");
122    }
123    if !quiet {
124        setup.print_unconnected_tools_hint();
125    }
126
127    // The Cockpit ships with LeanCTX: an update installs it when it is missing.
128    if crate::core::intelligence_runtime::cockpit::install_if_missing(true) && !quiet {
129        eprintln!("  \u{2713} LeanCTX Cockpit installed (open it with: lean-ctx cockpit).");
130    }
131}
132
133/// The setup refresh an update runs after replacing the binary. Setup sits
134/// above the engine, so the updater's caller supplies it.
135pub trait SetupRefresh {
136    /// Re-run setup in refresh-only mode: MCP configs, shell hooks and, unless
137    /// `skip_rules`, rules for the recorded or already-connected tools.
138    fn refresh(&self, proxy_active: bool, skip_rules: bool) -> Result<(), String>;
139    /// Print what [`SetupRefresh::refresh`] would change, without writing.
140    fn print_plan(&self, proxy_active: bool, skip_rules: bool);
141    /// Name installed tools the refresh leaves alone.
142    fn print_unconnected_tools_hint(&self);
143}
144
145/// `update --dry-run`: the refresh an update would run, without writing.
146pub(super) fn print_rewire_plan(skip_rules: bool, setup: &dyn SetupRefresh) {
147    let cfg = crate::core::config::Config::load();
148    let skip_rules = skip_rules || !cfg.setup.should_inject_rules();
149    setup.print_plan(cfg.proxy_enabled == Some(true), skip_rules);
150    setup.print_unconnected_tools_hint();
151}
152
153/// #356: rewrite every installed LaunchAgent plist (daemon, proxy, auto-updater)
154/// so an upgrade re-emits them with the deny-~/Documents seatbelt wrapper.
155/// plists are only generated on install, so an existing install would otherwise
156/// keep the pre-wrapper plist — and the prompt — until the next manual `enable`.
157/// Each `install` / `install_schedule` rewrites the plist and re-bootstraps it.
158/// Another instance (directory override, sandbox HOME) rewrites none of them:
159/// they belong to the default install.
160#[cfg(target_os = "macos")]
161fn rewrap_launchagents_for_tcc() {
162    if !crate::daemon_autostart::controls_user_services() {
163        return;
164    }
165    if crate::proxy_autostart::is_installed() {
166        crate::proxy_autostart::install(crate::core::proxy_endpoint::default_port(), true);
167    }
168    if crate::daemon_autostart::is_installed() {
169        crate::daemon_autostart::install(true);
170    }
171    if crate::core::update_scheduler::schedule_status().enabled {
172        let hours = crate::core::config::Config::load()
173            .updates
174            .check_interval_hours;
175        if let Err(e) = crate::core::update_scheduler::install_schedule(hours) {
176            tracing::warn!("#356 re-wrap of auto-update LaunchAgent failed: {e}");
177        }
178    }
179}
180
181fn wait_for_proxy_health(port: u16) {
182    let max_attempts = 20;
183    for i in 0..max_attempts {
184        if is_proxy_reachable(port) {
185            println!("  \x1b[32m✓\x1b[0m Proxy healthy on port {port}");
186            return;
187        }
188        if i == 0 {
189            print!("  \x1b[2mWaiting for proxy to become healthy");
190        }
191        print!(".");
192        use std::io::Write;
193        std::io::stdout().flush().ok();
194        std::thread::sleep(std::time::Duration::from_millis(500));
195    }
196    println!();
197    eprintln!(
198        "  \x1b[33m⚠\x1b[0m Proxy did not respond within {}s — writing env vars anyway",
199        max_attempts / 2
200    );
201    eprintln!("    If Claude Code shows connection errors, run: lean-ctx proxy start");
202}
203
204fn restart_proxy_if_running() {
205    let port = crate::core::proxy_endpoint::default_port();
206
207    if restart_managed_proxy() {
208        return;
209    }
210
211    if is_proxy_reachable(port) {
212        println!(
213            "  \x1b[33m⟳\x1b[0m Proxy running on port {port} — restart it to use the new binary:"
214        );
215        println!("    \x1b[1mlean-ctx proxy start --port={port}\x1b[0m");
216    }
217}
218
219/// Restart proxy managed by launchd (macOS) or systemd (Linux).
220/// Returns `true` if a managed service was found and restarted. Another
221/// instance restarts nothing: `systemctl --user restart lean-ctx-proxy`
222/// addresses the default install's unit by name, whatever HOME says.
223fn restart_managed_proxy() -> bool {
224    if !crate::daemon_autostart::controls_user_services() {
225        return false;
226    }
227    #[cfg(target_os = "macos")]
228    {
229        let plist_path = dirs::home_dir()
230            .unwrap_or_default()
231            .join("Library/LaunchAgents/com.leanctx.proxy.plist");
232        if plist_path.exists() {
233            if crate::core::launchd::bootstrap("com.leanctx.proxy", &plist_path) {
234                println!("  \x1b[32m✓\x1b[0m Proxy restarted (LaunchAgent)");
235            } else {
236                println!("  \x1b[33m⚠\x1b[0m Could not restart proxy LaunchAgent");
237            }
238            return true;
239        }
240    }
241
242    #[cfg(target_os = "linux")]
243    {
244        let service_path = dirs::home_dir()
245            .unwrap_or_default()
246            .join(".config/systemd/user/lean-ctx-proxy.service");
247        if service_path.exists() {
248            let result = std::process::Command::new("systemctl")
249                .args(["--user", "restart", "lean-ctx-proxy"])
250                .output();
251            match result {
252                Ok(o) if o.status.success() => {
253                    println!("  \x1b[32m✓\x1b[0m Proxy restarted (systemd)");
254                }
255                _ => {
256                    println!("  \x1b[33m⚠\x1b[0m Could not restart proxy systemd service");
257                }
258            }
259            return true;
260        }
261    }
262
263    false
264}
265
266fn is_proxy_reachable(port: u16) -> bool {
267    ureq::get(&format!("http://127.0.0.1:{port}/health"))
268        .call()
269        .is_ok()
270}
271
272/// How long the updater waits for the restarted daemon, as the installers do
273/// (`LEAN_CTX_DAEMON_WAIT_SECS`, default 10 s, since !432).
274const DAEMON_WAIT_ENV: &str = "LEAN_CTX_DAEMON_WAIT_SECS";
275const DEFAULT_DAEMON_WAIT_SECS: u64 = 10;
276/// Upper bound for the wait, so a stray value never hangs an update.
277const MAX_DAEMON_WAIT_SECS: u64 = 300;
278/// Interval between two version checks while waiting.
279pub(super) const DAEMON_POLL: Duration = Duration::from_millis(500);
280/// Longest single version probe; a probe never runs past the wait's deadline.
281pub(super) const DAEMON_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
282
283/// What restarting the daemon after an update found.
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub(super) enum DaemonRestart {
286    /// No daemon ran before the update: it stays stopped.
287    NotRunningBefore,
288    /// The new binary is not in place yet (the deferred swap on Windows when
289    /// the binary is locked): restarting now would start the old binary.
290    SwapDeferred,
291    /// An unattended update (`--scheduled`, `--quiet` from an older scheduler,
292    /// or a launchd-standalone process on macOS) found no autostart unit to restart the daemon through. Starting
293    /// it directly would put the daemon inside the updater's sandbox (the
294    /// deny-~/Documents seatbelt) or its timer unit, so it is left on the old
295    /// binary and the user is told to restart it.
296    ManualRestartNeeded,
297    /// Stopping or starting the daemon failed.
298    RestartFailed(String),
299    /// The daemon answers with the new version.
300    Verified(String),
301    /// Within `waited_secs` the daemon did not answer with `expected`;
302    /// `reported` is the last version it answered with (`None`: no answer).
303    VersionMismatch {
304        expected: String,
305        reported: Option<String>,
306        waited_secs: u64,
307    },
308}
309
310impl DaemonRestart {
311    /// Whether the version check ran, so a warning about the wait value
312    /// (`LEAN_CTX_DAEMON_WAIT_SECS`) is relevant.
313    pub(super) fn waited(&self) -> bool {
314        matches!(self, Self::Verified(_) | Self::VersionMismatch { .. })
315    }
316}
317
318/// The daemon operations the restart needs, so the decision logic is tested
319/// without starting a real daemon.
320pub(super) trait DaemonControl {
321    /// Whether this instance's autostart unit (LaunchAgent, systemd user
322    /// unit) is installed, so a restart goes through the service manager.
323    fn supervised(&self) -> bool;
324    /// Stop this instance's daemon and start it again on the new binary.
325    /// Not covered by the version-check deadline: the restart is bounded by
326    /// the stop ladder (endpoint shutdown, TERM, KILL) and the service
327    /// manager's own timeouts (`systemctl --user stop/start` waits up to the
328    /// unit's `TimeoutStopSec`/`TimeoutStartSec`).
329    fn restart(&mut self) -> Result<(), String>;
330    /// The version the running daemon reports within `timeout`, `None` when
331    /// it does not answer in time.
332    fn reported_version(&mut self, timeout: Duration) -> Option<String>;
333    /// The current time, so the wait is bounded by a deadline.
334    fn now(&self) -> Instant;
335    /// Wait before the next check.
336    fn pause(&mut self, duration: Duration);
337}
338
339/// What the updater knows about the daemon and its own run.
340#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
341pub(super) struct RestartContext {
342    /// This instance's daemon ran before the swap.
343    pub(super) was_running: bool,
344    /// The new binary is in place (not deferred to the Windows helper).
345    pub(super) swap_landed: bool,
346    /// An unattended run on a platform whose daemon belongs under a service
347    /// unit (see [`unattended_run`]).
348    pub(super) unattended: bool,
349    /// The setup refresh already restarted the daemon through its unit (see
350    /// [`restarted_by_rewrap`]).
351    pub(super) already_restarted: bool,
352}
353
354/// The wait for the restarted daemon from `LEAN_CTX_DAEMON_WAIT_SECS`: whole
355/// seconds, at most 300 s, the default 10 s when unset. An invalid value
356/// (`1.5`, `-3`, `abc`) also falls back to the default and a capped one to
357/// 300 s; both come with a warning for the user.
358pub(super) fn daemon_wait(raw: Option<&str>) -> (Duration, Option<String>) {
359    let default = Duration::from_secs(DEFAULT_DAEMON_WAIT_SECS);
360    let Some(value) = raw.map(str::trim).filter(|value| !value.is_empty()) else {
361        return (default, None);
362    };
363    let shown: String = value.chars().take(32).collect();
364    if !value.bytes().all(|b| b.is_ascii_digit()) {
365        return (
366            default,
367            Some(format!(
368                "  \x1b[33m⚠\x1b[0m Ignoring {DAEMON_WAIT_ENV}={shown:?}: not a whole number of seconds; waiting {DEFAULT_DAEMON_WAIT_SECS}s."
369            )),
370        );
371    }
372    match value.parse::<u64>() {
373        Ok(secs) if secs <= MAX_DAEMON_WAIT_SECS => (Duration::from_secs(secs), None),
374        _ => (
375            Duration::from_secs(MAX_DAEMON_WAIT_SECS),
376            Some(format!(
377                "  \x1b[33m⚠\x1b[0m {DAEMON_WAIT_ENV}={shown} is above the limit; waiting {MAX_DAEMON_WAIT_SECS}s."
378            )),
379        ),
380    }
381}
382
383/// Whether this update runs unattended on `os` in the sense that matters for
384/// the daemon: an automatic run (`--scheduled`, or `--quiet` alone as the
385/// schedulers written before #335 still invoke it, the same definition as
386/// the auto-update gate) or a launchd-standalone process. Only on macOS and
387/// Linux, where a directly started daemon would inherit the updater's
388/// deny-~/Documents seatbelt (macOS) or die with the oneshot timer unit's
389/// cgroup (Linux, `KillMode=control-group`). Windows has no unit: the daemon
390/// always starts directly there.
391pub(super) fn unattended_run(os: &str, scheduled: bool, quiet: bool, tcc_standalone: bool) -> bool {
392    matches!(os, "macos" | "linux") && (scheduled || quiet || tcc_standalone)
393}
394
395/// Whether the setup refresh already restarted the daemon on `os`: on macOS
396/// `post_update_rewire` re-wraps an installed daemon LaunchAgent and
397/// re-bootstraps it, which restarts the daemon that launchd runs. That holds
398/// only when the daemon found before the swap (`daemon_pid`) was the
399/// LaunchAgent's job (`launchd_pid`); a daemon started by hand next to an
400/// installed plist is still stopped and restarted explicitly.
401pub(super) fn restarted_by_rewrap(
402    os: &str,
403    unit_installed: bool,
404    daemon_pid: Option<u32>,
405    launchd_pid: Option<u32>,
406) -> bool {
407    os == "macos" && unit_installed && daemon_pid.is_some() && daemon_pid == launchd_pid
408}
409
410fn normalize_version(version: &str) -> &str {
411    version.trim().trim_start_matches('v')
412}
413
414/// Restart the daemon only when it ran before the update and the new binary
415/// is in place, then check until a deadline `wait` after the restart that it
416/// reports `expected`. Every probe is cut to the time left, so the whole wait
417/// ends by the deadline (the very first probe gets at least one poll
418/// interval, so a wait of 0 s still asks once). The deadline bounds only the
419/// version check, not [`DaemonControl::restart`] before it. A daemon that ran
420/// before is never left without a report: the outcome says whether it came
421/// back on the new version.
422pub(super) fn restart_and_verify(
423    control: &mut dyn DaemonControl,
424    context: RestartContext,
425    expected: &str,
426    wait: Duration,
427) -> DaemonRestart {
428    if !context.was_running {
429        return DaemonRestart::NotRunningBefore;
430    }
431    if !context.swap_landed {
432        return DaemonRestart::SwapDeferred;
433    }
434    if !context.already_restarted {
435        if context.unattended && !control.supervised() {
436            return DaemonRestart::ManualRestartNeeded;
437        }
438        if let Err(error) = control.restart() {
439            return DaemonRestart::RestartFailed(error);
440        }
441    }
442    let expected = normalize_version(expected).to_string();
443    let start = control.now();
444    let deadline = start + wait;
445    let mut reported = None;
446    let mut first = true;
447    loop {
448        let remaining = deadline.saturating_duration_since(control.now());
449        let budget = if first {
450            remaining.max(DAEMON_POLL)
451        } else {
452            remaining
453        };
454        first = false;
455        if let Some(version) = control.reported_version(DAEMON_PROBE_TIMEOUT.min(budget)) {
456            let version = normalize_version(&version).to_string();
457            if version == expected {
458                return DaemonRestart::Verified(version);
459            }
460            reported = Some(version);
461        }
462        let remaining = deadline.saturating_duration_since(control.now());
463        if remaining.is_zero() {
464            break;
465        }
466        control.pause(DAEMON_POLL.min(remaining));
467    }
468    DaemonRestart::VersionMismatch {
469        expected,
470        reported,
471        waited_secs: control.now().saturating_duration_since(start).as_secs(),
472    }
473}
474
475/// What the updater prints for `outcome`: `(warning, lines)`, where a warning
476/// goes to stderr even in quiet mode. `None` when there is nothing to say.
477pub(super) fn daemon_restart_report(outcome: &DaemonRestart) -> Option<(bool, Vec<String>)> {
478    const CHECK: &str =
479        "    Check it with: lean-ctx daemon status; restart it with: lean-ctx daemon restart";
480    match outcome {
481        DaemonRestart::NotRunningBefore => None,
482        DaemonRestart::Verified(version) => Some((
483            false,
484            vec![format!(
485                "  \x1b[32m✓\x1b[0m Daemon running on the new binary (v{version})"
486            )],
487        )),
488        DaemonRestart::SwapDeferred => Some((
489            true,
490            vec![
491                "  \x1b[33m⚠\x1b[0m The binary swap finishes after this process exits; the daemon was not restarted.".to_string(),
492                "    Once the swap is done, run: lean-ctx daemon restart".to_string(),
493            ],
494        )),
495        DaemonRestart::ManualRestartNeeded => Some((
496            true,
497            vec![
498                "  \x1b[33m⚠\x1b[0m The daemon still runs the old binary: an unattended update does not start a daemon outside its autostart unit.".to_string(),
499                "    To move it to the new binary, run: lean-ctx daemon restart".to_string(),
500            ],
501        )),
502        DaemonRestart::RestartFailed(error) => Some((
503            true,
504            vec![
505                format!("  \x1b[33m⚠\x1b[0m Could not restart the daemon on the new binary: {error}"),
506                CHECK.to_string(),
507            ],
508        )),
509        DaemonRestart::VersionMismatch {
510            expected,
511            reported,
512            waited_secs,
513        } => {
514            let first = match reported {
515                Some(version) => format!(
516                    "  \x1b[33m⚠\x1b[0m The restarted daemon reports v{version}, not v{expected}."
517                ),
518                None => format!(
519                    "  \x1b[33m⚠\x1b[0m The daemon did not come back on v{expected} within {waited_secs}s after the restart."
520                ),
521            };
522            Some((
523                true,
524                vec![
525                    first,
526                    CHECK.to_string(),
527                    "    The update itself is installed; to go back: lean-ctx update --rollback"
528                        .to_string(),
529                ],
530            ))
531        }
532    }
533}
534
535/// The version in a `GET /v1/local/capabilities` document (`"version"`).
536pub(super) fn version_from_capabilities(body: &str) -> Option<String> {
537    let doc: serde_json::Value = serde_json::from_str(body).ok()?;
538    doc.get("version")?
539        .as_str()
540        .map(normalize_version)
541        .filter(|version| !version.is_empty())
542        .map(str::to_string)
543}
544
545/// The daemon of this instance through the existing daemon and service API,
546/// the same channel as `lean-ctx daemon restart`: `stop_daemon` stops this
547/// data dir's daemon (and its launchd/systemd supervisor only when that runs
548/// it); the autostart unit starts it again where one is installed (macOS
549/// LaunchAgent, Linux systemd user unit), otherwise the new binary starts it
550/// directly (Windows, or no unit). Never `lean-ctx stop`.
551struct ServiceDaemon<'a> {
552    binary: &'a Path,
553    supervised: bool,
554    quiet: bool,
555    runtime: Option<tokio::runtime::Runtime>,
556}
557
558impl DaemonControl for ServiceDaemon<'_> {
559    fn supervised(&self) -> bool {
560        self.supervised
561    }
562
563    fn restart(&mut self) -> Result<(), String> {
564        if !self.quiet {
565            println!("  \x1b[2mRestarting the lean-ctx daemon on the new binary …\x1b[0m");
566        }
567        let stopped = if self.quiet {
568            crate::daemon::stop_daemon_quietly()
569        } else {
570            crate::daemon::stop_daemon()
571        };
572        stopped.map_err(|e| format!("stop: {e}"))?;
573        if self.supervised {
574            // A refused start is reported now, not after the whole wait.
575            return if crate::daemon_autostart::start() {
576                Ok(())
577            } else {
578                Err("start: the service manager did not start the autostart unit".to_string())
579            };
580        }
581        crate::daemon::start_daemon_with_binary(&[], Some(self.binary))
582            .map_err(|e| format!("start: {e}"))
583    }
584
585    fn reported_version(&mut self, timeout: Duration) -> Option<String> {
586        if self.runtime.is_none() {
587            self.runtime = tokio::runtime::Builder::new_current_thread()
588                .enable_all()
589                .build()
590                .ok();
591        }
592        let runtime = self.runtime.as_ref()?;
593        let body = runtime.block_on(async {
594            tokio::time::timeout(
595                timeout,
596                crate::daemon_client::daemon_request("GET", "/v1/local/capabilities", ""),
597            )
598            .await
599            .ok()?
600            .ok()
601        })?;
602        version_from_capabilities(&body)
603    }
604
605    fn now(&self) -> Instant {
606        Instant::now()
607    }
608
609    fn pause(&mut self, duration: Duration) {
610        std::thread::sleep(duration);
611    }
612}
613
614/// After a successful update: restart the daemon that ran before the swap on
615/// the new binary (`binary`) and confirm it reports `target_version`, as the
616/// installers do since !432. The rollback state is not touched: a daemon that
617/// does not come back is reported, the update stays installed and
618/// `lean-ctx update --rollback` remains available.
619pub(super) fn restart_daemon_after_update(
620    context: RestartContext,
621    target_version: &str,
622    binary: &Path,
623    quiet: bool,
624) -> DaemonRestart {
625    let (wait, wait_warning) = daemon_wait(std::env::var(DAEMON_WAIT_ENV).ok().as_deref());
626    let mut control = ServiceDaemon {
627        binary,
628        supervised: crate::daemon_autostart::is_installed(),
629        quiet,
630        runtime: None,
631    };
632    let outcome = restart_and_verify(&mut control, context, target_version, wait);
633    // The wait value matters only when a wait actually ran.
634    if let Some(warning) = wait_warning.filter(|_| outcome.waited()) {
635        eprintln!("{warning}");
636    }
637    if let Some((warning, lines)) = daemon_restart_report(&outcome) {
638        for line in lines {
639            if warning {
640                eprintln!("{line}");
641            } else if !quiet {
642                println!("{line}");
643            }
644        }
645    }
646    outcome
647}