1use std::fs;
2use std::io::Write;
3use std::path::PathBuf;
4use std::process::Command;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7use anyhow::{Context, Result};
8
9use crate::ipc;
10
11static IS_FOREGROUND_DAEMON: AtomicBool = AtomicBool::new(false);
15
16pub fn mark_foreground_daemon() {
18 IS_FOREGROUND_DAEMON.store(true, Ordering::Relaxed);
19}
20
21#[must_use]
23pub fn is_foreground_daemon() -> bool {
24 IS_FOREGROUND_DAEMON.load(Ordering::Relaxed)
25}
26
27fn data_dir() -> PathBuf {
28 dirs::data_local_dir()
29 .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join(".local/share"))
30 .join("lean-ctx")
31}
32
33pub fn daemon_pid_path() -> PathBuf {
34 data_dir().join("daemon.pid")
35}
36
37pub fn daemon_addr() -> ipc::DaemonAddr {
38 ipc::DaemonAddr::default_for_current_os()
39}
40
41pub fn is_daemon_running() -> bool {
42 let pid_path = daemon_pid_path();
43 let Ok(contents) = fs::read_to_string(&pid_path) else {
44 return false;
45 };
46 let Ok(pid) = contents.trim().parse::<u32>() else {
47 return false;
48 };
49 if ipc::process::is_alive(pid) {
50 return true;
51 }
52 let _ = fs::remove_file(&pid_path);
53 ipc::cleanup(&daemon_addr());
54 false
55}
56
57pub fn read_daemon_pid() -> Option<u32> {
58 let contents = fs::read_to_string(daemon_pid_path()).ok()?;
59 contents.trim().parse::<u32>().ok()
60}
61
62fn acquire_start_lock() -> Option<fs::File> {
71 use fs2::FileExt;
72 let lock_path = data_dir().join("daemon.start.lock");
73 if let Some(parent) = lock_path.parent() {
74 let _ = fs::create_dir_all(parent);
75 }
76 let file = fs::OpenOptions::new()
77 .create(true)
78 .write(true)
79 .truncate(false)
80 .open(&lock_path)
81 .ok()?;
82 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
83 loop {
84 match file.try_lock_exclusive() {
85 Ok(()) => return Some(file),
86 Err(_) if std::time::Instant::now() < deadline => {
87 std::thread::sleep(std::time::Duration::from_millis(50));
88 }
89 Err(_) => return None,
90 }
91 }
92}
93
94pub fn start_daemon(args: &[String]) -> Result<()> {
95 let _start_lock = acquire_start_lock();
97
98 if is_daemon_running() {
99 let pid = read_daemon_pid().unwrap_or(0);
100 anyhow::bail!("Daemon already running (PID {pid}). Use --stop to stop it first.");
101 }
102
103 ipc::cleanup(&daemon_addr());
104
105 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
106 crate::config_io::cleanup_legacy_backups(&data_dir);
107 }
108
109 let exe_str = crate::core::portable_binary::resolve_portable_binary();
110 let exe = std::path::PathBuf::from(&exe_str);
111
112 let mut cmd_args = vec!["serve".to_string()];
113 for arg in args {
114 if arg == "--daemon" || arg == "-d" {
115 continue;
116 }
117 cmd_args.push(arg.clone());
118 }
119 cmd_args.push("--_foreground-daemon".to_string());
120
121 let log_dir = data_dir();
122 let _ = fs::create_dir_all(&log_dir);
123 let stderr_log = log_dir.join("daemon-stderr.log");
124 let stderr_file = fs::OpenOptions::new()
125 .create(true)
126 .write(true)
127 .truncate(true)
128 .open(&stderr_log);
129 let stderr_cfg = match stderr_file {
130 Ok(f) => std::process::Stdio::from(f),
131 Err(error) => {
132 eprintln!(
133 "Cannot open {}: {error}; daemon stderr disabled.",
134 stderr_log.display()
135 );
136 std::process::Stdio::null()
137 }
138 };
139
140 let mut cmd = Command::new(&exe);
141 cmd.args(&cmd_args)
142 .stdin(std::process::Stdio::null())
143 .stdout(std::process::Stdio::null())
144 .stderr(stderr_cfg);
145 if crate::core::pathutil::process_is_tcc_standalone() {
151 cmd.env("LEAN_CTX_TCC_STANDALONE", "1");
152 }
153 let child = ipc::process::spawn_detached(&mut cmd)
156 .with_context(|| format!("failed to spawn daemon: {}", exe.display()))?;
157
158 let pid = child.id();
159 write_pid_file(pid)?;
160
161 std::thread::sleep(std::time::Duration::from_millis(200));
162
163 if !ipc::process::is_alive(pid) {
164 let _ = fs::remove_file(daemon_pid_path());
165 let stderr_content = fs::read_to_string(&stderr_log).unwrap_or_default();
166 let stderr_trimmed = stderr_content.trim();
167 if stderr_trimmed.is_empty() {
168 anyhow::bail!("Daemon process exited immediately. Check logs for errors.");
169 }
170 anyhow::bail!("Daemon process exited immediately:\n{stderr_trimmed}");
171 }
172
173 let addr = daemon_addr();
174 if crate::core::protocol::meta_visible() {
175 eprintln!(
176 "lean-ctx daemon started (PID {pid})\n Endpoint: {}\n PID file: {}",
177 addr.display(),
178 daemon_pid_path().display()
179 );
180 }
181
182 Ok(())
183}
184
185pub fn stop_daemon() -> Result<()> {
186 let pid_path = daemon_pid_path();
187
188 let Some(pid) = read_daemon_pid() else {
189 eprintln!("No daemon PID file found. Nothing to stop.");
190 return Ok(());
191 };
192
193 if !ipc::process::is_alive(pid) {
194 eprintln!("Daemon (PID {pid}) is not running. Cleaning up stale files.");
195 ipc::cleanup(&daemon_addr());
196 let _ = fs::remove_file(&pid_path);
197 return Ok(());
198 }
199
200 let http_shutdown_ok = try_http_shutdown();
201
202 if http_shutdown_ok {
203 for _ in 0..30 {
204 std::thread::sleep(std::time::Duration::from_millis(100));
205 if !ipc::process::is_alive(pid) {
206 break;
207 }
208 }
209 }
210
211 if ipc::process::is_alive(pid) {
212 let _ = ipc::process::terminate_gracefully(pid);
213 for _ in 0..20 {
214 std::thread::sleep(std::time::Duration::from_millis(100));
215 if !ipc::process::is_alive(pid) {
216 break;
217 }
218 }
219 }
220
221 if ipc::process::is_alive(pid) {
222 eprintln!("Daemon (PID {pid}) did not stop gracefully, force killing.");
223 let _ = ipc::process::force_kill(pid);
224 std::thread::sleep(std::time::Duration::from_millis(200));
225 }
226
227 let _ = fs::remove_file(&pid_path);
228 ipc::cleanup(&daemon_addr());
229 eprintln!("lean-ctx daemon stopped (PID {pid}).");
230
231 let orphans = ipc::process::find_pids_by_name("lean-ctx");
232 if !orphans.is_empty() {
233 eprintln!(" Cleaning up {} orphan process(es)…", orphans.len());
234 ipc::process::kill_all_by_name("lean-ctx");
235 }
236
237 Ok(())
238}
239
240fn try_http_shutdown() -> bool {
241 let Ok(rt) = tokio::runtime::Runtime::new() else {
242 return false;
243 };
244
245 rt.block_on(async {
246 crate::daemon_client::daemon_request("POST", "/v1/shutdown", "")
247 .await
248 .is_ok()
249 })
250}
251
252pub fn daemon_status() -> String {
253 let addr = daemon_addr();
254 if let Some(pid) = read_daemon_pid() {
255 if ipc::process::is_alive(pid) {
256 let listening = addr.is_listening();
257 return format!(
258 "Daemon running (PID {pid})\n Endpoint: {} ({})\n PID file: {}",
259 addr.display(),
260 if listening { "ready" } else { "missing" },
261 daemon_pid_path().display()
262 );
263 }
264 return format!("Daemon not running (stale PID file for PID {pid})");
265 }
266 "Daemon not running".to_string()
267}
268
269fn write_pid_file(pid: u32) -> Result<()> {
270 let pid_path = daemon_pid_path();
271 if let Some(parent) = pid_path.parent() {
272 fs::create_dir_all(parent)
273 .with_context(|| format!("cannot create dir: {}", parent.display()))?;
274 }
275 let mut f = fs::File::create(&pid_path)
276 .with_context(|| format!("cannot write PID file: {}", pid_path.display()))?;
277 write!(f, "{pid}")?;
278 Ok(())
279}
280
281pub fn init_foreground_daemon() -> Result<()> {
289 mark_foreground_daemon();
290 crate::core::layout_pin::heal();
291 crate::core::agents::reaper::spawn_reaper();
295 let pid = std::process::id();
296 write_pid_file(pid)?;
297 Ok(())
298}
299
300pub fn cleanup_daemon_files() {
302 let _ = fs::remove_file(daemon_pid_path());
303 ipc::cleanup(&daemon_addr());
304}