use std::path::Path;
use std::time::{Duration, Instant};
fn migrate_shadow_mode_default() {
let Ok(state) = crate::core::paths::state_dir() else {
return;
};
let marker = state.join("shadow_mode_migrated");
if marker.exists() {
return;
}
let global = crate::core::config::Config::load_global();
let raw_toml = crate::core::config::Config::path()
.and_then(|p| std::fs::read_to_string(p).ok())
.unwrap_or_default();
let explicitly_set = raw_toml.lines().any(|line| {
let trimmed = line.trim();
trimmed.starts_with("shadow_mode") && trimmed.contains('=')
});
if !explicitly_set && !global.shadow_mode {
match crate::core::config::Config::update_global(|c| c.shadow_mode = true) {
Ok(_) => {
eprintln!(" \u{2139} shadow_mode enabled (recommended default since v3.9.9).");
eprintln!(" Disable: lean-ctx config set shadow_mode false");
}
Err(e) => tracing::warn!("could not enable shadow_mode during update: {e}"),
}
} else if explicitly_set && !global.shadow_mode {
eprintln!(" \u{2139} shadow_mode is false in your config. Since v3.9.9, true is the");
eprintln!(" recommended default (60%+ more token savings). Enable:");
eprintln!(" lean-ctx config set shadow_mode true");
}
if let Some(parent) = marker.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(&marker, "migrated");
}
pub fn migrate_shadow_mode_default_public() {
migrate_shadow_mode_default();
}
pub(super) fn post_update_rewire(skip_rules: bool, quiet: bool, setup: &dyn SetupRefresh) {
#[cfg(target_os = "macos")]
rewrap_launchagents_for_tcc();
if crate::core::config::Config::load_global()
.proxy_enabled
.is_none()
&& crate::proxy_autostart::is_installed()
{
match crate::core::config::Config::update_global(|c| c.proxy_enabled = Some(true)) {
Ok(_) => {
eprintln!(" \u{2139} Proxy was already active \u{2014} keeping enabled.");
eprintln!(" Disable anytime: lean-ctx proxy disable");
}
Err(e) => tracing::warn!("could not persist proxy_enabled during update: {e}"),
}
}
migrate_shadow_mode_default();
let cfg = crate::core::config::Config::load();
let proxy_active = cfg.proxy_enabled == Some(true);
let effective_skip_rules = if skip_rules {
true
} else {
!cfg.setup.should_inject_rules()
};
if proxy_active {
restart_proxy_if_running();
wait_for_proxy_health(crate::core::proxy_endpoint::default_port());
}
if !cfg.shell_hook_disabled_effective() {
eprintln!(" \u{2139} Refreshing shell hooks in ~/.zshenv / ~/.bashenv.");
eprintln!(" Set shell_hook_disabled=true to prevent this in future updates.");
}
if let Err(e) = setup.refresh(proxy_active, effective_skip_rules) {
tracing::error!("Setup refresh error: {e}");
}
if !quiet {
setup.print_unconnected_tools_hint();
}
if crate::core::intelligence_runtime::cockpit::install_if_missing(true) && !quiet {
eprintln!(" \u{2713} LeanCTX Cockpit installed (open it with: lean-ctx cockpit).");
}
}
pub trait SetupRefresh {
fn refresh(&self, proxy_active: bool, skip_rules: bool) -> Result<(), String>;
fn print_plan(&self, proxy_active: bool, skip_rules: bool);
fn print_unconnected_tools_hint(&self);
}
pub(super) fn print_rewire_plan(skip_rules: bool, setup: &dyn SetupRefresh) {
let cfg = crate::core::config::Config::load();
let skip_rules = skip_rules || !cfg.setup.should_inject_rules();
setup.print_plan(cfg.proxy_enabled == Some(true), skip_rules);
setup.print_unconnected_tools_hint();
}
#[cfg(target_os = "macos")]
fn rewrap_launchagents_for_tcc() {
if !crate::daemon_autostart::controls_user_services() {
return;
}
if crate::proxy_autostart::is_installed() {
crate::proxy_autostart::install(crate::core::proxy_endpoint::default_port(), true);
}
if crate::daemon_autostart::is_installed() {
crate::daemon_autostart::install(true);
}
if crate::core::update_scheduler::schedule_status().enabled {
let hours = crate::core::config::Config::load()
.updates
.check_interval_hours;
if let Err(e) = crate::core::update_scheduler::install_schedule(hours) {
tracing::warn!("#356 re-wrap of auto-update LaunchAgent failed: {e}");
}
}
}
fn wait_for_proxy_health(port: u16) {
let max_attempts = 20;
for i in 0..max_attempts {
if is_proxy_reachable(port) {
println!(" \x1b[32m✓\x1b[0m Proxy healthy on port {port}");
return;
}
if i == 0 {
print!(" \x1b[2mWaiting for proxy to become healthy");
}
print!(".");
use std::io::Write;
std::io::stdout().flush().ok();
std::thread::sleep(std::time::Duration::from_millis(500));
}
println!();
eprintln!(
" \x1b[33m⚠\x1b[0m Proxy did not respond within {}s — writing env vars anyway",
max_attempts / 2
);
eprintln!(" If Claude Code shows connection errors, run: lean-ctx proxy start");
}
fn restart_proxy_if_running() {
let port = crate::core::proxy_endpoint::default_port();
if restart_managed_proxy() {
return;
}
if is_proxy_reachable(port) {
println!(
" \x1b[33m⟳\x1b[0m Proxy running on port {port} — restart it to use the new binary:"
);
println!(" \x1b[1mlean-ctx proxy start --port={port}\x1b[0m");
}
}
fn restart_managed_proxy() -> bool {
if !crate::daemon_autostart::controls_user_services() {
return false;
}
#[cfg(target_os = "macos")]
{
let plist_path = dirs::home_dir()
.unwrap_or_default()
.join("Library/LaunchAgents/com.leanctx.proxy.plist");
if plist_path.exists() {
if crate::core::launchd::bootstrap("com.leanctx.proxy", &plist_path) {
println!(" \x1b[32m✓\x1b[0m Proxy restarted (LaunchAgent)");
} else {
println!(" \x1b[33m⚠\x1b[0m Could not restart proxy LaunchAgent");
}
return true;
}
}
#[cfg(target_os = "linux")]
{
let service_path = dirs::home_dir()
.unwrap_or_default()
.join(".config/systemd/user/lean-ctx-proxy.service");
if service_path.exists() {
let result = std::process::Command::new("systemctl")
.args(["--user", "restart", "lean-ctx-proxy"])
.output();
match result {
Ok(o) if o.status.success() => {
println!(" \x1b[32m✓\x1b[0m Proxy restarted (systemd)");
}
_ => {
println!(" \x1b[33m⚠\x1b[0m Could not restart proxy systemd service");
}
}
return true;
}
}
false
}
fn is_proxy_reachable(port: u16) -> bool {
ureq::get(&format!("http://127.0.0.1:{port}/health"))
.call()
.is_ok()
}
const DAEMON_WAIT_ENV: &str = "LEAN_CTX_DAEMON_WAIT_SECS";
const DEFAULT_DAEMON_WAIT_SECS: u64 = 10;
const MAX_DAEMON_WAIT_SECS: u64 = 300;
pub(super) const DAEMON_POLL: Duration = Duration::from_millis(500);
pub(super) const DAEMON_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum DaemonRestart {
NotRunningBefore,
SwapDeferred,
ManualRestartNeeded,
RestartFailed(String),
Verified(String),
VersionMismatch {
expected: String,
reported: Option<String>,
waited_secs: u64,
},
}
impl DaemonRestart {
pub(super) fn waited(&self) -> bool {
matches!(self, Self::Verified(_) | Self::VersionMismatch { .. })
}
}
pub(super) trait DaemonControl {
fn supervised(&self) -> bool;
fn restart(&mut self) -> Result<(), String>;
fn reported_version(&mut self, timeout: Duration) -> Option<String>;
fn now(&self) -> Instant;
fn pause(&mut self, duration: Duration);
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct RestartContext {
pub(super) was_running: bool,
pub(super) swap_landed: bool,
pub(super) unattended: bool,
pub(super) already_restarted: bool,
}
pub(super) fn daemon_wait(raw: Option<&str>) -> (Duration, Option<String>) {
let default = Duration::from_secs(DEFAULT_DAEMON_WAIT_SECS);
let Some(value) = raw.map(str::trim).filter(|value| !value.is_empty()) else {
return (default, None);
};
let shown: String = value.chars().take(32).collect();
if !value.bytes().all(|b| b.is_ascii_digit()) {
return (
default,
Some(format!(
" \x1b[33m⚠\x1b[0m Ignoring {DAEMON_WAIT_ENV}={shown:?}: not a whole number of seconds; waiting {DEFAULT_DAEMON_WAIT_SECS}s."
)),
);
}
match value.parse::<u64>() {
Ok(secs) if secs <= MAX_DAEMON_WAIT_SECS => (Duration::from_secs(secs), None),
_ => (
Duration::from_secs(MAX_DAEMON_WAIT_SECS),
Some(format!(
" \x1b[33m⚠\x1b[0m {DAEMON_WAIT_ENV}={shown} is above the limit; waiting {MAX_DAEMON_WAIT_SECS}s."
)),
),
}
}
pub(super) fn unattended_run(os: &str, scheduled: bool, quiet: bool, tcc_standalone: bool) -> bool {
matches!(os, "macos" | "linux") && (scheduled || quiet || tcc_standalone)
}
pub(super) fn restarted_by_rewrap(
os: &str,
unit_installed: bool,
daemon_pid: Option<u32>,
launchd_pid: Option<u32>,
) -> bool {
os == "macos" && unit_installed && daemon_pid.is_some() && daemon_pid == launchd_pid
}
fn normalize_version(version: &str) -> &str {
version.trim().trim_start_matches('v')
}
pub(super) fn restart_and_verify(
control: &mut dyn DaemonControl,
context: RestartContext,
expected: &str,
wait: Duration,
) -> DaemonRestart {
if !context.was_running {
return DaemonRestart::NotRunningBefore;
}
if !context.swap_landed {
return DaemonRestart::SwapDeferred;
}
if !context.already_restarted {
if context.unattended && !control.supervised() {
return DaemonRestart::ManualRestartNeeded;
}
if let Err(error) = control.restart() {
return DaemonRestart::RestartFailed(error);
}
}
let expected = normalize_version(expected).to_string();
let start = control.now();
let deadline = start + wait;
let mut reported = None;
let mut first = true;
loop {
let remaining = deadline.saturating_duration_since(control.now());
let budget = if first {
remaining.max(DAEMON_POLL)
} else {
remaining
};
first = false;
if let Some(version) = control.reported_version(DAEMON_PROBE_TIMEOUT.min(budget)) {
let version = normalize_version(&version).to_string();
if version == expected {
return DaemonRestart::Verified(version);
}
reported = Some(version);
}
let remaining = deadline.saturating_duration_since(control.now());
if remaining.is_zero() {
break;
}
control.pause(DAEMON_POLL.min(remaining));
}
DaemonRestart::VersionMismatch {
expected,
reported,
waited_secs: control.now().saturating_duration_since(start).as_secs(),
}
}
pub(super) fn daemon_restart_report(outcome: &DaemonRestart) -> Option<(bool, Vec<String>)> {
const CHECK: &str =
" Check it with: lean-ctx daemon status; restart it with: lean-ctx daemon restart";
match outcome {
DaemonRestart::NotRunningBefore => None,
DaemonRestart::Verified(version) => Some((
false,
vec![format!(
" \x1b[32m✓\x1b[0m Daemon running on the new binary (v{version})"
)],
)),
DaemonRestart::SwapDeferred => Some((
true,
vec![
" \x1b[33m⚠\x1b[0m The binary swap finishes after this process exits; the daemon was not restarted.".to_string(),
" Once the swap is done, run: lean-ctx daemon restart".to_string(),
],
)),
DaemonRestart::ManualRestartNeeded => Some((
true,
vec![
" \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(),
" To move it to the new binary, run: lean-ctx daemon restart".to_string(),
],
)),
DaemonRestart::RestartFailed(error) => Some((
true,
vec![
format!(" \x1b[33m⚠\x1b[0m Could not restart the daemon on the new binary: {error}"),
CHECK.to_string(),
],
)),
DaemonRestart::VersionMismatch {
expected,
reported,
waited_secs,
} => {
let first = match reported {
Some(version) => format!(
" \x1b[33m⚠\x1b[0m The restarted daemon reports v{version}, not v{expected}."
),
None => format!(
" \x1b[33m⚠\x1b[0m The daemon did not come back on v{expected} within {waited_secs}s after the restart."
),
};
Some((
true,
vec![
first,
CHECK.to_string(),
" The update itself is installed; to go back: lean-ctx update --rollback"
.to_string(),
],
))
}
}
}
pub(super) fn version_from_capabilities(body: &str) -> Option<String> {
let doc: serde_json::Value = serde_json::from_str(body).ok()?;
doc.get("version")?
.as_str()
.map(normalize_version)
.filter(|version| !version.is_empty())
.map(str::to_string)
}
struct ServiceDaemon<'a> {
binary: &'a Path,
supervised: bool,
quiet: bool,
runtime: Option<tokio::runtime::Runtime>,
}
impl DaemonControl for ServiceDaemon<'_> {
fn supervised(&self) -> bool {
self.supervised
}
fn restart(&mut self) -> Result<(), String> {
if !self.quiet {
println!(" \x1b[2mRestarting the lean-ctx daemon on the new binary …\x1b[0m");
}
let stopped = if self.quiet {
crate::daemon::stop_daemon_quietly()
} else {
crate::daemon::stop_daemon()
};
stopped.map_err(|e| format!("stop: {e}"))?;
if self.supervised {
return if crate::daemon_autostart::start() {
Ok(())
} else {
Err("start: the service manager did not start the autostart unit".to_string())
};
}
crate::daemon::start_daemon_with_binary(&[], Some(self.binary))
.map_err(|e| format!("start: {e}"))
}
fn reported_version(&mut self, timeout: Duration) -> Option<String> {
if self.runtime.is_none() {
self.runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.ok();
}
let runtime = self.runtime.as_ref()?;
let body = runtime.block_on(async {
tokio::time::timeout(
timeout,
crate::daemon_client::daemon_request("GET", "/v1/local/capabilities", ""),
)
.await
.ok()?
.ok()
})?;
version_from_capabilities(&body)
}
fn now(&self) -> Instant {
Instant::now()
}
fn pause(&mut self, duration: Duration) {
std::thread::sleep(duration);
}
}
pub(super) fn restart_daemon_after_update(
context: RestartContext,
target_version: &str,
binary: &Path,
quiet: bool,
) -> DaemonRestart {
let (wait, wait_warning) = daemon_wait(std::env::var(DAEMON_WAIT_ENV).ok().as_deref());
let mut control = ServiceDaemon {
binary,
supervised: crate::daemon_autostart::is_installed(),
quiet,
runtime: None,
};
let outcome = restart_and_verify(&mut control, context, target_version, wait);
if let Some(warning) = wait_warning.filter(|_| outcome.waited()) {
eprintln!("{warning}");
}
if let Some((warning, lines)) = daemon_restart_report(&outcome) {
for line in lines {
if warning {
eprintln!("{line}");
} else if !quiet {
println!("{line}");
}
}
}
outcome
}