Skip to main content

lean_ctx/
daemon.rs

1use std::fs;
2use std::io::Write;
3use std::path::PathBuf;
4use std::process::Command;
5
6use anyhow::{Context, Result};
7
8use crate::ipc;
9
10fn data_dir() -> PathBuf {
11    dirs::data_local_dir()
12        .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join(".local/share"))
13        .join("lean-ctx")
14}
15
16pub fn daemon_pid_path() -> PathBuf {
17    data_dir().join("daemon.pid")
18}
19
20pub fn daemon_addr() -> ipc::DaemonAddr {
21    ipc::DaemonAddr::default_for_current_os()
22}
23
24pub fn is_daemon_running() -> bool {
25    let pid_path = daemon_pid_path();
26    let Ok(contents) = fs::read_to_string(&pid_path) else {
27        return false;
28    };
29    let Ok(pid) = contents.trim().parse::<u32>() else {
30        return false;
31    };
32    if ipc::process::is_alive(pid) {
33        return true;
34    }
35    let _ = fs::remove_file(&pid_path);
36    ipc::cleanup(&daemon_addr());
37    false
38}
39
40pub fn read_daemon_pid() -> Option<u32> {
41    let contents = fs::read_to_string(daemon_pid_path()).ok()?;
42    contents.trim().parse::<u32>().ok()
43}
44
45/// Exclusive, bounded-wait lock that serializes the daemon-start critical
46/// section (liveness check → spawn → PID write). Several MCP servers launching
47/// at once (Claude Code + OpenCode + Cursor) would otherwise all pass the
48/// `is_daemon_running()` check in the TOCTOU window and each spawn a daemon —
49/// the process proliferation seen in #453. The advisory flock is tied to the
50/// open fd, so it is released automatically if a holder crashes; the bounded
51/// wait keeps a wedged holder from blocking startup forever (the
52/// `is_daemon_running()` re-check remains the last line of defense).
53fn acquire_start_lock() -> Option<fs::File> {
54    use fs2::FileExt;
55    let lock_path = data_dir().join("daemon.start.lock");
56    if let Some(parent) = lock_path.parent() {
57        let _ = fs::create_dir_all(parent);
58    }
59    let file = fs::OpenOptions::new()
60        .create(true)
61        .write(true)
62        .truncate(false)
63        .open(&lock_path)
64        .ok()?;
65    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
66    loop {
67        match file.try_lock_exclusive() {
68            Ok(()) => return Some(file),
69            Err(_) if std::time::Instant::now() < deadline => {
70                std::thread::sleep(std::time::Duration::from_millis(50));
71            }
72            Err(_) => return None,
73        }
74    }
75}
76
77pub fn start_daemon(args: &[String]) -> Result<()> {
78    // Held for the whole critical section; released when `_start_lock` drops.
79    let _start_lock = acquire_start_lock();
80
81    if is_daemon_running() {
82        let pid = read_daemon_pid().unwrap_or(0);
83        anyhow::bail!("Daemon already running (PID {pid}). Use --stop to stop it first.");
84    }
85
86    ipc::cleanup(&daemon_addr());
87
88    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
89        crate::config_io::cleanup_legacy_backups(&data_dir);
90    }
91
92    let exe_str = crate::core::portable_binary::resolve_portable_binary();
93    let exe = std::path::PathBuf::from(&exe_str);
94
95    let mut cmd_args = vec!["serve".to_string()];
96    for arg in args {
97        if arg == "--daemon" || arg == "-d" {
98            continue;
99        }
100        cmd_args.push(arg.clone());
101    }
102    cmd_args.push("--_foreground-daemon".to_string());
103
104    let log_dir = data_dir();
105    let _ = fs::create_dir_all(&log_dir);
106    let stderr_log = log_dir.join("daemon-stderr.log");
107    let stderr_file = fs::OpenOptions::new()
108        .create(true)
109        .write(true)
110        .truncate(true)
111        .open(&stderr_log);
112    let stderr_cfg = match stderr_file {
113        Ok(f) => std::process::Stdio::from(f),
114        Err(_) => std::process::Stdio::inherit(),
115    };
116
117    let mut cmd = Command::new(&exe);
118    cmd.args(&cmd_args)
119        .stdin(std::process::Stdio::null())
120        .stdout(std::process::Stdio::null())
121        .stderr(stderr_cfg);
122    // Detached spawn: on Windows the daemon must escape the parent's
123    // console/Job so it survives AI-client MCP process recycling (GL #545).
124    let child = ipc::process::spawn_detached(&mut cmd)
125        .with_context(|| format!("failed to spawn daemon: {}", exe.display()))?;
126
127    let pid = child.id();
128    write_pid_file(pid)?;
129
130    std::thread::sleep(std::time::Duration::from_millis(200));
131
132    if !ipc::process::is_alive(pid) {
133        let _ = fs::remove_file(daemon_pid_path());
134        let stderr_content = fs::read_to_string(&stderr_log).unwrap_or_default();
135        let stderr_trimmed = stderr_content.trim();
136        if stderr_trimmed.is_empty() {
137            anyhow::bail!("Daemon process exited immediately. Check logs for errors.");
138        }
139        anyhow::bail!("Daemon process exited immediately:\n{stderr_trimmed}");
140    }
141
142    let addr = daemon_addr();
143    if crate::core::protocol::meta_visible() {
144        eprintln!(
145            "lean-ctx daemon started (PID {pid})\n  Endpoint: {}\n  PID file: {}",
146            addr.display(),
147            daemon_pid_path().display()
148        );
149    }
150
151    Ok(())
152}
153
154pub fn stop_daemon() -> Result<()> {
155    let pid_path = daemon_pid_path();
156
157    let Some(pid) = read_daemon_pid() else {
158        eprintln!("No daemon PID file found. Nothing to stop.");
159        return Ok(());
160    };
161
162    if !ipc::process::is_alive(pid) {
163        eprintln!("Daemon (PID {pid}) is not running. Cleaning up stale files.");
164        ipc::cleanup(&daemon_addr());
165        let _ = fs::remove_file(&pid_path);
166        return Ok(());
167    }
168
169    let http_shutdown_ok = try_http_shutdown();
170
171    if http_shutdown_ok {
172        for _ in 0..30 {
173            std::thread::sleep(std::time::Duration::from_millis(100));
174            if !ipc::process::is_alive(pid) {
175                break;
176            }
177        }
178    }
179
180    if ipc::process::is_alive(pid) {
181        let _ = ipc::process::terminate_gracefully(pid);
182        for _ in 0..20 {
183            std::thread::sleep(std::time::Duration::from_millis(100));
184            if !ipc::process::is_alive(pid) {
185                break;
186            }
187        }
188    }
189
190    if ipc::process::is_alive(pid) {
191        eprintln!("Daemon (PID {pid}) did not stop gracefully, force killing.");
192        let _ = ipc::process::force_kill(pid);
193        std::thread::sleep(std::time::Duration::from_millis(200));
194    }
195
196    let _ = fs::remove_file(&pid_path);
197    ipc::cleanup(&daemon_addr());
198    eprintln!("lean-ctx daemon stopped (PID {pid}).");
199
200    let orphans = ipc::process::find_pids_by_name("lean-ctx");
201    if !orphans.is_empty() {
202        eprintln!("  Cleaning up {} orphan process(es)…", orphans.len());
203        ipc::process::kill_all_by_name("lean-ctx");
204    }
205
206    Ok(())
207}
208
209fn try_http_shutdown() -> bool {
210    let Ok(rt) = tokio::runtime::Runtime::new() else {
211        return false;
212    };
213
214    rt.block_on(async {
215        crate::daemon_client::daemon_request("POST", "/v1/shutdown", "")
216            .await
217            .is_ok()
218    })
219}
220
221pub fn daemon_status() -> String {
222    let addr = daemon_addr();
223    if let Some(pid) = read_daemon_pid() {
224        if ipc::process::is_alive(pid) {
225            let listening = addr.is_listening();
226            return format!(
227                "Daemon running (PID {pid})\n  Endpoint: {} ({})\n  PID file: {}",
228                addr.display(),
229                if listening { "ready" } else { "missing" },
230                daemon_pid_path().display()
231            );
232        }
233        return format!("Daemon not running (stale PID file for PID {pid})");
234    }
235    "Daemon not running".to_string()
236}
237
238fn write_pid_file(pid: u32) -> Result<()> {
239    let pid_path = daemon_pid_path();
240    if let Some(parent) = pid_path.parent() {
241        fs::create_dir_all(parent)
242            .with_context(|| format!("cannot create dir: {}", parent.display()))?;
243    }
244    let mut f = fs::File::create(&pid_path)
245        .with_context(|| format!("cannot write PID file: {}", pid_path.display()))?;
246    write!(f, "{pid}")?;
247    Ok(())
248}
249
250/// Initialize the foreground-daemon process. Commits the XDG layout pin (and
251/// drains a residual `~/.lean-ctx`) *before* the daemon writes anything, so this
252/// long-running, possibly launchd/systemd-autostarted writer can never
253/// re-collapse config/data/state/cache onto a stray legacy dir (GL #623). The
254/// MCP server pins on its own start; the daemon is the other independent entry
255/// point (e.g. `serve --_foreground-daemon`), so it must heal too. `heal()` is
256/// idempotent and cheap — a no-op once pinned and when no residual dir exists.
257pub fn init_foreground_daemon() -> Result<()> {
258    crate::core::layout_pin::heal();
259    let pid = std::process::id();
260    write_pid_file(pid)?;
261    Ok(())
262}
263
264/// Cleanup PID file and IPC endpoint on shutdown.
265pub fn cleanup_daemon_files() {
266    let _ = fs::remove_file(daemon_pid_path());
267    ipc::cleanup(&daemon_addr());
268}