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 start_daemon_with_binary(args, None)
96}
97
98pub(crate) fn start_daemon_with_binary(
100 args: &[String],
101 binary: Option<&std::path::Path>,
102) -> Result<()> {
103 let _start_lock = acquire_start_lock();
105
106 if is_daemon_running() {
107 let pid = read_daemon_pid().unwrap_or(0);
108 anyhow::bail!("Daemon already running (PID {pid}). Use --stop to stop it first.");
109 }
110
111 ipc::cleanup(&daemon_addr());
112
113 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
114 crate::config_io::cleanup_legacy_backups(&data_dir);
115 }
116
117 let exe = binary.map_or_else(
118 || std::path::PathBuf::from(crate::core::portable_binary::resolve_portable_binary()),
119 std::path::Path::to_path_buf,
120 );
121
122 let mut cmd_args = vec!["serve".to_string()];
123 for arg in args {
124 if arg == "--daemon" || arg == "-d" {
125 continue;
126 }
127 cmd_args.push(arg.clone());
128 }
129 cmd_args.push("--_foreground-daemon".to_string());
130
131 let log_dir = data_dir();
132 let _ = fs::create_dir_all(&log_dir);
133 let stderr_log = log_dir.join("daemon-stderr.log");
134 let stderr_file = fs::OpenOptions::new()
135 .create(true)
136 .write(true)
137 .truncate(true)
138 .open(&stderr_log);
139 let stderr_cfg = match stderr_file {
140 Ok(f) => std::process::Stdio::from(f),
141 Err(error) => {
142 eprintln!(
143 "Cannot open {}: {error}; daemon stderr disabled.",
144 stderr_log.display()
145 );
146 std::process::Stdio::null()
147 }
148 };
149
150 let mut cmd = Command::new(&exe);
151 cmd.args(&cmd_args)
152 .stdin(std::process::Stdio::null())
153 .stdout(std::process::Stdio::null())
154 .stderr(stderr_cfg);
155 if crate::core::pathutil::process_is_tcc_standalone() {
161 cmd.env("LEAN_CTX_TCC_STANDALONE", "1");
162 }
163 let child = ipc::process::spawn_detached(&mut cmd)
166 .with_context(|| format!("failed to spawn daemon: {}", exe.display()))?;
167
168 let pid = child.id();
169 write_pid_file(pid)?;
170
171 std::thread::sleep(std::time::Duration::from_millis(200));
172
173 if !ipc::process::is_alive(pid) {
174 let _ = fs::remove_file(daemon_pid_path());
175 let stderr_content = fs::read_to_string(&stderr_log).unwrap_or_default();
176 let stderr_trimmed = stderr_content.trim();
177 if stderr_trimmed.is_empty() {
178 anyhow::bail!("Daemon process exited immediately. Check logs for errors.");
179 }
180 anyhow::bail!("Daemon process exited immediately:\n{stderr_trimmed}");
181 }
182
183 let addr = daemon_addr();
184 if crate::core::protocol::meta_visible() {
185 eprintln!(
186 "lean-ctx daemon started (PID {pid})\n Endpoint: {}\n PID file: {}",
187 addr.display(),
188 daemon_pid_path().display()
189 );
190 }
191
192 Ok(())
193}
194
195pub fn stop_daemon() -> Result<()> {
196 let pid_path = daemon_pid_path();
197
198 let Some(pid) = read_daemon_pid() else {
199 eprintln!("No daemon PID file found. Nothing to stop.");
200 return Ok(());
201 };
202
203 if !ipc::process::is_alive(pid) {
204 eprintln!("Daemon (PID {pid}) is not running. Cleaning up stale files.");
205 ipc::cleanup(&daemon_addr());
206 let _ = fs::remove_file(&pid_path);
207 return Ok(());
208 }
209
210 let http_shutdown_ok = try_http_shutdown();
211
212 if http_shutdown_ok {
213 for _ in 0..30 {
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 let _ = ipc::process::terminate_gracefully(pid);
223 for _ in 0..20 {
224 std::thread::sleep(std::time::Duration::from_millis(100));
225 if !ipc::process::is_alive(pid) {
226 break;
227 }
228 }
229 }
230
231 if ipc::process::is_alive(pid) {
232 eprintln!("Daemon (PID {pid}) did not stop gracefully, force killing.");
233 let _ = ipc::process::force_kill(pid);
234 std::thread::sleep(std::time::Duration::from_millis(200));
235 }
236
237 let _ = fs::remove_file(&pid_path);
238 ipc::cleanup(&daemon_addr());
239 eprintln!("lean-ctx daemon stopped (PID {pid}).");
240
241 Ok(())
248}
249
250fn try_http_shutdown() -> bool {
251 let Ok(rt) = tokio::runtime::Runtime::new() else {
252 return false;
253 };
254
255 rt.block_on(async {
256 crate::daemon_client::daemon_request("POST", "/v1/shutdown", "")
257 .await
258 .is_ok()
259 })
260}
261
262pub fn daemon_status() -> String {
263 let addr = daemon_addr();
264 if let Some(pid) = read_daemon_pid() {
265 if ipc::process::is_alive(pid) {
266 let listening = addr.is_listening();
267 return format!(
268 "Daemon running (PID {pid})\n Endpoint: {} ({})\n PID file: {}",
269 addr.display(),
270 if listening { "ready" } else { "missing" },
271 daemon_pid_path().display()
272 );
273 }
274 return format!("Daemon not running (stale PID file for PID {pid})");
275 }
276 "Daemon not running".to_string()
277}
278
279fn write_pid_file(pid: u32) -> Result<()> {
280 let pid_path = daemon_pid_path();
281 if let Some(parent) = pid_path.parent() {
282 fs::create_dir_all(parent)
283 .with_context(|| format!("cannot create dir: {}", parent.display()))?;
284 }
285 let mut f = fs::File::create(&pid_path)
286 .with_context(|| format!("cannot write PID file: {}", pid_path.display()))?;
287 write!(f, "{pid}")?;
288 Ok(())
289}
290
291pub fn init_foreground_daemon() -> Result<()> {
299 mark_foreground_daemon();
300 crate::core::layout_pin::heal();
301 crate::core::agents::reaper::spawn_reaper();
305 crate::core::intelligence_runtime::cockpit::install_if_missing_in_background();
308 let pid = std::process::id();
309 write_pid_file(pid)?;
310 Ok(())
311}
312
313pub fn cleanup_daemon_files() {
315 let _ = fs::remove_file(daemon_pid_path());
316 ipc::cleanup(&daemon_addr());
317}