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
26/// GH #2006: collecting the history resolves every touched file of the recent
27/// sessions inside the project root. On a network drive that is a round trip
28/// per path, and it ran synchronously before the server logged or answered
29/// `initialize` (95-150 s on SMB). It now runs on the warming thread, before
30/// that thread takes the cache lock, so neither the handshake nor the first
31/// tool call waits for it.
32fn warm_cache_in_background(cache: Arc<RwLock<SessionCache>>, project_root: Option<String>) {
33    if project_root.is_none() {
34        return;
35    }
36
37    if let Err(error) = std::thread::Builder::new()
38        .name("lean-ctx-cache-warm".to_string())
39        .spawn(move || {
40            let history = collect_warming_history(project_root.as_deref());
41            if history.is_empty() {
42                return;
43            }
44            let mut cache = cache.blocking_write();
45            crate::core::cache::warming::warm_cache(&mut cache, &history);
46        })
47    {
48        tracing::debug!("lean-ctx: failed to start cache warming task: {error}");
49    }
50}
51
52impl Default for LeanCtxServer {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58impl LeanCtxServer {
59    /// Creates a new server with default settings, auto-detecting the project root.
60    pub fn new() -> Self {
61        Self::new_with_project_root(None)
62    }
63
64    /// Creates a new server rooted at the given project directory.
65    pub fn new_with_project_root(project_root: Option<&str>) -> Self {
66        Self::new_with_startup(
67            project_root,
68            std::env::current_dir().ok().as_deref(),
69            SessionMode::Personal,
70            "default",
71            "default",
72        )
73    }
74
75    /// Creates a new server in Context OS shared mode for a specific workspace/channel.
76    pub fn new_shared_with_context(
77        project_root: &str,
78        workspace_id: &str,
79        channel_id: &str,
80    ) -> Self {
81        Self::new_with_startup(
82            Some(project_root),
83            std::env::current_dir().ok().as_deref(),
84            SessionMode::Shared,
85            workspace_id,
86            channel_id,
87        )
88    }
89
90    /// Ensures this MCP connection owns a durable local bus presence before
91    /// executing a tool. Construction registers eagerly; this is the
92    /// fail-closed retry for a transient startup lock or registry failure.
93    pub(crate) async fn ensure_session_presence(&self) -> Result<(), String> {
94        if self.presence_agent_id.read().await.is_some() {
95            return Ok(());
96        }
97        // Concurrent first calls (16 parallel reads on a fresh engine) each
98        // registered their own agent and timed out on the registry file lock
99        // on Windows. One registers; the rest wait and reuse its id.
100        let _init = self.presence_init.lock().await;
101        if self.presence_agent_id.read().await.is_some() {
102            return Ok(());
103        }
104
105        let project_root = self.presence_root();
106        // #1766: once `initialize` has resolved the session's role, the retry
107        // must register with it — falling back to the `context-engine`
108        // placeholder rewrote a `reviewer` presence.
109        let requested_role = self.presence_role.read().await.clone();
110        let agent_id = match requested_role.as_deref() {
111            Some(role) => crate::core::agents::AgentRegistry::register_mcp_process_as(
112                project_root,
113                role,
114                None,
115            )?,
116            None => crate::core::agents::AgentRegistry::register_mcp_process(project_root, None)?,
117        };
118        *self.presence_agent_id.write().await = Some(agent_id);
119        Ok(())
120    }
121
122    fn presence_root(&self) -> &str {
123        self.startup_project_root
124            .as_deref()
125            .or(self.startup_shell_cwd.as_deref())
126            .unwrap_or(".")
127    }
128
129    pub(crate) fn new_with_startup(
130        project_root: Option<&str>,
131        startup_cwd: Option<&Path>,
132        session_mode: SessionMode,
133        workspace_id: &str,
134        channel_id: &str,
135    ) -> Self {
136        let ttl = std::env::var("LEAN_CTX_CACHE_TTL")
137            .ok()
138            .and_then(|v| v.parse().ok())
139            .unwrap_or_else(|| {
140                let cfg = crate::core::config::Config::load();
141                crate::core::config::MemoryCleanup::effective(&cfg).idle_ttl_secs()
142            });
143
144        // Purge stale graph indices on startup to prevent serving outdated data
145        crate::core::graph_index::ProjectIndex::purge_stale_indices();
146
147        let mut startup = detect_startup_context(project_root, startup_cwd);
148        // Launchd daemons commonly start in `/`. A broad root must never become
149        // session state: it creates a cross-project mega-session and, before
150        // the bounded project index, also made every later MCP launch scan it.
151        if startup.project_root.as_deref().is_some_and(|root| {
152            crate::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(root))
153        }) {
154            tracing::debug!("lean-ctx: ignoring broad startup project root");
155            startup.project_root = None;
156        }
157        let (session, context_os) = match session_mode {
158            SessionMode::Personal => {
159                // A personal MCP server owns one fresh, PID-qualified session.
160                // Reusing a persisted project "latest" session lets concurrent
161                // servers inject each other's state during initialize.
162                let mut session = SessionState::new();
163                if let Some(ref root) = startup.project_root {
164                    session.project_root = Some(root.clone());
165                }
166                if let Some(ref cwd) = startup.shell_cwd {
167                    session.shell_cwd = Some(cwd.clone());
168                }
169                (Arc::new(RwLock::new(session)), None)
170            }
171            SessionMode::Shared => {
172                let Some(ref root) = startup.project_root else {
173                    // Shared mode without a project root is not useful; fall back to personal.
174                    return Self::new_with_startup(
175                        project_root,
176                        startup_cwd,
177                        SessionMode::Personal,
178                        workspace_id,
179                        channel_id,
180                    );
181                };
182                let rt = crate::core::context_os::runtime();
183                let session = rt
184                    .shared_sessions
185                    .get_or_load(root, workspace_id, channel_id);
186                rt.metrics.record_session_loaded();
187                // Ensure shell_cwd is refreshed (best-effort).
188                if let Some(ref cwd) = startup.shell_cwd
189                    && let Ok(mut s) = session.try_write()
190                {
191                    s.shell_cwd = Some(cwd.clone());
192                }
193                (session, Some(rt))
194            }
195        };
196
197        // Indices are NOT built eagerly here. A freshly connected agent that sits
198        // idle — or only uses ctx_read/ctx_shell/ctx_tree — must pay zero indexing
199        // cost. Heavy/search tools warm their indices lazily on first use via
200        // `index_orchestrator::ensure_warm_for_tool`, driven from dispatch (#152).
201        // An eager full graph + BM25 scan on every `new()` pegged a CPU core on
202        // each server start; multiplied across multiple agents and stdio respawns
203        // it was the root cause of the idle-high-CPU report (#453).
204
205        // Rehydrate the persistent stub index (#955) so the first unchanged
206        // re-read after this restart can collapse to the `[unchanged]` stub
207        // instead of re-delivering the whole file — gated by conversation +
208        // mtime/md5 so it can never serve a stale or cross-chat stub.
209        crate::core::read_stub_index::load();
210
211        let cache = Arc::new(RwLock::new(SessionCache::new()));
212        let bm25_cache: Arc<std::sync::Mutex<Option<crate::core::bm25_cache::Bm25CacheEntry>>> =
213            Arc::new(std::sync::Mutex::new(None));
214
215        // Register every server-local cache with the single process-wide guardian.
216        // The registry stores weak targets, so closed HTTP/MCP sessions are not retained.
217        let eviction_target = std::sync::Arc::new(
218            crate::core::eviction_orchestrator::EvictionOrchestrator::new(
219                cache.clone(),
220                bm25_cache.clone(),
221            ),
222        );
223        crate::core::eviction_orchestrator::register(&eviction_target);
224        crate::core::memory_guard::start_guard(std::sync::Arc::new(
225            crate::core::eviction_orchestrator::on_memory_pressure,
226        ));
227        warm_cache_in_background(cache.clone(), startup.project_root.clone());
228
229        let presence_root = startup
230            .project_root
231            .as_deref()
232            .or(startup.shell_cwd.as_deref())
233            .unwrap_or(".");
234        let presence_agent_id =
235            match crate::core::agents::AgentRegistry::register_mcp_process(presence_root, None) {
236                Ok(agent_id) => Some(agent_id),
237                Err(error) => {
238                    tracing::warn!("lean-ctx: failed to register MCP agent presence: {error}");
239                    None
240                }
241            };
242
243        Self {
244            cache,
245            session,
246            tool_calls: Arc::new(RwLock::new(Vec::new())),
247            call_count: Arc::new(AtomicUsize::new(0)),
248            background_tick: Arc::new(AtomicUsize::new(0)),
249            pro_trigger_check_count: Arc::new(AtomicUsize::new(0)),
250            cache_ttl_secs: ttl,
251            last_call: Arc::new(RwLock::new(Instant::now())),
252            agent_id: Arc::new(RwLock::new(None)),
253            task_envelope: Arc::new(RwLock::new(None)),
254            native_receipt_authority: None,
255            presence_agent_id: Arc::new(RwLock::new(presence_agent_id)),
256            presence_init: Arc::new(tokio::sync::Mutex::new(())),
257            presence_role: Arc::new(RwLock::new(None)),
258            client_name: Arc::new(RwLock::new(String::new())),
259            autonomy: Arc::new(crate::core::autonomy::AutonomyState::new()),
260            loop_detector: Arc::new(RwLock::new(
261                crate::core::loop_detection::LoopDetector::with_config(
262                    &crate::core::config::Config::load().loop_detection,
263                ),
264            )),
265            workflow: Arc::new(RwLock::new(
266                crate::core::workflow::load_active().ok().flatten(),
267            )),
268            ledger: Arc::new(RwLock::new(
269                crate::core::context_ledger::ContextLedger::load(),
270            )),
271            pipeline_stats: Arc::new(RwLock::new(crate::core::pipeline::PipelineStats::new())),
272            session_mode,
273            workspace_id: if workspace_id.trim().is_empty() {
274                "default".to_string()
275            } else {
276                workspace_id.trim().to_string()
277            },
278            channel_id: if channel_id.trim().is_empty() {
279                "default".to_string()
280            } else {
281                channel_id.trim().to_string()
282            },
283            context_os,
284            context_ir: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
285                crate::core::context_ir::ContextIrV1::load(),
286            ))),
287            registry: Some(std::sync::Arc::new(
288                crate::server::registry::build_registry(),
289            )),
290            rules_stale_checked: Arc::new(std::sync::atomic::AtomicBool::new(false)),
291            rules_tip_shown: Arc::new(std::sync::atomic::AtomicBool::new(false)),
292            last_seen_event_id: Arc::new(std::sync::atomic::AtomicI64::new(0)),
293            startup_project_root: startup.project_root,
294            startup_shell_cwd: startup.shell_cwd,
295            peer: Arc::new(tokio::sync::RwLock::new(None)),
296            has_client_roots: Arc::new(std::sync::atomic::AtomicBool::new(false)),
297            roots_resolved: Arc::new(std::sync::atomic::AtomicBool::new(false)),
298            roots_list_attempts: Arc::new(std::sync::atomic::AtomicU32::new(0)),
299            bm25_cache,
300            progress_sender: Arc::new(std::sync::Mutex::new(None)),
301            _eviction_target: eviction_target,
302            last_tools_config_hash: Arc::new(std::sync::atomic::AtomicU64::new(
303                crate::server::tools_config_watch::current_hash(),
304            )),
305            interaction_mode: Arc::new(std::sync::atomic::AtomicU8::new(
306                InteractionMode::Agent as u8,
307            )),
308        }
309    }
310
311    /// Clears the cache and saves the session if the TTL idle threshold has been exceeded.
312    pub async fn check_idle_expiry(&self) {
313        if self.cache_ttl_secs == 0 {
314            return;
315        }
316        let last = *self.last_call.read().await;
317        if last.elapsed().as_secs() >= self.cache_ttl_secs {
318            self.clear_idle_cache().await;
319        }
320        *self.last_call.write().await = Instant::now();
321    }
322
323    /// Idle TTL of the read cache (`memory_cleanup` / `LEAN_CTX_CACHE_TTL`); 0 = off.
324    pub fn idle_ttl(&self) -> std::time::Duration {
325        std::time::Duration::from_secs(self.cache_ttl_secs)
326    }
327
328    async fn clear_idle_cache(&self) {
329        tokio::spawn(crate::core::session::SessionState::save_shared_logged(
330            self.session.clone(),
331        ));
332        let mut cache = self.cache.write().await;
333        let redelivered = cache.count_full_delivered();
334        let count = cache.clear();
335        crate::core::cache_telemetry::record_idle(redelivered as u64);
336        // The persisted stub index outlives the warm-cache clear, so a
337        // same-conversation re-read after idle still collapses to the stub
338        // via the cold fallback (#955). Flush it now for durability.
339        crate::core::read_stub_index::persist();
340        if count > 0 {
341            tracing::info!(
342                "Cache auto-cleared after {}s idle ({count} file(s), {redelivered} forced re-delivery)",
343                self.cache_ttl_secs
344            );
345        }
346    }
347
348    /// Release what an idle server holds without waiting for the next call:
349    /// the read cache (as `check_idle_expiry` would), the resident indexes and
350    /// the allocator's free pages. Everything reloads on demand. Restarts the
351    /// TTL so the next call does not clear (and count) the cache a second time.
352    pub async fn release_idle_memory(&self) {
353        use crate::core::memory_guard;
354        let before = (
355            memory_guard::get_rss_bytes(),
356            memory_guard::allocator_stats(),
357        );
358        self.clear_idle_cache().await;
359        *self.last_call.write().await = Instant::now();
360        let _ = tokio::task::spawn_blocking(|| {
361            crate::core::eviction_orchestrator::on_memory_pressure(
362                memory_guard::PressureLevel::Hard,
363            );
364            memory_guard::jemalloc_purge();
365        })
366        .await;
367        let after = (
368            memory_guard::get_rss_bytes(),
369            memory_guard::allocator_stats(),
370        );
371        let mb = |bytes: Option<u64>| bytes.map_or_else(|| "?".into(), |b| format!("{}", b >> 20));
372        tracing::info!(
373            "[mcp-idle] released: RSS {} → {} MB, heap {} → {} MB",
374            mb(before.0),
375            mb(after.0),
376            mb(before.1.map(|s| s.0)),
377            mb(after.1.map(|s| s.0)),
378        );
379    }
380
381    async fn record_shutdown_episode(&self) {
382        let tool_calls: Vec<(String, u64)> = self
383            .tool_calls
384            .read()
385            .await
386            .iter()
387            .map(|call| (call.tool.clone(), call.duration_ms))
388            .collect();
389        if tool_calls.is_empty() {
390            return;
391        }
392
393        let session = self.session.read().await.clone();
394        let Some(project_root) = session
395            .project_root
396            .clone()
397            .or_else(|| self.startup_project_root.clone())
398        else {
399            return;
400        };
401        let agent_id = self.agent_id.read().await.clone();
402        let agent_id = match agent_id {
403            Some(agent_id) => Some(agent_id),
404            None => self.presence_agent_id.read().await.clone(),
405        };
406        let policy = crate::core::config::Config::load()
407            .memory_policy_effective()
408            .unwrap_or_default();
409        let project_hash = crate::core::project_hash::hash_project_root(&project_root);
410
411        match crate::core::episodic_memory::record_session_episode(
412            &project_hash,
413            &session,
414            &tool_calls,
415            agent_id.as_deref(),
416            &policy.episodic,
417            true,
418        ) {
419            Ok(Some(id)) => tracing::info!("lean-ctx: recorded shutdown episode {id}"),
420            Ok(None) => {}
421            Err(error) => tracing::warn!("lean-ctx: failed to record shutdown episode: {error}"),
422        }
423    }
424
425    /// Aggressive cleanup on connection drop: save session, consolidate knowledge, clear caches.
426    pub async fn shutdown(&self) {
427        self.record_shutdown_episode().await;
428        crate::core::savings_tracker::persist_session_summary();
429        if let Some(agent_id) = self.presence_agent_id.read().await.clone()
430            && let Err(error) = crate::core::agents::AgentRegistry::finish_persistent(&agent_id)
431        {
432            tracing::warn!("lean-ctx: failed to finish MCP agent presence: {error}");
433        }
434        {
435            let session = self.session.read().await;
436            let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
437            let root = session.project_root.clone();
438            drop(session);
439
440            if has_insights && let Some(ref root) = root {
441                crate::tools::startup::auto_consolidate_knowledge(root);
442            }
443        }
444        crate::core::session::SessionState::save_shared_logged(self.session.clone()).await;
445        // Persist buffered stats (incl. CEP cache-hit/session counters) before
446        // the process exits. Short bridge sessions — e.g. a phase-isolated
447        // benchmark harness that spawns a fresh server per phase — may never
448        // reach the 30s live-stats flush cadence, which left
449        // `cep.sessions`/`total_cache_hits` at 0 in stats.json despite real
450        // cache hits (#361).
451        crate::core::stats::flush();
452        // Flush the persistent stub index (#955) so an unchanged re-read survives
453        // this restart as a cheap stub instead of a full re-delivery.
454        crate::core::read_stub_index::persist();
455        {
456            let mut cache = self.cache.write().await;
457            let count = cache.clear();
458            if count > 0 {
459                tracing::info!("[shutdown] cleared {count} cached file(s)");
460            }
461        }
462        crate::core::memory_guard::force_purge();
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::LeanCtxServer;
469
470    #[tokio::test]
471    async fn missing_presence_is_registered_before_first_tool() {
472        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
473        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
474        *server.presence_agent_id.write().await = None;
475
476        server
477            .ensure_session_presence()
478            .await
479            .expect("registration retry succeeds");
480        let agent_id = server
481            .presence_agent_id
482            .read()
483            .await
484            .clone()
485            .expect("presence id is retained");
486        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
487        assert!(
488            registry
489                .agents
490                .iter()
491                .any(|agent| agent.agent_id == agent_id)
492        );
493    }
494
495    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
496    async fn concurrent_presence_retries_register_once() {
497        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
498        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
499        *server.presence_agent_id.write().await = None;
500        let before = crate::core::agents::AgentRegistry::load()
501            .map(|registry| registry.agents.len())
502            .unwrap_or(0);
503
504        let calls: Vec<_> = (0..16)
505            .map(|_| {
506                let server = server.clone();
507                tokio::spawn(async move { server.ensure_session_presence().await })
508            })
509            .collect();
510        for call in calls {
511            call.await
512                .expect("task joined")
513                .expect("presence retry succeeds");
514        }
515
516        let agent_id = server
517            .presence_agent_id
518            .read()
519            .await
520            .clone()
521            .expect("presence id is retained");
522        let registry = crate::core::agents::AgentRegistry::load().expect("registry persisted");
523        assert!(
524            registry.agents.len() <= before + 1,
525            "no duplicate registrations"
526        );
527        assert!(
528            registry
529                .agents
530                .iter()
531                .any(|agent| agent.agent_id == agent_id)
532        );
533    }
534
535    #[tokio::test]
536    async fn session_presence_failure_is_observable_to_tool_gate() {
537        let _isolated_data_dir = crate::core::data_dir::isolated_data_dir();
538        let data_dir = crate::core::data_dir::lean_ctx_data_dir().expect("data dir");
539        std::fs::create_dir_all(&data_dir).expect("data dir exists");
540        std::fs::write(data_dir.join("agents"), "not a directory").expect("poison agents path");
541
542        let server = LeanCtxServer::new_shared_with_context("/workspace/lean-ctx", "ws", "ch");
543        assert!(server.presence_agent_id.read().await.is_none());
544        assert!(server.ensure_session_presence().await.is_err());
545    }
546}