Skip to main content

lean_ctx/tools/
server_lifecycle.rs

1use std::path::Path;
2use std::sync::Arc;
3use std::sync::atomic::AtomicUsize;
4use std::time::Instant;
5use tokio::sync::RwLock;
6
7use crate::core::cache::SessionCache;
8use crate::core::session::SessionState;
9
10use super::server::{InteractionMode, LeanCtxServer, SessionMode};
11use super::startup::detect_startup_context;
12
13const MAX_WARM_SESSIONS: usize = 8;
14
15fn collect_warming_history(
16    project_root: Option<&str>,
17) -> Vec<crate::core::cache::warming::RecentFile> {
18    let Some(project_root) = project_root else {
19        return Vec::new();
20    };
21
22    let sessions = SessionState::load_recent_for_project_root(project_root, MAX_WARM_SESSIONS);
23    crate::core::cache::warming::collect_recent_files_in_project(&sessions, project_root)
24}
25
26fn warm_cache_in_background(
27    cache: Arc<RwLock<SessionCache>>,
28    history: Vec<crate::core::cache::warming::RecentFile>,
29) {
30    if history.is_empty() {
31        return;
32    }
33
34    if let Err(error) = std::thread::Builder::new()
35        .name("lean-ctx-cache-warm".to_string())
36        .spawn(move || {
37            let mut cache = cache.blocking_write();
38            crate::core::cache::warming::warm_cache(&mut cache, &history);
39        })
40    {
41        tracing::debug!("lean-ctx: failed to start cache warming task: {error}");
42    }
43}
44
45impl Default for LeanCtxServer {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl LeanCtxServer {
52    /// Creates a new server with default settings, auto-detecting the project root.
53    pub fn new() -> Self {
54        Self::new_with_project_root(None)
55    }
56
57    /// Creates a new server rooted at the given project directory.
58    pub fn new_with_project_root(project_root: Option<&str>) -> Self {
59        Self::new_with_startup(
60            project_root,
61            std::env::current_dir().ok().as_deref(),
62            SessionMode::Personal,
63            "default",
64            "default",
65        )
66    }
67
68    /// Creates a new server in Context OS shared mode for a specific workspace/channel.
69    pub fn new_shared_with_context(
70        project_root: &str,
71        workspace_id: &str,
72        channel_id: &str,
73    ) -> Self {
74        Self::new_with_startup(
75            Some(project_root),
76            std::env::current_dir().ok().as_deref(),
77            SessionMode::Shared,
78            workspace_id,
79            channel_id,
80        )
81    }
82
83    /// Ensures this MCP connection owns a durable local bus presence before
84    /// executing a tool. Construction registers eagerly; this is the
85    /// fail-closed retry for a transient startup lock or registry failure.
86    pub(crate) async fn ensure_session_presence(&self) -> Result<(), String> {
87        if self.presence_agent_id.read().await.is_some() {
88            return Ok(());
89        }
90
91        let project_root = self
92            .startup_project_root
93            .as_deref()
94            .or(self.startup_shell_cwd.as_deref())
95            .unwrap_or(".");
96        let agent_id = crate::core::agents::AgentRegistry::register_mcp_process(project_root)?;
97        *self.presence_agent_id.write().await = Some(agent_id);
98        Ok(())
99    }
100
101    pub(crate) fn new_with_startup(
102        project_root: Option<&str>,
103        startup_cwd: Option<&Path>,
104        session_mode: SessionMode,
105        workspace_id: &str,
106        channel_id: &str,
107    ) -> Self {
108        let ttl = std::env::var("LEAN_CTX_CACHE_TTL")
109            .ok()
110            .and_then(|v| v.parse().ok())
111            .unwrap_or_else(|| {
112                let cfg = crate::core::config::Config::load();
113                crate::core::config::MemoryCleanup::effective(&cfg).idle_ttl_secs()
114            });
115
116        // Purge stale graph indices on startup to prevent serving outdated data
117        crate::core::graph_index::ProjectIndex::purge_stale_indices();
118
119        let mut startup = detect_startup_context(project_root, startup_cwd);
120        // Launchd daemons commonly start in `/`. A broad root must never become
121        // session state: it creates a cross-project mega-session and, before
122        // the bounded project index, also made every later MCP launch scan it.
123        if startup.project_root.as_deref().is_some_and(|root| {
124            crate::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(root))
125        }) {
126            tracing::debug!("lean-ctx: ignoring broad startup project root");
127            startup.project_root = None;
128        }
129        let (session, context_os) = match session_mode {
130            SessionMode::Personal => {
131                // A personal MCP server owns one fresh, PID-qualified session.
132                // Reusing a persisted project "latest" session lets concurrent
133                // servers inject each other's state during initialize.
134                let mut session = SessionState::new();
135                if let Some(ref root) = startup.project_root {
136                    session.project_root = Some(root.clone());
137                }
138                if let Some(ref cwd) = startup.shell_cwd {
139                    session.shell_cwd = Some(cwd.clone());
140                }
141                (Arc::new(RwLock::new(session)), None)
142            }
143            SessionMode::Shared => {
144                let Some(ref root) = startup.project_root else {
145                    // Shared mode without a project root is not useful; fall back to personal.
146                    return Self::new_with_startup(
147                        project_root,
148                        startup_cwd,
149                        SessionMode::Personal,
150                        workspace_id,
151                        channel_id,
152                    );
153                };
154                let rt = crate::core::context_os::runtime();
155                let session = rt
156                    .shared_sessions
157                    .get_or_load(root, workspace_id, channel_id);
158                rt.metrics.record_session_loaded();
159                // Ensure shell_cwd is refreshed (best-effort).
160                if let Some(ref cwd) = startup.shell_cwd
161                    && let Ok(mut s) = session.try_write()
162                {
163                    s.shell_cwd = Some(cwd.clone());
164                }
165                (session, Some(rt))
166            }
167        };
168
169        // Indices are NOT built eagerly here. A freshly connected agent that sits
170        // idle — or only uses ctx_read/ctx_shell/ctx_tree — must pay zero indexing
171        // cost. Heavy/search tools warm their indices lazily on first use via
172        // `index_orchestrator::ensure_warm_for_tool`, driven from dispatch (#152).
173        // An eager full graph + BM25 scan on every `new()` pegged a CPU core on
174        // each server start; multiplied across multiple agents and stdio respawns
175        // it was the root cause of the idle-high-CPU report (#453).
176
177        // Rehydrate the persistent stub index (#955) so the first unchanged
178        // re-read after this restart can collapse to the `[unchanged]` stub
179        // instead of re-delivering the whole file — gated by conversation +
180        // mtime/md5 so it can never serve a stale or cross-chat stub.
181        crate::core::read_stub_index::load();
182
183        let warming_history = collect_warming_history(startup.project_root.as_deref());
184        let cache = Arc::new(RwLock::new(SessionCache::new()));
185        let bm25_cache: Arc<std::sync::Mutex<Option<crate::core::bm25_cache::Bm25CacheEntry>>> =
186            Arc::new(std::sync::Mutex::new(None));
187
188        // Register every server-local cache with the single process-wide guardian.
189        // The registry stores weak targets, so closed HTTP/MCP sessions are not retained.
190        let eviction_target = std::sync::Arc::new(
191            crate::core::eviction_orchestrator::EvictionOrchestrator::new(
192                cache.clone(),
193                bm25_cache.clone(),
194            ),
195        );
196        crate::core::eviction_orchestrator::register(&eviction_target);
197        crate::core::memory_guard::start_guard(std::sync::Arc::new(
198            crate::core::eviction_orchestrator::on_memory_pressure,
199        ));
200        warm_cache_in_background(cache.clone(), warming_history);
201
202        let presence_root = startup
203            .project_root
204            .as_deref()
205            .or(startup.shell_cwd.as_deref())
206            .unwrap_or(".");
207        let presence_agent_id =
208            match crate::core::agents::AgentRegistry::register_mcp_process(presence_root) {
209                Ok(agent_id) => Some(agent_id),
210                Err(error) => {
211                    tracing::warn!("lean-ctx: failed to register MCP agent presence: {error}");
212                    None
213                }
214            };
215
216        Self {
217            cache,
218            session,
219            tool_calls: Arc::new(RwLock::new(Vec::new())),
220            call_count: Arc::new(AtomicUsize::new(0)),
221            pro_trigger_check_count: Arc::new(AtomicUsize::new(0)),
222            cache_ttl_secs: ttl,
223            last_call: Arc::new(RwLock::new(Instant::now())),
224            agent_id: Arc::new(RwLock::new(None)),
225            task_envelope: Arc::new(RwLock::new(None)),
226            presence_agent_id: Arc::new(RwLock::new(presence_agent_id)),
227            client_name: Arc::new(RwLock::new(String::new())),
228            autonomy: Arc::new(crate::core::autonomy::AutonomyState::new()),
229            loop_detector: Arc::new(RwLock::new(
230                crate::core::loop_detection::LoopDetector::with_config(
231                    &crate::core::config::Config::load().loop_detection,
232                ),
233            )),
234            workflow: Arc::new(RwLock::new(
235                crate::core::workflow::load_active().ok().flatten(),
236            )),
237            ledger: Arc::new(RwLock::new(
238                crate::core::context_ledger::ContextLedger::load(),
239            )),
240            pipeline_stats: Arc::new(RwLock::new(crate::core::pipeline::PipelineStats::new())),
241            session_mode,
242            workspace_id: if workspace_id.trim().is_empty() {
243                "default".to_string()
244            } else {
245                workspace_id.trim().to_string()
246            },
247            channel_id: if channel_id.trim().is_empty() {
248                "default".to_string()
249            } else {
250                channel_id.trim().to_string()
251            },
252            context_os,
253            context_ir: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
254                crate::core::context_ir::ContextIrV1::load(),
255            ))),
256            registry: Some(std::sync::Arc::new(
257                crate::server::registry::build_registry(),
258            )),
259            rules_stale_checked: Arc::new(std::sync::atomic::AtomicBool::new(false)),
260            rules_tip_shown: Arc::new(std::sync::atomic::AtomicBool::new(false)),
261            last_seen_event_id: Arc::new(std::sync::atomic::AtomicI64::new(0)),
262            startup_project_root: startup.project_root,
263            startup_shell_cwd: startup.shell_cwd,
264            peer: Arc::new(tokio::sync::RwLock::new(None)),
265            has_client_roots: Arc::new(std::sync::atomic::AtomicBool::new(false)),
266            roots_resolved: Arc::new(std::sync::atomic::AtomicBool::new(false)),
267            roots_list_attempts: Arc::new(std::sync::atomic::AtomicU32::new(0)),
268            bm25_cache,
269            progress_sender: Arc::new(std::sync::Mutex::new(None)),
270            _eviction_target: eviction_target,
271            last_tools_config_hash: Arc::new(std::sync::atomic::AtomicU64::new(
272                crate::server::tools_config_watch::current_hash(),
273            )),
274            interaction_mode: Arc::new(std::sync::atomic::AtomicU8::new(
275                InteractionMode::Agent as u8,
276            )),
277        }
278    }
279
280    /// Clears the cache and saves the session if the TTL idle threshold has been exceeded.
281    pub async fn check_idle_expiry(&self) {
282        if self.cache_ttl_secs == 0 {
283            return;
284        }
285        let last = *self.last_call.read().await;
286        if last.elapsed().as_secs() >= self.cache_ttl_secs {
287            let pending_save = {
288                let mut session = self.session.write().await;
289                session.prepare_save().ok()
290            };
291            if let Some(prepared) = pending_save {
292                drop(tokio::task::spawn_blocking(move || {
293                    let _ = prepared.write_to_disk();
294                }));
295            }
296            let mut cache = self.cache.write().await;
297            let redelivered = cache.count_full_delivered();
298            let count = cache.clear();
299            crate::core::cache_telemetry::record_idle(redelivered as u64);
300            // The persisted stub index outlives the warm-cache clear, so a
301            // same-conversation re-read after idle still collapses to the stub
302            // via the cold fallback (#955). Flush it now for durability.
303            crate::core::read_stub_index::persist();
304            if count > 0 {
305                tracing::info!(
306                    "Cache auto-cleared after {}s idle ({count} file(s), {redelivered} forced re-delivery)",
307                    self.cache_ttl_secs
308                );
309            }
310        }
311        *self.last_call.write().await = Instant::now();
312    }
313
314    async fn record_shutdown_episode(&self) {
315        let tool_calls: Vec<(String, u64)> = self
316            .tool_calls
317            .read()
318            .await
319            .iter()
320            .map(|call| (call.tool.clone(), call.duration_ms))
321            .collect();
322        if tool_calls.is_empty() {
323            return;
324        }
325
326        let session = self.session.read().await.clone();
327        let Some(project_root) = session
328            .project_root
329            .clone()
330            .or_else(|| self.startup_project_root.clone())
331        else {
332            return;
333        };
334        let agent_id = self.agent_id.read().await.clone();
335        let agent_id = match agent_id {
336            Some(agent_id) => Some(agent_id),
337            None => self.presence_agent_id.read().await.clone(),
338        };
339        let policy = crate::core::config::Config::load()
340            .memory_policy_effective()
341            .unwrap_or_default();
342        let project_hash = crate::core::project_hash::hash_project_root(&project_root);
343
344        match crate::core::episodic_memory::record_session_episode(
345            &project_hash,
346            &session,
347            &tool_calls,
348            agent_id.as_deref(),
349            &policy.episodic,
350            true,
351        ) {
352            Ok(Some(id)) => tracing::info!("lean-ctx: recorded shutdown episode {id}"),
353            Ok(None) => {}
354            Err(error) => tracing::warn!("lean-ctx: failed to record shutdown episode: {error}"),
355        }
356    }
357
358    /// Aggressive cleanup on connection drop: save session, consolidate knowledge, clear caches.
359    pub async fn shutdown(&self) {
360        self.record_shutdown_episode().await;
361        crate::core::savings_tracker::persist_session_summary();
362        if let Some(agent_id) = self.presence_agent_id.read().await.clone()
363            && let Err(error) = crate::core::agents::AgentRegistry::finish_persistent(&agent_id)
364        {
365            tracing::warn!("lean-ctx: failed to finish MCP agent presence: {error}");
366        }
367        {
368            let session = self.session.read().await;
369            let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
370            let root = session.project_root.clone();
371            drop(session);
372
373            if has_insights && let Some(ref root) = root {
374                crate::tools::startup::auto_consolidate_knowledge(root);
375            }
376        }
377        let pending_save = {
378            let mut session = self.session.write().await;
379            session.prepare_save().ok()
380        };
381        if let Some(prepared) = pending_save {
382            let _ = tokio::task::spawn_blocking(move || prepared.write_to_disk()).await;
383        }
384        // Persist buffered stats (incl. CEP cache-hit/session counters) before
385        // the process exits. Short bridge sessions — e.g. a phase-isolated
386        // benchmark harness that spawns a fresh server per phase — may never
387        // reach the 30s live-stats flush cadence, which left
388        // `cep.sessions`/`total_cache_hits` at 0 in stats.json despite real
389        // cache hits (#361).
390        crate::core::stats::flush();
391        // Flush the persistent stub index (#955) so an unchanged re-read survives
392        // this restart as a cheap stub instead of a full re-delivery.
393        crate::core::read_stub_index::persist();
394        {
395            let mut cache = self.cache.write().await;
396            let count = cache.clear();
397            if count > 0 {
398                tracing::info!("[shutdown] cleared {count} cached file(s)");
399            }
400        }
401        crate::core::memory_guard::force_purge();
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::LeanCtxServer;
408
409    #[tokio::test]
410    async fn missing_presence_is_registered_before_first_tool() {
411        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
412        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
413        *server.presence_agent_id.write().await = None;
414
415        server
416            .ensure_session_presence()
417            .await
418            .expect("registration retry succeeds");
419        let agent_id = server
420            .presence_agent_id
421            .read()
422            .await
423            .clone()
424            .expect("presence id is retained");
425        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
426        assert!(
427            registry
428                .agents
429                .iter()
430                .any(|agent| agent.agent_id == agent_id)
431        );
432    }
433
434    #[tokio::test]
435    async fn session_presence_failure_is_observable_to_tool_gate() {
436        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
437        let data_dir = crate::core::data_dir::lean_ctx_data_dir().expect("data dir");
438        std::fs::create_dir_all(&data_dir).expect("data dir exists");
439        std::fs::write(data_dir.join("agents"), "not a directory").expect("poison agents path");
440
441        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
442        assert!(server.presence_agent_id.read().await.is_none());
443        assert!(server.ensure_session_presence().await.is_err());
444    }
445}