1use std::path::Path;
8use std::time::{Duration, Instant};
9
10fn 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 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 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 if let Some(parent) = marker.parent() {
52 let _ = std::fs::create_dir_all(parent);
53 }
54 let _ = std::fs::write(&marker, "migrated");
55}
56
57pub 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 #[cfg(target_os = "macos")]
70 rewrap_launchagents_for_tcc();
71
72 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 migrate_shadow_mode_default();
92
93 let cfg = crate::core::config::Config::load();
95 let proxy_active = cfg.proxy_enabled == Some(true);
96
97 let effective_skip_rules = if skip_rules {
100 true
101 } else {
102 !cfg.setup.should_inject_rules()
103 };
104
105 if proxy_active {
107 restart_proxy_if_running();
108 wait_for_proxy_health(crate::core::proxy_endpoint::default_port());
109 }
110
111 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 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 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
133pub trait SetupRefresh {
136 fn refresh(&self, proxy_active: bool, skip_rules: bool) -> Result<(), String>;
139 fn print_plan(&self, proxy_active: bool, skip_rules: bool);
141 fn print_unconnected_tools_hint(&self);
143}
144
145pub(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#[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
219fn 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
272const DAEMON_WAIT_ENV: &str = "LEAN_CTX_DAEMON_WAIT_SECS";
275const DEFAULT_DAEMON_WAIT_SECS: u64 = 10;
276const MAX_DAEMON_WAIT_SECS: u64 = 300;
278pub(super) const DAEMON_POLL: Duration = Duration::from_millis(500);
280pub(super) const DAEMON_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
282
283#[derive(Debug, Clone, PartialEq, Eq)]
285pub(super) enum DaemonRestart {
286 NotRunningBefore,
288 SwapDeferred,
291 ManualRestartNeeded,
297 RestartFailed(String),
299 Verified(String),
301 VersionMismatch {
304 expected: String,
305 reported: Option<String>,
306 waited_secs: u64,
307 },
308}
309
310impl DaemonRestart {
311 pub(super) fn waited(&self) -> bool {
314 matches!(self, Self::Verified(_) | Self::VersionMismatch { .. })
315 }
316}
317
318pub(super) trait DaemonControl {
321 fn supervised(&self) -> bool;
324 fn restart(&mut self) -> Result<(), String>;
330 fn reported_version(&mut self, timeout: Duration) -> Option<String>;
333 fn now(&self) -> Instant;
335 fn pause(&mut self, duration: Duration);
337}
338
339#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
341pub(super) struct RestartContext {
342 pub(super) was_running: bool,
344 pub(super) swap_landed: bool,
346 pub(super) unattended: bool,
349 pub(super) already_restarted: bool,
352}
353
354pub(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
383pub(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
395pub(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
414pub(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
475pub(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
535pub(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
545struct 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 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
614pub(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 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}